我希望用户输入"right“或"left”,根据输入,将发生一些操作。
如果用户在前两次输入"right“,笑脸就会变得悲伤,不能走出森林。如果用户多次输入“正确”,笑脸总是会变得沮丧,砍掉一些树,做一张桌子,然后翻出来,因为它不能走出森林。
只要用户输入“左”,笑脸就会离开森林。
以下是我的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/")问题是,即使用户输入第三次、第四次或第五次“正确”,“翻转”动作也不会发生。笑脸只会变得悲伤,它不会从第一个循环中走出来。
我在这里做错了什么?
发布于 2019-02-12 21:59:31
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/")发布于 2019-02-12 22:00:17
您的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/")发布于 2019-02-12 22:01:33
您不需要多个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 + 1https://stackoverflow.com/questions/54651672
复制相似问题