Python中while循环问题的实现

2024-05-16 10:43:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望用户键入“right”或“left”,根据输入,一些操作将发生。你知道吗

如果用户在前两次输入“right”,笑脸就会变得悲伤,无法走出森林。如果用户再多次输入“right”,笑脸总是会变得沮丧,砍掉一些树,做一张桌子,然后翻转出来,因为它无法走出森林。你知道吗

一旦用户键入“left”,笑脸就会从林中消失。你知道吗

下面是我的Python代码:

n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
i = 1
while n == "right" or n == "Right" and i < 3:
    n = input("You are in the Lost Forest\n****************\n****************\n :(\n****************\n****************\nGo left or right? ")
    i = i + 1
while n == "right" or n == "Right" and i >= 3:
    n = input("You are in the Lost Forest\n****************\n******       ***\n  (╯°□°)╯︵ ┻━┻\n****************\n****************\nGo left or right? ")
print("\nYou got out of the Lost Forest!\n\o/")

问题是,即使用户第三次、第四次或第五次键入“right”等等,也不会发生“翻页”操作。笑脸只会变得悲伤,它不会从第一圈出来。你知道吗

我做错什么了?你知道吗


Tags: orthe用户inrightyouinput键入
2条回答

您的if条件没有按预期工作,因为条件是按顺序计算的。因此,如果n=="right"为真,i的值无关紧要。相反,您应该将其更改为:

n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
i = 1
while (n == "right" or n == "Right") and i < 3:
    n = input("You are in the Lost Forest\n****************\n****************\n :(\n****************\n****************\nGo left or right? ")
    i = i + 1
while (n == "right" or n == "Right") and i >= 3:
    n = input("You are in the Lost Forest\n****************\n******       ***\n  (╯°□°)╯︵ ┻━┻\n****************\n****************\nGo left or right? ")
print("\nYou got out of the Lost Forest!\n\o/")

while语句中缺少括号。以下内容将满足您的需求:

n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
i = 1
while (n == "right" or n == "Right") and i < 3:
    n = input("You are in the Lost Forest\n****************\n****************\n :(\n****************\n****************\nGo left or right? ")
    i = i + 1
while (n == "right" or n == "Right") and i >= 3:
    n = input("You are in the Lost Forest\n****************\n******       ***\n  (╯°□°)╯︵ ┻━┻\n****************\n****************\nGo left or right? ")
print("\nYou got out of the Lost Forest!\n\o/")

我建议你用(n.lower() == "right")代替n == "right" or n == "Right"

这样,用户也可以输入正确的,它不会影响您的程序。你知道吗

另外,代码不起作用的原因是缺少括号,您可能可以从其他答案中看到。你知道吗

相关问题 更多 >