[Basic knowledge of python] 5. for loop and while loop

Preface

In the previous level, we learned about two new data types: lists and dictionaries.

In this level, the theme we want to learn is [Loop]. Looping means: repeating one thing many times.

Insert image description here
Everyone’s life and work are full of cycles. Many times, cycles mean repetition and boring. For example, you have to manually enter the personal information of 200 employees, or she has to explain the same thing over and over again to people who are not serious, or her life is unchanged and like a pool of stagnant water.

In the end, you need to break the cycle of a static life yourself, but when it comes to work, we can let the computer help us. Unlike humans, computers are not afraid of hardship or fatigue. They can repeat boring things thousands of times as long as they can find the answer you want.

This is precisely where programming liberates humans. For example, if you need to download many, many pictures, you originally have to do it manually, but the computer can help you download the pictures one by one according to certain rules through [Loop], and you can just rest aside. Computers are better at repetitive tasks than you are.

For another example, as an operator, you may need to dissolve many user groups. Originally, you have to manually click one by one, but the computer can help people dissolve one by one according to certain rules through [loop]. Computers can do repetitive tasks with less effort than you.

Now if you look at the word "circulation" again, is it different from the beginning?

Why are computers so good at doing repetitive tasks? Note that it means "super good and super fast", not just "can do the job and doesn't complain".

The principle is actually because the [loop statements] in the code allow the computer to execute instructions repeatedly and automatically.

Insert image description here
To achieve "repeated and automatic code execution", there are two loop statements for us to choose from: one is the for...in... loop statement, and the other is the while loop statement.

"Loop" is very important in computers and is the most basic programming knowledge. In order to explain it more clearly, we have divided the loop chapter into two levels. In this level, we will have a preliminary understanding of the two loop statements and learn their simple applications.

Without further ado, let’s take a look at the first loop method: the for…in… loop, which is also referred to as the for loop.

for…in…loop statement

Do you still remember the example of the class teacher’s roll call in the previous level? What was supposed to be a task that had to be repeated 50 times ended up being 3 lines of code.

student = ['党志文', '浦欣然', '罗鸿朗', '姜信然', '居俊德', '宿鸿福', '张成和', '林景辉', '戴英华', '马鸿宝', '郑翰音', '厉和煦', '钟英纵', '卢信然', '任正真', '翟彭勃', '蒋华清', '双英朗', '金文柏', '饶永思', '堵宏盛', '濮嘉澍', '戈睿慈', '邰子默', '于斯年', '扈元驹', '厍良工', '甘锐泽', '姚兴怀', '殳英杰', '吴鸿福', '王永年', '宫锐泽', '黎兴发', '朱乐贤', '关乐童', '养永寿', '养承嗣', '贾康成', '韩修齐', '彭凯凯', '白天干', '瞿学义', '那同济', '衡星文', '公兴怀', '宫嘉熙', '牧乐邦', '温彭祖', '桂永怡']
for i in student:
    print(i+'在不在?')

Lines 2-3 here are the for loop.

Let’s first look at the simplest for loop code to understand its format:

Insert image description here
Come on, first run the sample code in the picture.

for i in [1,2,3,4,5]:
   print(i)

operation result:

1
2
3
4
5

All the numbers in the list appear on the terminal in sequence, right? Let’s use an analogy in vernacular to better understand the meaning of this code:

Insert image description here

for i in [1,2,3,4,5]:
   print(i)

#有一群数字在排队办业务,也就是列表[1,2,3,4,5]
#它们中的每一个被叫到号的时候(for i in),就轮流进去一个空房间办业务
#每一个数字进去房间之后,都对计算机说:“喂,我要办这个业务:帮忙把我自己打印出来”,也就是print(i)
#然后计算机忠实的为每一个数字提供了打印服务,将1,2,3,4,5都打印在了屏幕上

The three main points of the for loop are: 1. Empty room; 2. A group of people waiting to do business; 3. Business process

Let’s look at them one by one:

for loop: empty room

for i in [1,2,3,4,5]:  #i是“空房间”
   print(i)

The scientific name of the empty room is [item], you can think of it as a variable. So first, we need to give the room a name, which is the "variable name".

Why do I always use i? Because the English word is item, so i is a common name. But actually you can name this room whatever you want.

Come on, just run the code and try it.

for i in [1,2]:
    print(i)

for number in [1,2]:
    print(number)

for LOVE in [1,2]:
    print(LOVE)

