Python while (bool):

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13671546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:21:22  来源:igfitidea点击:

Python while (bool):

pythonlogic

提问by Rohit Rayudu

In this case:

在这种情况下:

swag = True
i = 0

while swag:
    i=i+1
    print(swag)
    if i == 3:
        swag = False

Will the while loop exit after 3 turns?

while 循环会在 3 圈后退出吗?

Does while swag - check if swag exists or if swag is True

是否在 swag - 检查 swag 是否存在或 swag 是否为 True

采纳答案by Xymostech

while swag:will run while swagis "truthy", which it will be while swagis True, and will not be when you set swagto False.

while swag:将运行 whileswag是“真实的”,这将是 while swagis True,而当您设置swag为时则不会False

回答by arshajii

Does while swag - check if swag exists or if swag is True

是否在 swag - 检查 swag 是否存在或 swag 是否为 True

It checks if swagis True(or "truthy", I should say). And yes, the loop will exit after 3 iterations because i=i+1must be executed 3 timesuntil i == 3and (by the if-statement) swagis set to False, at which point the loop will exit.

它检查是否swagTrue(或“真实”,我应该说)。是的,循环将在 3 次迭代后退出,因为i=i+1必须执行3 次,直到i == 3和(通过 -if语句)swag设置为False,此时循环将退出。

But why not check this yourself?

但为什么不自己检查一下呢?

swag = True
i = 0

while swag:
    i=i+1
    print(swag)
    if i == 3:
        swag = False
True
True
True

回答by Sandwich Heat

You can also shorten your expression to increment variable 'i' by 1 by using the following notation: i+=1 (same as i=i+1)

您还可以使用以下符号缩短表达式以将变量“i”增加 1:i+=1(与 i=i+1 相同)