Python while循环的用法(附带实例)
在 Python 中,while 循环的基本语法为:
举个简单的例子:
while var:
execute_cmd()
只要 var 变量为真,则 execute_cmd() 将一直执行下去。举个简单的例子:
counter = 0
while counter < 4:
counter += 1
print('in while')
print('out while')
当 counter 小于 4 时,会一直处于 while 循环中。当不满足小于 4 的条件时,则退出 while 循环。运行结果为:
in while
in while
in while
in while
out while
while循环使用else语句
当 while 不满足判断条件时,执行 else 语句。例如:
counter = 2
while counter < 3:
counter += 1
print('in while')
else:
print('in else')
执行后,将分别打印 'in while' 和 'in else',运行结果为:
in while
in else
ICP备案:
公安联网备案: