Before we learn python You may need a thing to repeat the operation , Some may require a lot of duplicate code , It may be necessary to for To loop code .
### for example
classnumbers=['zhang','wang','su','meng']
for classnumber in classnumbers:
print(classnumber)
zhang
wang
su
meng
We set up a list to write the names of our classmates in the list , Then we set a correlation quantity classnumber, Use for Cycle through , Finally, output the correlation quantity classnumber,python Will be from the list classnumbers Repeated extraction of elements from , The final output is all the names in the list .
Of course, if you want to add more operations to the loop .
for example :
classnumbers=['zhang','wang','su']
for calssnumber in classnumbers:
print (f"{classnumber.title()},that is a good guy
Zhang,that is a good guy
Wang,that is a good guy
Su,that is a good guy
When we finish for After the cycle , Want to do something , Indent can be cancelled , Code without indentation can only be executed once
classnumbers=['zhang','wang','su']
for calssnumber in classnumbers:
print (f"{classnumber.title()},that is a good guy
print("they are good boys")
Zhang,that is a good guy
Wang,that is a good guy
Su,that is a good guy
they are good boys
When we use for When looping, we need to pay attention to indentation , We can use tab Indent , If we forget what we can reach python Unable to run , Of course, if you make extra indentation , It will not work .
The most important thing in the cycle is :, When you finish typing a sentence for Remember to add... After the cycle :, To tell python The next line is the first line of the loop . I often forget , Sometimes, after looking for the problem for a long time, I find it when I rewrite it , Turned out to be : Forget the ,: It's not easy to find out that you forget .