while循环使用if / elif / else语句

时间:2018-06-09 23:30:47

标签: python

我刚刚开始学习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',则调用instruction()函数(此工作)

2)如果用户输入' n'它会打印""你觉得你比我好吗?..." (这项工作)

3)如果用户没有输入“' y'或者' n',我想继续循环,直到用户插入或' y'或者' n'。 但是这不起作用。

我不明白为什么。这就是我认为应该如何运作的方式:

  • 在开始时,变量instruction_yes_no设置为""

  • 它进入循环因为instruction_yes_no!=而不是' y'或者' n'

  • 现在,instruction_yes_no假定用户输入的值

  • 如果用户没有输入“' y'或者' n'它应该保持循环,但不是。

2 个答案:

答案 0 :(得分:2)

  

如果用户没有输入' y'或者' n'它应该保持循环,但不是

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

在if块中移动该中断(当instruction_yes_no.lower() == "y"时)。

答案 1 :(得分:2)

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

while instruction_yes_no.lower() != "y" or "n":

相同
while (instruction_yes_no.lower() != "y") or True:

你想要这个:

while instruction_yes_no.lower() != "y" and instruction_yes_no.lower() != "n":

或许这个,它更短:)

while instruction_yes_no.lower() not in ["y", "n"]:
相关问题