In Python programming, a while statement is used to loop the execution of a program, which, under certain conditions, loops through a program to handle the same tasks that require repeated processing. Its basic form is:
While judging condition: Execute statement ...
The execution statement can be a single statement or a block of statements. The judging condition can be any expression, and any value other than 0, or non-null (NULL), is true.
The loop ends when the condition false false is judged.
Instance:
#!/usr/bin/pythoncount = 0while (count < 5 print The count is: '
The Count is:0
The Count is:1
The Count Is:2
The Count Is:3
The Count Is:4
Good bye!
While statement there are two other important command Continue,break to skip the loop, Continue is used to skip the cycle, break is used to exit the loop, in addition, "judging condition" can also be a constant or Boolean value, the constant indicates that the loop must be established, A Boolean value of TRUE indicates that the loop is set to FALSE and is not valid, as follows:
# Continue and break usageI= 1WhileI< 10:I+= 1 IfI%2 > 0: # Skip output when non-even continue print i # output even 2 , 4, 6, 8, 10i = 1while 1: # Cycle condition of 1 must be established print i # output 1~10 I += 1if I > 10 : # when I is greater than 10 o'clock jump out of the loop break
Looping with Else statements
In Python, while ... else means that the statement in the while is not the same as normal, and the statement in else is executed when the loop is executed normally (that is, the while is not interrupted by a break jump), for ... else is the same.
#!/usr/bin/pythonCount = 0while count < 5: Print Count, "is less than 5" count = count + 1else: Print Count , "is isn't less than 5"
The result of the above example output is:
0 is less than 51 is less than 5 2 is less than 53 is less than 54 is less than 55 is not less than 5
< Span class= "lit" >< Span class= "pun" >< Span class= "PLN" >< Span class= "pun" >< span class= "str" >&NBSP;
Python while loop