Detailed explanation of python for and while loops
for loop
1. For statement format
for expression 1 in expression 2: # Determine whether expression 1 is in the range included in expression 2
Statement 1 # If the previous condition is true, execute the following statement
Statement 2
...
statement n
Two, for loop example
- number = [ 1 , 2 , 3 , 4 , 5 ] # create a list called number
- for i in number: # Determine whether the variable i is included in the number list
- print "The number is %d" %i # Print if included.
- <span> </span> # After the execution is completed, return to the beginning of the for statement to continue to judge whether the condition is true;
- Note: The judgment statement in the for loop can use the undefined variable i
- <span> </span> In fact, the variable is defined at the beginning of the for loop, and will be redefined every time the loop begins;
while loop
First, the while statement format
while Judgment condition: # If the judgment condition is true, the execution statement in the loop body is executed; The judgment condition is true can be any expression, any non-zero, non-null (null) value;
execute statement
2. While example
- #!/usr/bin/python
- #-*- coding:UTF-8 -*-
- i = 0 # Create a variable named i and assign the initial value to 0;
- numbers = range( 0 , 6 ) # Wear a list named numbers and assign it with the range function;
- whilie i < 5 : # First judge whether the expression i < 5 is true; if it is true, execute the statement in the loop body;
- print numbers[i] # print the i+1th element of the list number, (the table below of the list starts from 0);
- <span style= "white-space:pre;" > </span>i = i+ 1 # Increment the variable by 1;
Summarize
>>>
Try to use less while loops, most of the time for loops are better
>>>
for loop is used to match a specific set and loop # similar to the switch case statement in C language;
>>>
while loop is used to judge the condition is true and loop
>>>
appendix
Learning and Reference Links
(1) python tutorial: http://www.runoob.com/python/python-while-loop.html
(2) python online programming website: https://penjee.com/tutorial