operation result:

1
2
1
2
1
2

Are all three results the same? That's right, no need to be restricted by names.

After the for loop ends, we can still use this room, but who is in the room at this time? Please run the code to experience it:

for i in [1,2,3,4,5]:
    print(i)

print('事情全部办完了!现在留在空房间里的人是谁?')
print(i)

operation result:

1
2
3
4
5
事情全部办完了!现在留在空房间里的人是谁?
5

It turned out that after the business was over, the last 5 who walked in stayed in the room and was printed.

After figuring out what an "empty room" is, let's look at the next point:

for loop: a group of people queuing up to do business

Insert image description here
The "group of people queuing up to do business" we just saw all appear in the form of a list: [1,2,3,4,5]. What other data types also belong to "a group of people queuing up to do business"?

I think you've guessed it, it's a dictionary. Let’s directly experience the effect of the code running:

dict = {
    
    '日本':'东京','英国':'伦敦','法国':'巴黎'}

for i in dict:
    print(i)

operation result:

日本
英国
法国

We used print(i) to print out the "empty room" i, and found that i would receive each [key] in the dictionary one by one.

So what doesn’t belong to “a group of people queuing up to do business”? Please take a guess:

Which of the following options cannot be placed in the for i in a: loop?

Aa =[1,3,50,9]
Ba=5
Ca ={'Master':'Tang Monk','Elder Brother':'Sun Wukong','Second Senior Brother':'Zhu Bajie','Third Junior Brother':'Sha Monk'}
Da='Wu Cheng'en'

The answer is: B
dictionary, list and string 'Wu Chengen' are all a group of people queuing up to do business, but a = 5 is not.

Haha, were you a little hesitant when you answered the question? After seeing the answer, you were a little confused: Why is 'Wu Cheng'en' also acceptable?

Don't doubt that strings also belong to "a group of people queuing up to do business." For example, the words "Wu Chengen" are like a family of three, but when they go into an empty room to do business, the family can go in one by one. Come and try it.

for i in '吴承恩':
    print(i)

operation result:

吴
承
恩

Integers and floating point numbers do not belong to "a group of people queuing up to do business". If they are placed in a for loop, the code will report an error.

Please try the error code. After encountering the error, you can modify the code to the correct one (just change a and b into string types), or skip it directly.

a = 100
b = 0.01

for i in a:
    print(i)

for i in b:
    print(i)

Now we understand: lists, dictionaries, and strings can all be "a group of people queuing up to do business."

for i in [1,2,3,4,5]:  
   print(i)

It’s still this code. You should already know the result of running the code. 1, 2, 3, 4, and 5 appear in sequence. In other words, when this group of people in line enter the empty room one by one, everyone will complete their business.

The scientific name of this process in Python is [traversal].

In fact, the word traversal has already appeared in ancient Chinese:

Insert image description here
It's just that the ancients traversed famous mountains and rivers, seeking knowledge one by one; while Python traverses data structures (lists, dictionaries, etc.) and accesses the data one by one.

In addition to the three data types of lists, dictionaries, and strings, we can also traverse other data collections. For example, the range() function is often used together with the for loop.

range() function

# 请直接运行代码
for i in range(3):
    print(i)

operation result:

0
1
2

After running, you see the integers 0, 1, 2, right? Using the range(x) function, you can generate a sequence of integers from 0 to x-1.

There are many more uses for it, let’s take a look at this code and run:

for i in range(13,17):
    print(i)

operation result:

13
14
15
16

Using the range(a,b) function, you can generate a sequence of integers that takes the head but not the tail.

You may want to ask, why should I take these integers out of nothing? Well, that's a good question. Let’s look at another piece of code and run it:

for i in range(1,10):
    for j in range(1,10):
        print(str(i)+'*'+str(j)+'='+str(i*j))
print('我很棒')

operation result:

1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18
3*1=3
3*2=6
3*3=9
3*4=12
3*5=15
3*6=18
3*7=21
3*8=24
3*9=27
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*8=32
4*9=36
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
6*1=6
6*2=12
6*3=18
6*4=24
6*5=30
6*6=36
6*7=42
6*8=48
6*9=54
7*1=7
7*2=14
7*3=21
7*4=28
7*5=35
7*6=42
7*7=49
7*8=56
7*9=63
8*1=8
8*2=16
8*3=24
8*4=32
8*5=40
8*6=48
8*7=56
8*8=64
8*9=72
9*1=9
9*2=18
9*3=27
9*4=36
9*5=45
9*6=54
9*7=63
9*8=72
9*9=81
我很棒

