【问题标题】:My while statement is going wacky and I'm not sure what is wrong [duplicate]我的while语句很古怪,我不确定出了什么问题[重复]
【发布时间】:2016-09-24 22:54:40
【问题描述】:

我的代码不起作用,我不确定发生了什么。问题是当我第一次输入“Y”时,它仍然显示“请输入有效的输入”,我需要重新输入第二次才能正常工作。

if getoutofbed == "y":
    outofbed = 1
    print("You chose to get out of bed.")
elif getoutofbed == "n":
    outofbed = 2
    print("Your mom disregards your choice and screams at you to get out of bed. Listening to your mother, you step off the ledge of your resting place.")
    print("    .@@@@,")
    print("    aa`@@@,",name.upper(),"I DONT CARE IF YOU DONT WANNA GET UP!")
    print("    =  `@@@ GET UP!")
    print("      )_/`@'")
    print("     / || @")
    print("     | || @")
    print("     /~|| `")
    print("    /__W_/")
    print("      |||")
    print("     _|||")
    print("    ((___)")
    print("")
    print("")
while outofbed != 1 or 2:
    print("Please enter a valid input.")
    print("")
    print("")
    getoutofbed = input("Choose to get out of bed? Y/N").lower()
    print("")
    print("")
    if getoutofbed == "y":
        print("You chose to get out of bed.")
        break
    elif getoutofbed == "n":
        print("    .@@@@,")
        print("    aa`@@@,",name.upper(),"I DONT CARE IF YOU DONT WANNA GET UP!")
        print("    =  `@@@ GET UP!")
        print("      )_/`@'")
        print("     / || @")
        print("     | || @")
        print("     /~|| `")
        print("    /__W_/")
        print("      |||")
        print("     _|||")
        print("    ((___)")
        break

【问题讨论】:

  • 那是因为'y' != 'Y'
  • outofbed != 1 or 2: 不像英语那样“如果床外是一个或床外是两个”那样工作......

标签: python python-3.x while-loop python-3.1


【解决方案1】:

您需要更改您的 while 循环语句。

即使outofbed != 1 计算为False2 也会计算为True,因为它是一个“真实”值。改成这样:

while outofbed != 1 and outofbed != 2:

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多