首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用if/elif/else语句的While循环

使用if/elif/else语句的While循环
EN

Stack Overflow用户
提问于 2018-06-10 07:30:47
回答 1查看 2.2K关注 0票数 0

我刚刚开始学习Python,我对while循环有一些问题。

代码语言:javascript
复制
instruction_yes_no = ""

while instruction_yes_no.lower() != "y" or "n":
    instruction_yes_no = input("Do you want to see the instruction? Please write 'Y' or 'N'\n")
    if instruction_yes_no.lower() == "y":
        print("You are gonna lose even if you read the instructions...")
        print("\n")
        time.sleep(1)
        instruction()
    elif instruction_yes_no.lower() == "n":
        print("Do you think you are better than me? I will beat you faster since you have not read the instructions")
        time.sleep(1)
    else:
        print("You mortal...you have not chosen a valid input. Type or 'Y' or 'N'")
        time.sleep(1)
    break

基本上,我想获得以下几点:

1)如果用户输入'y',则调用指令()函数(这是有效的)

2)如果用户输入'n',它会打印“你认为你比我好吗?...”(这是可行的)

3)如果用户没有键入'y‘或'n',我希望继续循环,直到用户插入或'y’或'n‘。然而,这是不起作用的。

我不明白为什么。我认为它应该是这样工作的:

  • 在开始时,变量instruction_yes_no设置为""
  • It进入循环,因为instruction_yes_no !=

'y‘or 'n’

  • 现在,instruction_yes_no假定用户输入的值为
  • ,如果用户没有输入'y‘或’n‘,则应该继续循环,但不会。
EN

回答 1

Stack Overflow用户

发布于 2018-06-10 07:39:00

哦,这是一个典型的常见错误:

代码语言:javascript
复制
while instruction_yes_no.lower() != "y" or "n":

它与

代码语言:javascript
复制
while (instruction_yes_no.lower() != "y") or True:

您需要的是以下内容:

代码语言:javascript
复制
while instruction_yes_no.lower() != "y" and instruction_yes_no.lower() != "n":

也可以这样,它更短:)

代码语言:javascript
复制
while instruction_yes_no.lower() not in ["y", "n"]:
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50779391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档