Say important things three times, haha. Like this, with the range() function, when you want to repeat a piece of code n times, you can directly use for i in range(n) to solve the problem.

Let’s practice: if you want to repeatedly print “I missed him on the nth day after Shuhuan left”, and n ranges from 0 to 10, how would you write it?

Reference answer:

for i in range(11):
    print('书恒走的第'+str(i)+'天,想他')

operation result:

书桓走的第0天,想他
书桓走的第1天,想他
书桓走的第2天,想他
书桓走的第3天,想他
书桓走的第4天,想他
书桓走的第5天,想他
书桓走的第6天,想他
书桓走的第7天,想他
书桓走的第8天,想他
书桓走的第9天,想他
书桓走的第10天,想他

Did you do it right?

There is another usage of the range() function. Let’s run it directly to experience it:

for i in range(0,10,3):
    print(i)

operation result:

0
3
6
9

Have you observed any patterns? Here range(0,10,3) means: counting from 0 to 9 (taking the head but not the tail), the step size is 3.
Insert image description here
Okay, let's do it in practice: Please use a for loop to complete the calculation of multiplying integers from 1 to 100 by 5, and print it out. The effect will be like this:

5
10
15
20
……(中间过程省略)
490
495
500

How would you write the for loop code?

Before we start writing code, we need to create a list of integers from 1 to 100. What is the correct way to write it?

range(1,101 )

That's right! range(1,101) represents a list of integers from 1-100, excluding 101.
Please start writing code:

Reference answer:

for i in range(1,101):
    print(i*5)

Let’s finally understand the third key point of the for loop:

for loop: service process

Insert image description here
Let's take the following code as an example:

for i in [1,2,3,4,5]:print(i*5)

In these two lines of code, in means to take values ​​sequentially from "a group of people queuing up to do business" (strings, lists, dictionaries, etc.), which we have just learned.

During the cycle, "a group of people queuing up to do business" will be taken out one by one, and then walk into room i to handle business.

But what about the work process? The process here is very simple, all are print(i*5). Then in the case of i=1, execute the process once; in the case of i=2, execute the process again...and continue to execute it until i=5, thus completing all the tasks for this group of people:

Insert image description here
The scientific name of "service process" is [for clause]. The format is to start a new line after [colon] and write the command with [indent].

Format is a "little thing" that cannot be overemphasized in programming, so here we emphasize the format of the for loop:

Insert image description here
At this point, you have mastered the basic syntax of for loop, let's do some more exercises.

Suppose you want to make a big purchase, let Xiao Ming buy vinegar, Xiao Hong buy oil, Xiao Bai buy salt, and Xiao Zhang buy rice; let's first write these things into a dictionary: d = {'Xiao Ming':'vinegar','Xiao Hong':'oil','Xiaobai':'salt','Xiao Zhang':'rice'}

If we print out the items that these four people want to buy in sequence, we need to write 4 print statements:

d={
    
    '小明':'醋','小红':'油','小白':'盐','小张':'米'}
print(d['小明'])
print(d['小红'])
print(d['小白'])
print(d['小张'])

Please use for loop to replace the above repetitive code and achieve the same effect.

Reference answer:

#请直接运行代码
d = {
    
    '小明':'醋','小红':'油','小白':'盐','小张':'米'}

for i in d:
    print(d[i])

Did you do it right? If you are a little unsure, you can go back and fill up on the relevant knowledge of "Dictionary".

At this point, the three main points of the for loop have been explained:

Insert image description here
Okay, we've finished learning the for loop, let's look at another way of looping.

while loop

Let’s first take a look at what a while loop looks like:

Insert image description here
Guess what the result of running the code in the picture will be?

#请直接运行代码
a = 0
while a < 5:
    a = a + 1
    print(a)

operation result:

1
2
3
4
5

Or 1,2,3,4,5 appear in sequence, right? Let’s also explain this code in vernacular.

Unlike the for loop statement, the while statement does not have an "empty room", nor does it "finish a group of people queuing up to do business." It is "under certain conditions" and "acting in accordance with the process".

Insert image description here

a = 0                #先定义变量a,并赋值
while a < 5:         #设定一个放行条件:a要小于5,才能办事
    a = a + 1  # 满足条件时,就办事:将a+1
    print(a)   # 继续办事:将a+1的结果打印出来 

