Python 3 while循环
Python 3 while循环
Python语言中的while循环语句重复执行目标语句,只要给定条件为true。
语法
Python中while循环的语法为:
while expression: statement(s)
在这里,语句(statement(s))可以是单个语句或均匀缩进语句块。条件(condition)可以是表达式,以及任何非零值时为真。当条件为真时循环迭代。
当条件为false,则程序控制流会进到紧接在循环之后的行。
在Python中,所有编程结构后相同数量的字符空格的缩进语句被认为是一个单一代码块的一部分。Python使用缩进作为分组语句的方法。
例子
#!/usr/bin/python3 count = 0 while (count < 9): print ('The count is:', count) count = count + 1 print ("Good bye!")
输出
The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Good bye!
这里的块由print语句和increment语句组成,重复执行,直到计数不再小于9。每次迭代都会显示索引计数的当前值,然后增加1。
无限循环
如果条件永远不会变为FALSE,一个循环就会变成无限循环。使用while循环时,有可能永远不会解析为FALSE值时而导致无限循环,所以必须谨慎使用。导致无法结束一个循环。这种循环被称为一个无限循环。
服务器需要连续运行,以便客户端程序可以在有需要通信时与服务器端通信,所以无限循环在客户机/服务器编程有用。
例子
#!/usr/bin/python3 var = 1 while var == 1 : # This constructs an infinite loop num = int(input("Enter a number :")) print ("You entered: ", num) print ("Good bye!")
输出
Enter a number :20 You entered: 20 Enter a number :29 You entered: 29 Enter a number :3 You entered: 3 Enter a number :11 You entered: 11 Enter a number :22 You entered: 22 Enter a number :Traceback (most recent call last): File "examples\test.py", line 5, in num = int(input("Enter a number :")) KeyboardInterrupt
上面的例子将进入无限循环,你需要使用CTRL+C退出程序。
循环使用else语句
Python支持将else语句与循环语句相关联。
如果else语句与for循环一起使用,则else语句将在循环已用尽列表迭代时执行。
如果else语句与while循环一起使用,则在条件变为false时执行else语句。
下面的示例说明了else语句和while语句的组合,while语句打印小于5的数字,否则else语句将被执行。
例子
#!/usr/bin/python3 count = 0 while count < 5: print (count, " is less than 5") count = count + 1 else: print (count, " is not less than 5")
输出
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
单套件声明
类似于if语句语法,如果while子句仅由单个语句组成,则它可能与while标头位于同一行。
例子
#!/usr/bin/python3 flag = 1 while (flag): print ('Given flag is really true!') print ("Good bye!")
上面的例子进入无限循环,你需要按CTRL+C键退出。