Use for statement
Example 6.3 uses a for statement
The code is as follows |
Copy Code |
#!/usr/bin/python # Filename:for.py For I in range (1, 5): Print I Else print ' For loop are over ' Output $ python for.py 1 2 3 4 The For loop are over |
Jump out for Loop
Continue
The code is as follows |
Copy Code |
# Encoding=utf-8
For x in range (10): If x==5: Continue
Print X |
The above loop uses continue to jump out of this cycle, so only when the x==5 out of this cycle, and then continue next, so the print X statement only in the x==5 when the other values are executed to the
Break
The code is as follows |
Copy Code |
# Encoding=utf-8 For x in range (10): If x==5: Break
Print X |
The break loop used above, so the entire for loop is jumped out of the x==5, so the print X statement terminates only when it hits 4.
Other instances
# First: Ask for prime numbers between 50-100
The code is as follows |
Copy Code |
Import Math For I in range (50, 100 + 1): For j in range (2, int (math.sqrt (i)) + 1): If I% j = 0: Break Else Print I |
# Second: Put else's position in the same indent as if.
The code is as follows |
Copy Code |
Import Math For I in range (50, 100 + 1): For j in range (2, int (math.sqrt (i)) + 1): If I% j = 0: Break Else Print I |
# Third: Add a break statement after else.
code is as follows |
copy code |
Import Math for I in range (1): to J in range (2, int (math.sqrt (i)) + 1): & nbsp; if I% j = 0: break Else: print I break |