Obviously, the while loop has two main points: 1. Release conditions; 2. Service process. Let’s look at the first one first.

while loop: release condition

While means "when" in English, while is followed by a condition. When the condition is met, the code inside the while (while clause) will be executed in a loop.

So the while loop is essentially like a checkpoint: as long as things meet the conditions, then "do things according to the process" over and over again.

Just like in the example above, as long as the condition a<5 is true, the process will continue (print out the result of a+1) until the condition is not true, and the service process will stop.

a = 0
while a < 5:
    a = a + 1
    print(a)

Similarly, the while statement should also pay attention to the code specifications:

Insert image description here
Like the for loop, colons and indentation of internal code are essential. ╭(╯^╰)╮If you write irregularly, the computer will report an error to you, and then you will be stuck in an inexplicable place for a long time...

Below, we use a fun case to illustrate the specific usage of while. I wonder if students have read Jin Yong's martial arts novel "The Legend of the Condor Heroes"?

The protagonist in the novel, Xiao Longnu (the leader of the Ancient Tomb Sect), has lived in an ancient tomb on Zhongnan Mountain since she was a child. This sect has a rule that unless a man is willing to die for the leader, the leader can never leave the tomb.

In Python, the logic of this story is translated as: when (while) no man is willing to die for Xiao Longnu, Xiao Longnu will always live in the ancient tomb. This is a cycle. Only when the condition (no man is willing to die for Xiao Longnu) is false, the cycle can be broken, and Xiao Longnu can leave the ancient tomb and go down the mountain.

I will write this code first, you can take a look~

man = ''  # 注:''代表空字符串
while man != '有':  #注:!=代表不等于
​    man = input('有没有愿意为小龙女死的男人?没有的话就不能出古墓。')
print('小龙女可以出古墓门下山啦~')

Line 1 of code: defines the variable man as an empty string. Before using a variable, you must first define the variable and assign a value to the variable. We will continue to use the variable man below.

Line 2 of code: There is a condition after while. When this condition is met, that is, when man != 'yes', the process is released and the work is done. Start executing the code inside the loop, that is, the code on line 3, and start asking.

Line 3 of code: Ask if any man is willing to die for Xiao Longnu? After entering the information, return to the second line of code and re-judge whether the condition is true or false. The while loop does not end until the condition is judged to be false, that is, man == 'has'.

Line 4 of code: The code after the while loop ends, which is also the code outside the loop. Because when a man is willing to die for Xiao Longnu, the condition after while will be false. At this time, the program will end the loop and run the fourth line of code.

Let's run it. You also need to enter the content. You can enter any data first. As long as you enter something other than Yes, the code will keep looping; until you enter Yes, the loop will end.

man = ''  # 注:这个''代表空字符串
while man != '有':
    man = input('有没有愿意为小龙女死的男人?没有的话就不能出古墓。')
print('小龙女可以出古墓门下山啦~')

operation result:

有没有愿意为小龙女死的男人?没有的话就不能出古墓。1
有没有愿意为小龙女死的男人?没有的话就不能出古墓。hah
有没有愿意为小龙女死的男人?没有的话就不能出古墓。没有
有没有愿意为小龙女死的男人?没有的话就不能出古墓。有
小龙女可以出古墓门下山啦~

Fortunately, the hero of the novel, Yang Guo, came to the Tomb of the Living Dead by chance and fell in love with Xiao Longnu. Yang Guo had a deep affection for Xiao Longnu and was willing to die for her, so after meeting the sect's rules, Xiao Longnu could leave the ancient tomb and go down the mountain.

Okay, after you have experienced the logic of the while loop, now I want to ask you to practice it yourself. Don’t worry, it’s not that difficult. If you have any questions, take a look at Xiao Longnu’s example.

The story of this sudden change of style is as follows: the door of your house is a password door, and the password is your birthday 816. When the wrong password is entered, it will prompt "Please try entering the password:". Until the password is entered correctly, it will prompt "Welcome home!".

The running effect of the terminal should be similar to this:

请尝试输入密码:
123
请尝试输入密码:
456
请尝试输入密码:
789
请尝试输入密码:
……(中间过程省略)
816
欢迎回家!

Please complete this code:

How about it, have you written it down?
The reference answer is this:

password = ''  # 变量password用来保存输入的密码

while password != '816':
    password = input('请尝试输入密码:')

print('欢迎回家!')

