Unique python loop statement
- 2020-05-17 05:51:52
- OfStack
1. Local variables
for i in range(5):
print i,
print i,
Operation results:
0 1 2 3 4 4
i is a local variable in the for statement. But in python, within the same method body, a local variable is defined that is scoped from the beginning of the definition line to the end of the method body.
In other programming languages, the sentence "print i" is incorrect because i is not defined
Case 1:
def func():
a = 100
if a > 50:
b = True
print b
if __name__ == '__main__':
func()
Results:
True
Example 2:
def func():
a = 100
if a > 50:
b = True
print b
if __name__ == '__main__':
func()
print b
The last line is incorrect, because b is not defined, and b in the func() method is a local variable in the body of the function, so "print b" in main is incorrect.
2, python for loop control statement
Example 1:
for i in range(5):
for j in range(6):
print (i,j),
print
Operation results:
(0, 0) (0, 1) (0, 2) (0, 3) (0, 4) (0, 5)
(1, 0) (1, 1) (1, 2) (1, 3) (1, 4) (1, 5)
(2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (2, 5)
(3, 0) (3, 1) (3, 2) (3, 3) (3, 4) (3, 5)
(4, 0) (4, 1) (4, 2) (4, 3) (4, 4) (4, 5)
Example 2:
Find the prime number between 50 and 100
import math
cout = 0
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,
cout +=1
if cout % 10 == 0:
cout = 0
print
#break # I can't add here break Otherwise it will be outside forbreak Because of this level else With the first 2 a for It's side by side
Operation results:
53 59 61 67 71 73 79 83 89 97
Resolution:
The for statement is the loop control statement in python. Can be used to traverse a 1 object, with an optional else block attached, mainly for handling for statements containing break statements.
If the for loop is not terminated by break, the statement in else is executed. for terminates the for loop when needed.
The format of the for statement is as follows:
for <> in < A collection of objects >:
if < conditions 1>:
break
if < conditions 2>:
continue
< Other statements >
else:
<...>