首页 > 解决方案 > 带有 if/elif/else 语句的 While 循环

问题描述

我刚刚开始学习 Python,我在 while 循环方面遇到了一些问题。

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'。但是,这不起作用。

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

标签: python

解决方案


如果用户没有输入“y”或“n”,它应该保持循环,但不会

因为你有breakif-elif-else 之后。所以无论如何它都会破裂。

将中断移动到 if 块内(when instruction_yes_no.lower() == "y")。


推荐阅读