我希望用户键入“ right”或“ left”,然后根据输入内容,将执行一些操作。
如果用户前两次键入“ 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/")
问题在于,即使用户第三次,第四次或第五次键入“正确”,依此类推,“翻转”操作也不会发生。笑脸只会变得悲伤,不会从第一个循环中消失。
我在这里做什么错了?
答案 0 :(得分:2)
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/")
答案 1 :(得分:2)
您的条件是否如预期那样无法正常运行,因为条件是按顺序评估的。因此,如果n=="right"
为true,则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/")
答案 2 :(得分:0)
您不需要多个while循环,而在循环内部只需一个简单的if-elif
:
n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
i = 1
while (n.lower() == "right"):
if i < 3:
n = input("You are in the Lost Forest\n****************\n****************\n :(\n****************\n****************\nGo left or right? ")
elif i >= 3:
n = input("You are in the Lost Forest\n****************\n****** ***\n (╯°□°)╯︵ ┻━┻\n****************\n****************\nGo left or right? ")
i = i + 1
答案 3 :(得分:0)
我建议您将n == "right" or n == "Right"
替换为(n.lower() == "right")
这样,用户也可以输入rIght,并且不会影响您的程序。
此外,您的代码无法正常工作的原因是缺少括号,您可能可以在其他答案中阅读。