1. Local Variables
For I in range (5):
print I,
print I,
Run Result:
0 1 2 3 4 4
I is the local variable inside the for statement. But inside Python, in the same method body, a local variable is defined, and the scope of the variable is to define the row to start at the end of the method body.
In other programming languages, the phrase "print I" is wrong, because I do not define
Example 1:
def func ():
a = +
if a >:
b = True
print b
if __name__ = = ' __main__ ':
func ()
Results:
True
Example 2:
def func ():
a = +
if a >:
b = True
print b
if __name__ = = ' __main__ ':
func ()
PR int b
The last line is incorrect because there is no defined B,func () method where B is the local variable in the function body, so the "print B" inside 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
Run Result:
(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:
Ask for prime numbers between [50,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% = 0:
cout = 0
print
#break # You cannot add a break here, otherwise you will be outside the forbreak because this level of else is side-by-side with the second for
Run Result:
53 59 61 67 71 73 79 83 89 97
Analytical:
The For statement is a circular control statement in Python. Can be used to traverse an object and have an optional else block, which is used primarily to process a for statement containing a break statement.
If the For loop is not terminated by a break, the statement in else is executed. For the For loop is terminated when needed.
The For statement is formatted as follows:
For <> in < object set:
if < condition 1>: Break
If < condition 2>:
continue
< other statements >
else:
<...>