nearly two years Python language is constantly welcomed by the major enterprises, learning python 's pots of friends also gradually increased, then this article small series and everyone together to pick a steak,python What is the difference between a language's looping statements and other languages, and take a look at them.
1. Local Variables
for I in range (5):
Print I,
Print I,
Operation Result:
0 1 2 3 4 4
I is a local variable inside the for statement. In python , however, within the same method, a local variable is defined, and the scope of the variable is defined as the beginning of the line to the end of the method body.
in other programming languages,the phrase "Print I" is wrong, because i is not defined
Example 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 wrong, because B is not defined , and b in thefunc () method is a local variable within the function body, so the main inside the "Print B" wrong.
2,python for loop control Statement
Example 1:
for I in range (5):
for J in range (6):
Print (I,J),
Print
Operation 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 [50,100] the prime number between
Import mathcout = 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 # Here cannot be added break, otherwise it will be outside the forbreak, because this level of else and the second for It's a side relationship .
Operation Result:
53 59 61 67 71 73 79 83 89 97
Analytical:
for python The loop control statement. Can be used to traverse an object and also has an optional else block, Mainly used to handle for statement contains break statement.
if the for loop is not terminated by a break, the statement in else is executed . for to terminate the For loop when needed .
the format for the For statement is as follows:
for <> in < object collection ;:
if < conditions 1>:
Break
if < conditions 2>:
Continue
< other statements >Else:
<...>
Source: Blog Park
Python looping statements differ from other programming languages