简体   繁体   English

在 while 循环中忽略“else”选项替代

[英]"else" option alternative is ignored in a while loop

This is probably a simple problem that requires a simple answer...but I have been scratching my head why this happens.这可能是一个简单的问题,需要一个简单的答案……但我一直在摸索为什么会这样。 It's a problem on the loop that I am testing.这是我正在测试的循环上的一个问题。 Here's the loop:这是循环:

done = False
while done==False:
    checkUser = input("Do you want to continue?\nType Y or y to continue; any other char to quit\nType here: ")
    print(checkUser) # just to check the input

    if checkUser =='Y' or 'y':
        print ('Yes, I want to continue.')
        done = False
        break

    else:
        print('No. I want to quit now.')
        done = True
        sys.exit()

When I run this script on PyCharm, I get the outputs below:当我在 PyCharm 上运行此脚本时,我得到以下输出:

Do you want to continue?
Type Y or y to continue; any other char to quit
Type here: y
y
Yes, I want to continue

Do you want to continue?
Type Y or y to continue; any other char to quit
Type here: n
n
Yes, I want to continue

Question: why is the "else" option ignored?问题:为什么忽略“else”选项?

I tried so many variations like removing sys.exit() and so forth, but the loop still behaves the same way.我尝试了很多变体,例如删除sys.exit()等等,但循环的行为仍然相同。

change the line if checkUser =='Y' or 'y': to if checkUser =='Y' or checkUser == 'y': code worked as your expectation.if checkUser =='Y' or 'y':更改为if checkUser =='Y' or checkUser == 'y':代码按您的预期工作。 if checkUser =='Y' or 'y': means check if checkUser is 'Y' or 'y' is true which is true for any input. if checkUser =='Y' or 'y':表示检查 checkUser 是否为 'Y' 或 'y' 是否为真,这对于任何输入都是正确的。

It's not necessary to add break at the end of the if-condition as the while loop is already controlled by done variable.没有必要在 if 条件的末尾添加break ,因为 while 循环已经由done变量控制。 And your if-condition is not written properly such that the machine interprets as:并且您的 if 条件未正确编写,因此机器将解释为:

if (checkUser == 'Y') or ('y')

so the conditions become:所以条件变成:

condition_1: checkUser = 'Y'?
condition_2: 'y'?

if 'y' will always generate true so the while loop will go forever. if 'y' 将始终生成 true,因此 while 循环将永远是 go。 You should do:你应该做:

if checkUser == 'Y' or checkUser == 'y'

see if it helps you.看看它是否对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM