当前位置:网站首页>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/
边栏推荐
- Sigkdd22 | graph generalization framework of graph neural network under the paradigm of "pre training, prompting and fine tuning"
- Talk about redis transactions
- 【kotlin】第二天
- 16 -- 删除无效的括号
- 事务的四大特性
- OpenSSF安全计划:SBOM将驱动软件供应链安全
- 可变参数模板 Variadic Templates
- ICML 2022 ぷ the latest fedformer of the Dharma Institute of Afghanistan ⻓ surpasses SOTA in the whole process of time series prediction
- #28对象方法扩展
- Eolink launched a support program for small and medium-sized enterprises and start-ups to empower enterprises!
猜你喜欢
【kotlin】第二天
QT notes (XXVIII) using qwebengineview to display web pages
分布式Session解决方案
substrate 技术每周速览 20220411
Problems encountered in vs compilation
28 object method extension
SQL injection principle
HTTP Caching Protocol practice
Google Earth Engine(GEE)——Export. image. The difference and mixing of toasset/todrive, correctly export classification sample data to asset assets and references
一场分销裂变活动,不止是发发朋友圈这么简单!
随机推荐
Luogu_ P1007 single log bridge_ thinking
How is the London Silver point difference calculated
Teach you how to realize pynq-z2 bar code recognition
Introduction to TTCAN brick moving
Use of abortcontroller
On traversal of tree nodes
LeetCode每日一练(无重复字符的最长子串)
域名绑定动态IP最佳实践
[high concurrency] deeply analyze the callable interface
Design principles and ideas: design principles
Numerical extension of 27es6
Design of UART controller based on FPGA (with code)
[digital signal processing] discrete time signal (discrete time signal knowledge points | signal definition | signal classification | classification according to certainty | classification according t
SIGKDD22|图“预训练、提示、微调”范式下的图神经网络泛化框架
Indexeddb learning materials
一场分销裂变活动,不止是发发朋友圈这么简单!
About fast exponentiation
Principle Comparison and analysis of mechanical hard disk and SSD solid state disk
Hyperledger Fabric 2. X custom smart contract
Does polardb-x currently not support self-made database service Das?