当前位置:网站首页>3.3 one of the fixed number of cycles
3.3 one of the fixed number of cycles
2022-06-27 15:52:00 【leeshuqing】
Except for sequential statements 、 Outside the conditional judgment statement , There is one last control statement , Circular statement . Let's first look at the simplest one : A fixed number of cycles .
Loops are a powerful control statement , It allows us to execute a piece of code repeatedly , And end under certain conditions . For example, in data analysis , We need to do the same numerical processing for all records , So this is a cycle , Loop through each record , Treat separately , After all records are processed, it can be ended .

Let's start with an example . Suppose you want to complete 5 How to write the input and addition of integer data ? With the above variable definition foundation , The most intuitive method is to repeatedly paste the code just now , This is a good opportunity for beginners , Be familiar with the writing of code and the flexibility of operation .
num1 = int(input())
num2 = int(input())
num3 = int(input())
num4 = int(input())
num5 = int(input())
print(num1 + num2 + num3 + num4 + num5)
You can try continuous input 5 It's an integer , Finally, you can see the total output .

The green text in the lower pane is the entered integer , Black is the output content .
No problem though , But I don't feel like I have done a lot of repetitive work ! And if you want to enter 100 How about the number ? With more flexibility , The number of entries is not even completely certain , For example, suppose the input number is 0, It means that the accumulation process ends ? Or the sum exceeds 100 It's over, too , How to deal with these ?

To be sure , These operations make it impossible for you to do it in this repetitive way in your code , It is not realistic to input too many numbers , The latter flexibility makes it even more difficult to determine how many times to repeat , Because it is affected by user input data at this time , This is also unpredictable in programming .
Back to the code , You will also notice that the code is highly similar , Only the variable names are different , And it seems that the serial number is different .

Because we represent these variables separately , Although the serial number is continuous , But in essence , These variable names are no different from other random names , There is no continuous access method that can be used between them .
Could you consider taking this number as the serial number list ? We might as well change these different variable names first . such as :

At this point we can notice , The different variables are already very similar , Only one serial number in square brackets changes independently .
This is actually a list (list) The idea of . We define lists , Because we need lists . The list , It's a set of data , Usually the type is the same , For example, here are all integers , But there are more , They all use a single name to denote , But they are distinguished from each other by different serial numbers .
num[1] = int(input())
num[2] = int(input())
num[3] = int(input())
num[4] = int(input())
num[5] = int(input())
print(num[1] + num[2] + num[3] + num[4] + num[5])
However, running this code will still cause errors , It will be prompted to num No definition , It's a list num No definition .

To do this, we need to add a special list definition at the beginning :
num = [0] * 5
num[1] = int(input())
num[2] = int(input())
num[3] = int(input())
num[4] = int(input())
num[5] = int(input())
print(num[1] + num[2] + num[3] + num[4] + num[5])
The first line of code defines a list , The name is num, Each list element is 0, share 5 List elements , It can be seen as 5 Integer variables grouped together , But there is no direct variable name . But it can go through num[1] and num[2] To read .
But running this code produces a common error “list assignment index out of range( The list serial number is out of bounds )”:

It's easier to say , The serial number used in our list is out of bounds . The reason is also simple , The first sequence number in the default list is from 0 Start , This is very strange , Such is the case , This is an old tradition of computer language .
therefore , Let's change it to : There's no problem this time , The function is the same , Just the serial number from 0 Start writing .
num = [0] * 5
num[0] = int(input())
num[1] = int(input())
num[2] = int(input())
num[3] = int(input())
num[4] = int(input())
print(num[0] + num[1] + num[2] + num[3] + num[4])
With this foundation , Next, how to simplify the input ? For simplicity , We can imagine that the input function should look like this :

Please note that , The serial number here is for flexibility , We also changed it to a variable i, Because the value of a variable can be changed flexibly . The reader may ask , The variable name cannot be too simple ? you 're right , however , This i It's also a habit . Generally, the serial number of the list usually uses i、j、k And so on .
here i In order to express the 5 Elements , You need to have 0、1 To 4 Wait for multiple values . Then we can use the loop to express the process , The method is very fixed . The complete code is :
num = [0] * 5
for i in range(5):
num[i] = int(input())
print(num[0] + num[1] + num[2] + num[3] + num[4])
there for Is a loop statement ,range Is a function , Scope of representation , When the parameter is 5 When , Represents automatic generation 0 To 4 total 5 Elements , Just like the list 5 Element serial numbers correspond to .

