Home>Article>Backend Development> How to use python's while
Python While loop statement
The while statement in Python programming is used to execute the program in a loop, that is, under certain conditions, execute a certain program in a loop , to handle the same tasks that need to be processed repeatedly.
The basic form is:(Recommended learning:Python video tutorial)
while 判断条件: 执行语句……
The execution statement can be a single statement or statement block. The judgment condition can be any expression, and any non-zero or non-null value is true.
When the judgment condition is false, the loop ends.
There are two other important commands in the while statement: continue, break is used to skip the loop, continue is used to skip the loop, break is used to exit the loop, in addition" The judgment condition "can also be a constant value, indicating that the loop must be established. The specific usage is as follows:
# continue 和 break 用法 i = 1while i < 10: i += 1 if i%2 > 0: # 非双数时跳过输出 continue print i # 输出双数2、4、6、8、10 i = 1while 1: # 循环条件为1必定成立 print i # 输出1~10 i += 1 if i > 10: # 当i大于10时跳出循环 break
Loop uses the else statement
In python, while...else is in the loop When the condition is false, the else statement block is executed:
#!/usr/bin/python count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5"
The output result of the above example is:
0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is not less than 5
For more Python-related technical articles, please visit thePython Tutorialcolumn to learn!
The above is the detailed content of How to use python's while. For more information, please follow other related articles on the PHP Chinese website!