So what, maybe you have a little doubt (probably you haven't noticed it), whose birthday is 816? Let me tell you secretly, it is the birthday of Li Ruotong, the heroine of the 1995 version of "The Legend of the Condor Heroes", the eternal Little Dragon Girl.

Insert image description here
Okay, let’s get down to business. Let’s look at the second key point of the while loop: the service process.

while loop: work process

While loop, when the conditions are met, the code will be executed in a loop after another.

Let’s take a multiple-choice question. Please look at the code to answer the question:

a = 0

while a < 5:
​    a = a + 1
print(a)

What is the result of running the terminal?

Bingo! Correct answer, a starts from 0 and increases by 1 each time through the loop. When a is added to 5, the condition of the loop will not be met and the checkpoint will not pass, so the loop will end. Finally print a, which is 5.

This question is very similar to the example question at the beginning. The only difference is whether print(a) is indented.

# 之前的例题
a = 0

while a < 5:
​    a = a + 1
    print(a)

# 本题
a = 0

while a < 5:
​    a = a + 1
print(a)

When there is indentation, print(a) is also the "service process" in the loop and will print the numbers one by one. When there is no indentation, the "service flow" in the loop can only be addition, and print(a) will only print the last number at the end of the loop.

A little troublesome, right? Let’s break it down and see what each line of code means:

a = 0  # 定义了一个变量a

while a < 5:  # 当a小于5的时候,就自动执行后续缩进部分的语句
    print('现在a的值是:' + str(a)) #加一个print看看现在的a是多少
    a = a + 1  # 每执行一次循环,变量a的值都加1
    print('加1后a的值是:' + str(a)) #加一个print看看加1后的a是多少
print(a)

It can be seen that in the last round of the loop, a=4, and then the value of a is finally equal to 5 after adding 1:

Insert image description here
Therefore, the indented [while clause] is the "service process" that will be executed in a loop. You should almost understand this~

Then, let's do a little exercise again.

Previously, we used a for loop to solve the problem of "multiplying 1 to 100 by 5":

for i in range(1,101):
    print(i*5)

If we use a while loop now, how should we write it? Come and try it.

Reference answer:

i = 1
while i<101 :
    print (i*5)
    i = i+1

At this point, you have learned all the knowledge about for loops and while loops~

Both the for loop and the while loop can help us complete repetitive tasks. So what is the difference between the two loops? When to use for and when to use while? Let's compare.

Comparison of two cycles

The biggest difference between a for loop and a while loop is [whether the workload of the loop is determined]. The for loop is like an empty room handling business in sequence, and does not get off work until [all the work is completed]. But the while loop is like a checkpoint release, [keep working when the conditions are met], and close the checkpoint until the conditions are not met.

So, when we [the workload is determined], we can let the for loop complete the repetitive work. On the contrary, [when the workload is uncertain] you can let the while loop work:

# 适合用for...in...循环
for i in '神雕侠侣':print(i)

# 适合用while循环
password = ''
while password != '816':
​     password = input('请尝试输入密码:')

To split the string 'The Legend of Condor Heroes' into characters and print them out one by one, this matter [the workload is determined], it is suitable to use a for loop.

As for the matter of "entering the password and judging whether the entered password is correct", we don't know how many times we have to judge to get the correct password, so [the workload is uncertain] and it is suitable to use a while loop.

However, there is a situation where both for loops and while loops can solve the problem, and that is [doing one thing N times]:

# 直接运行代码即可

#用for循环把诗句打印3遍
for i in range(3) :
    print('明日复明日,明日何其多。')

#用while循环把诗句打印3遍
j = 0
while j<3 :
    
    print ('明日何其多,明日何其多。')
    j =j+1

You'll see, you can do both. However, the code of the for loop is relatively simpler.

Let’s summarize when to use for and when to use while:

Insert image description here
Okay, so far, we have finished covering the most basic knowledge. Coming to the end of this level, I want to talk about "circulation".

As mentioned at the beginning, computers can help us do many complicated and repetitive tasks. When computers free up our hands, some time is freed up in our ordinary days.

What will you do with all this time?

There was a time when I chose to let my thoughts run wild and see where my edge was.

Later, I used the extra time to return to life, learn to spend time with my family, and learn to express my cherishment.

And at this time, here, every you at this moment is the choice I make for these times.

There is still a long way to go, see you at the next level.

Guess you like

Origin blog.csdn.net/qq_41308872/article/details/132692557