当前位置:网站首页>3.4 fixed number of cycles II
3.4 fixed number of cycles II
2022-06-27 15:52:00 【leeshuqing】
We Continue to learn about the fixed number of loop statements .
Last time we talked about using loops to simplify input . Next , How to simplify the output ?

In a glance , It seems difficult to write it as flexible as input . The reason lies in input Only one data is entered for each execution , Here, a summary data is output together .
So if you want to write with a loop , First of all, we should split this statement :

here , Output only output once , But the output value has been calculated . It's time to define variables again , We define a sum Save the sum .
The reason why it is split into this shape , Or is it for circular expression . Let's focus on this sum Sum up . We can imagine , Addition can only be done two by two , The specific accumulation calculation process is actually formed by the continuous accumulation of two numerical values . For example, first count two :

You may see the law of circulation , But the first one is really different .
Let's use our brains , Write it in the same way as the following :

The key here is to piece together a recyclable structure , Form a method that can be expressed circularly . therefore , We wrote the final code :
sum = 0
for i in range(len(num)):
sum = sum + num[i]
print(sum)
Students who still have questions can write down each execution process of this cycle by themselves , You will find that it is the corresponding multiple sum Cumulative statement :

For lists with fixed values , We can also go straight through for Loop to read through each element , You do not need to access... By serial number :
num = [1, 2, 3, 4, 5]
for i in num:
print(i)
Output is :
1
2
3
4
5
So the accumulation code just now can also be written as :
sum = 0
for i in num:
sum = sum + i
print(sum)The output is the value of five list elements . here i No longer serial number , It is the corresponding value . The second line here for Statement means to fetch each list element in sequence , Save to i in , So you can for Pass in cycle i Get the value of the current list element .
The complete code is :
num = [0] * 5
for i in range(len(num)):
num[i] = int(input())
sum = 0
for i in range(len(num)):
sum = sum + num[i]
print(sum)
perhaps :
num = [0] * 5
for i in range(len(num)):
num[i] = int(input())
sum = 0
for i in num:
sum = sum + i
print(sum)
for Statements can also be used simply and flexibly , Such as :
print([i for i in range(5)])
Output is :[0, 1, 2, 3, 4], It can be understood as a continuous i Finally combined into a list .
Just practiced print Output sum statement and continuous accumulation sum Of for Circulation is closely related , If you want to prevent subsequent code changes, you may for and print It changed accidentally sum, You can think about print and for Integrate together :
num = [0] * 5
for i in range(len(num)):
num[i] = int(input())
sum = 0
for i in range(len(num)):
sum = sum + num[i]
else:
print(sum)
there else Is with the for It's a whole , Throughout for At the end of the cycle , Automatically else The statement in , Therefore, the statements here usually express the closing function that needs to be performed at the end of the loop .
Next , We might as well adjust the code , See if you can continue to optimize :
First We put all the variable definitions in front of us , This does not change the logical order of the code , So it's still true .
num = [0] * 5
sum = 0
for i in range(len(num)):
num[i] = int(input())
for i in range(len(num)):
sum = sum + num[i]
print(sum)
however , Does the existing two loops look like they can be merged ?
num = [0] * 5
sum = 0
for i in range(len(num)):
num[i] = int(input())
sum = sum + num[i]
print(sum)
Absolutely. , And the function and effect are the same .
however , We observe carefully again , Do you find that there is a waste of steps ? In circulation , Each time we put the entered value into the list element , Then add the values of the list elements to sum, So why not just add the input values to sum What about China? ?
num = [0] * 5
sum = 0
for i in range(len(num)):
sum = sum + int(input())
print(sum)
in fact , Absolutely. . The code is written here , We can even do the same without lists at all :
sum = 0
for i in range(5):
sum = sum + int(input())
print(sum)
Of course , This does not mean that using lists makes no sense . Although the same effect can be achieved at this time , But all kinds of original input data have been lost , in other words , If you need to retrieve these entered values again later , The use of lists can still provide continuous access to each input value . therefore , We also need to flexibly choose the implementation of the code according to our own needs .
Supporting learning resources 、 MOOC video :
Python Big data analysis - Shu Qing Li
https://www.njcie.com/python/
边栏推荐
- Talk about redis transactions
- 利用Redis实现订单30分钟自动取消
- 手机号码的格式
- Use redis to automatically cancel orders within 30 minutes
- LeetCode每日一练(主要元素)
- 我想买固收+产品,但是不了解它主要投资哪些方面,有人知道吗?
- What is the London Silver code
- HTTP Caching Protocol practice
- 守护雪山之王:这些AI研究者找到了技术的新「用武之地」
- Weekly snapshot of substrate technology 20220411
猜你喜欢

2022年最新《谷粒学院开发教程》:8 - 前台登录功能

守护雪山之王:这些AI研究者找到了技术的新「用武之地」

PSS: vous n'êtes qu'à deux niveaux du NMS Free + Lifting point | 2021 Paper

The latest development course of grain college in 2022: 8 - foreground login function

关于TensorFlow使用GPU加速
![洛谷_P1003 [NOIP2011 提高组] 铺地毯_暴力枚举](/img/65/413ac967cc8fc22f170c8c7ddaa106.png)
洛谷_P1003 [NOIP2011 提高组] 铺地毯_暴力枚举

Teach you how to package and release the mofish Library

2022-2-16 learning the imitated Niuke project - Section 6 adding comments

Numerical extension of 27es6

Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear
随机推荐
Gin general logging Middleware
A distribution fission activity is more than just a circle of friends!
Derivation of Halcon camera calibration principle
Can polardb-x be accessed through the client of related tools as long as the client supporting JDBC / ODBC protocol is afraid?
关于快速幂
sql注入原理
Numerical extension of 27es6
Design of CAN bus controller based on FPGA (with main codes)
Use redis to automatically cancel orders within 30 minutes
带你认识图数据库性能和场景测试利器LDBC SNB
Teach you how to realize pynq-z2 bar code recognition
如果想用dms来处理数据库权限问题,想问下账号只能用阿里云的ram账号吗(阿里云的rds)
Today, Teng Xu came out with 37k during the interview. It's really a miracle. He showed me his skill
Does polardb-x currently not support self-made database service Das?
[MySQL] query valid data based on time
Design of vga/lcd display controller based on FPGA (with code)
Je veux acheter des produits à revenu fixe + mais je ne sais pas quels sont ses principaux investissements.
PSS: you are only two convolution layers away from the NMS free+ point | 2021 paper
关于TensorFlow使用GPU加速
Introduction to TTCAN brick moving