This section will introduce you to
python Loop statementThe use of.
the loop statement in Python has a forAnd while. The main content of this article is
for loop statements in the Python language, which is mentioned in the
Else Loopwill be listed separately to explain.
Brief comment on:
A looping statement is an integral part of any programming language. Similarly, a forloop is an important part of Python
The following is a structure diagram of the FOR Loop statement:
First, we can loop like this.
Fruits = [' apple ', ' banana ', ' mango ']for fruit in fruits: print (Fruit.capitalize ())
This is the basic structure of the For loop, and now let's go on to a little-known feature--else clause in Python's for loop.
For loops There is also a majority of people who are unfamiliar with the ELSE clause, which executes when the loop completes normally, meaning that the loop does not encounter any break statements. When you understand where to use them, it can be very useful.
A common condition is to run a loop and search for an item, and if the item is found, we use break to jump out of the loop. There are two situations that can cause the loop to end. The first one is to find the item and break, and the second is to end the cycle naturally. Now we might want to know which one of these is the reason for the loop to complete, one way is to set a flag and then check it at the end of the loop, and the other is to use the ELSE clause.
Here is the basic structure of a for/else loop:
For item in container: if Search_something (item): # Found It! Process (item) Breakelse: # didn ' t find anything . Not_found_in_container ()
The following example comes from an official document
For n in range (2, ten): for x in range (2, N): if n% x = = 0: print (n, ' equals ', X, ' * ', n/x) break
It finds the factor between 2 to 10. Now for the interesting part, we can add an additional ELSE clause block to catch the prime number and print:
For-N in range (2, +): for x in range (2, N): if n% x = = 0: print (n, ' equals ', X, ' * ', n/x) break Els E: # loop fell through without finding a factor print (n, ' is a prime number ')
Extracurricular extension:
Python while loop statement and synchronous parsing (code example)