Detailed explanation of python for and while loops

Detailed explanation of python for and while loops

Original  January 21, 2017 12:06:12
  • 269

for loop


python_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


[python]  view plain copy  
  1. number = [ 1 , 2 , 3 , 4 , 5 ]               # create a list called number  
  2. for  i  in  number:                   # Determine whether the variable i is included in the number list  
  3.            print "The number is %d"   %i       # Print if included.      
[python]  view plain copy  
  1. <span> </span> # After the execution is completed, return to the beginning of the for statement to continue to judge whether the condition is true;  
[python]  view plain copy  
  1.   
[python]  view plain copy  
  1. Note:  The judgment statement in the for  loop can use the undefined variable i  
[python]  view plain copy  
  1. <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

python_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
[python]  view plain copy  
  1. #!/usr/bin/python  
  2. #-*-  coding:UTF-8  -*-  
  3.   
  4. i =  0 # Create a variable named i and assign the initial value to 0;                        
[python]  view plain copy  
  1. numbers = range( 0 , 6 )      # Wear a list named numbers and assign it with the range function;  
[python]  view plain copy  
  1. whilie i <  5 :             # First judge whether the expression i < 5 is true; if it is true, execute the statement in the loop body;  
[python]  view plain copy  
  1. print   numbers[i]   # print the i+1th element of the list number, (the table below of the list starts from 0);  
[python]  view plain copy  
  1. <span style= "white-space:pre;" > </span>i = i+ 1 # Increment the variable by 1;             
[python]  view plain copy  
  1.   

[python]  view plain copy  
  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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645199&siteId=291194637