This section will introduce you to the use of Python loop statements.
The looping statements in Python are for and while.
The control structure of a Python loop statement is shown below:
while loop
The general form of the while statement in Python:
while Determines the condition:
statement
Again, you need to pay attention to colons and indentation. Also, there are no do...while loops in Python.
The following example uses thewhile to calculate the sum of 1 to 100:
#!/usr/bin/env python3 n = 100 sum = 0 counter = 1 while counter <= n: sum = sum + counter counter += 1 print("The sum of 1 through %d is: %d." % (n,sum))
The results of the implementation are as follows:
The sum of 1 through 100 is.5050
infinite loop
We can achieve infinite loops by setting the conditional expression to never be false, as shown in the following example:
#!/usr/bin/python3 var = 1 while var == 1 : # expression is always true num = int(input("Enter a number :")) print ("The number you entered is: ", num) print ("Good bye!")
Execute the above script and the output is as follows:
Enter a number :5
The number you entered is: 5
Enter a number .
You can use CTRL+C to exit the current infinite loop.
Infinite loops are useful for real-time requests from clients on the server.
The while loop uses the else statement.
Executes the else block while ... else is false:
#!/usr/bin/python3 count = 0 while count < 5: print (count, " Less than 5") count = count + 1 else: print (count, " greater than or equal to 5")
Execute the above script and the output is as follows:
0 Less than 5
1 Less than 5
2 Less than 5
3 Less than 5
4 Less than 5
5 Greater than or equal to 5
Simple statement group
Similar to the syntax of the if statement, if you have only one statement in your while loop body, you can write that statement on the same line as the while, as shown below:
#!/usr/bin/python flag = 1 while (flag): print ('Welcome to visit me!') print ("Good bye!")
Note: In the above infinite loop you can use CTRL+C to break the loop.
Execute the above script and the output is as follows:
for statement
Python for loops can iterate over any sequence of items, such as a list or a string.
The general format of a for loop is as follows:
for <variable> in <sequence>: <statements> else: <statements>
Python loop loop example:
an actual example
>>>languages = ["C", "C++", "Perl", "Python"] >>> for x in languages: ... print (x) ... C C++ Perl Python >>>
The following for example uses a break statement, which is used to jump out of the current loop body:
an actual example
#!/usr/bin/python3 sites = ["Baidu", "Google","jb51","Taobao"] for site in sites: if site == "jb51": print("Me!") break print("Cyclic data" + site) else: print("No cyclic data!") print("Complete the cycle!")
After executing the script, it will jump out of the loop body when looping to "jb51":
Cyclic data Baidu
Cyclic data Google
I am!
Complete the cycle!
range() function
If you need to iterate through a sequence of numbers, you can use the built-in range() function. It will generate the sequence of numbers, e.g.
>>>for i in range(5): ... print(i) ... 0 1 2 3 4
You can also use range to specify interval values:
>>>for i in range(5,9) : print(i) 5 6 7 8 >>>
It is also possible to make the range start with a specified number and specify a different increment (it can even be a negative number, sometimes this is called a 'step').
>>>for i in range(0, 10, 3) : print(i) 0 3 6 9 >>>
Negatives:
>>>for i in range(-10, -100, -30) : print(i) -10 -40 -70 >>>
You can combine the range() and len() functions to iterate through the indexes of a sequence, as follows.
>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ'] >>> for i in range(len(a)): ... print(i, a[i]) ... 0 Google 1 Baidu 2 Runoob 3 Taobao 4 QQ >>>
You can also use the range() function to create a list:
>>>list(range(5)) [0, 1, 2, 3, 4] >>>
break and continue statements and else clauses in loops
The break statement allows you to break out of for and while loops. If you terminate from a for or while loop, any corresponding loop else blocks will not be executed. An example is shown below:
#!/usr/bin/python3 for letter in 'Jb51net': # First instance if letter == 'e': break print ('The current letter is :', letter) var = 10 # Second example while var > 0: print ('The current variable value is :', var) var = var -1 if var == 5: break print ("Good bye!")
The output of executing the above script is:
The current letter is : J
The current letter is : b
The current letter is : 5
Current letter is : 1
The current letter is : n
Current variable value is : 10
Current variable value is : 9
Current variable value is : 8
Current variable value is : 7
Current variable value is : 6
Good bye!
The continue statement is used to tell Python to skip the remaining statements in the current loop block and continue with the next round of the loop.
#!/usr/bin/python3 for letter in 'Jb51net': # First instance if letter == 'n': # Outputs are skipped when the letter is o continue print ('Current letter :', letter) var = 10 # Second example while var > 0: var = var -1 if var == 5: # Output skipped when variable is 5 continue print ('Current variable value :', var) print ("Good bye!")
The output of executing the above script is:
Current letter : J
Current letter : b
Current letter : 5
Current letter : 1
Current letter : e
Current letter : t
Current variable value : 9
Current variable value : 8
Current Variable Value : 7
Current Variable Value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
Loop statements can have an else clause, which is executed when the loop is terminated by exhausting the list (in a for loop) or when the condition becomes false (in a while loop), but not when the loop is terminated by break.
The following is an example of a loop for querying prime numbers.
#!/usr/bin/python3 for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'Equal to', x, '*', n//x) break else: # No element found in loop print(n, "is a prime number.)
The output of executing the above script is:
2 is a prime number.
3 is a prime number.
4 equals 2 * 2
5 is a prime number.
6 equals 2 * 3
7 is a prime number.
8 equals 2 * 4
9 equals 3 * 3
pass statement
Python pass is the null statement, which is intended to maintain the structural integrity of the program.
pass doesn't do anything and is generally used as a placeholder statement, as in the following example
>>>while True: ... pass # Wait for keyboard interrupt (Ctrl+C)
Smallest class.
>>>class MyEmptyClass: ... pass
The following example executes a pass block with the letter o.
#!/usr/bin/python3 for letter in 'Jb51net': if letter == 'n': pass print ('Execute pass block') print ('Current letter :', letter) print ("Good bye!")
The output of executing the above script is:
Current letter : J
Current letter : b
Current letter : 5
Current letter : 1
Execute pass block
Current letter : n
Current letter : e
Current letter : t
Good bye!
Iterate using the built-in enumerate function.
for index, item in enumerate(sequence):
process(index, item)
an actual example
>>> sequence = [12, 34, 34, 23, 45, 76, 89] >>> for i, j in enumerate(sequence): ... print(i, j) ... 0 12 1 34 2 34 3 23 4 45 5 76 6 89
for loops over all integers 1-100
#!/usr/bin/env python3 n = 0 sum = 0 for n in range(0,101):# n Range 0-100 sum += n print(sum)
Use loop nesting to implement the 99-multiplication rule: the
#!/usr/bin/python3 # One outer layer of loop control rows #i is the number of lines i=1 while i<=9: # Inside, a layer of loops controls the number of columns in each row. j=1 while j<=i: mut =j*i print("%d*%d=%d"%(j,i,mut), end=" ") j+=1 print("") i+=1
Example of nested use of for loops:
#!/usr/bin/python3 for i in range(1,6): for j in range(1, i+1): print("*",end='') print('\r')
Output results:
*
**
***
****
*****
Sum of 1-100.
>>> sum(range(101))
5050
The difference between a while loop statement and a for loop statement using else:
1. If the else statement is used in conjunction with a while loop statement, the else statement is executed when the condition becomes False.
2. If the else statement is used in conjunction with a for loop statement, the else statement block is executed only when the for loop terminates normally!