in Express i Take each serial number in turn , Execute the statements in the loop each time , But the serial number is different every time , Just realize the previous writing 5 The same effect as the second input . Same as the previous branch judgment , Here, the colon is also used to indicate the end of the loop condition , Indent the statement block in the loop .
Of course , There are also more flexible improvements :
num = [0] * 5
for i in range(len(num)):
num[i] = int(input())
print(num[0] + num[1] + num[2] + num[3] + num[4])
Here we use len(num) To replace the 5, The advantage of this is to avoid changing the length of the list in the future , Forget that there is no corresponding modification at this time, resulting in an error that is difficult to find , This is also an important issue that we should pay attention to when writing code , That is, to ensure the modifiability of the code , Try to avoid “ Hard encoding ”, And adopt this flexible and dynamic way to .
for It's actually one of the simplest loop statements , Cycle means repetition , But the variables are changed appropriately in iterations , There is change in unchanging , Achieve a flexible effect . Through execution you will find , This loop statement is like a processing machine , As production goes on , Continuously generate some statement blocks , Each statement block just meets our predetermined requirements .
Of course , You may have noticed , Then why is the last output statement so troublesome ? Let's hear the decomposition next time .
Supporting learning resources 、 MOOC video :
Python Big data analysis - Shu Qing Li
https://www.njcie.com/python/
边栏推荐
- 实现简单的三D立方体自动旋转
- Weekly snapshot of substrate technology 20220411
- 一场分销裂变活动,不止是发发朋友圈这么简单!
- LeetCode每日一练(主要元素)
- Design of vga/lcd display controller based on FPGA (with code)
- 固收+产品有什么特点?
- 带你认识图数据库性能和场景测试利器LDBC SNB
- In the Alibaba cloud experiment, if the k8s forwards to port 3306 and the MySQL client is turned on, it will terminate abnormally. What is the reason?
- Teach you how to realize pynq-z2 bar code recognition
- 漏洞复现----34、yapi 远程命令执行漏洞
猜你喜欢

SIGKDD22|图“预训练、提示、微调”范式下的图神经网络泛化框架

Today, Teng Xu came out with 37k during the interview. It's really a miracle. He showed me his skill

QT notes (XXVIII) using qwebengineview to display web pages
![Luogu_ P1008 [noip1998 popularization group] triple strike_ enumeration](/img/9f/64b0b83211bd1c615f2db9273bb905.png)
Luogu_ P1008 [noip1998 popularization group] triple strike_ enumeration

Numerical extension of 27es6

Top ten Devops best practices worthy of attention in 2022

Programming skills: script scheduling

LeetCode每日一练(杨辉三角)

关于TensorFlow使用GPU加速

Why can't the start method be called repeatedly? But the run method can?
随机推荐
Use of abortcontroller
Different perspectives
OpenSSF安全计划:SBOM将驱动软件供应链安全
NFT双币质押流动性挖矿dapp合约定制
Eolink 推出面向中小企业及初创企业支持计划,为企业赋能!
Problems encountered in vs compilation
Cannot determine value type from string ‘<p>1</p>‘
ICML 2022 | 阿⾥达摩院最新FEDformer,⻓程时序预测全⾯超越SOTA
洛谷_P1003 [NOIP2011 提高组] 铺地毯_暴力枚举
手机号码的格式
Openssf security plan: SBOM will drive software supply chain security
关于 Spartacus 的 sitemap.xml 问题
PSS: you are only two convolution layers away from the NMS free+ point | 2021 paper
机械硬盘和ssd固态硬盘的原理对比分析
Design of spread spectrum communication system based on FPGA (with main code)
substrate 技术每周速览 20220411
老师能给我说一下固收+产品主要投资于哪些方面?
Knowledge map model
创建数据库并使用
Google Earth Engine(GEE)——Export. image. The difference and mixing of toasset/todrive, correctly export classification sample data to asset assets and references