在Python中将一个循环包装到另一个循环中?

2024-06-12 21:00:44 发布

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

目标:

  • 如果用户在前两次输入“right”,笑脸就会变得悲伤,因为它无法走出森林。

  • 如果用户键入“right”3、4、5次等等,笑脸就会变得沮丧,砍掉一些树,做一张桌子,然后翻转过来。

  • 如果用户键入其他内容,则会向用户显示一条显示“Invalid input”的消息,并要求用户再次输入。

  • 如果用户键入“left”,smiley将离开林,程序将终止。

Python代码:

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    
while (n.lower() != "right") and (n.lower() != "left"):
    n = input("Invalid Input\nYou are in the Lost Forest\n****************\n****************\n :(\n****************\n****************\nGo left or right? ")    
while (n.lower() == "left"):
    print("\nYou got out of the Lost Forest!\n\o/")
    break

错误:

如果用户在前两次键入“right”或“left”以外的任何内容,然后键入“right”,程序将立即终止,而不给键入“left”的机会。你知道吗

我应该如何编辑我的代码?你知道吗


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

更像这样:

lost = "You are in the Lost Forest\n****************\n****************\n :(\n****************\n****************\nGo left or right? "
inp = lost
rightCount = 0
while True:
    n = input(inp)
    if (n.lower() == "right"):
        rightCount = rightCount + 1
        if rightCount > 3:
            inp = ("You are in the Lost Forest\n****************\n******       ***\n  (╯°□°)╯︵ ┻━┻\n****************\n****************\nGo left or right? ")
        else:
           inp = lost  
    elif n.lower() == "left":
        print("\nYou got out of the Lost Forest!\n\o/")    #syntax error fixed
        break
    else:
        inp = ("Invalid Input\nYou are in the Lost Forest\n****************\n****************\n :(\n****************\n****************\nGo left or right? ")  

我想您忘记了将所有内容包装到while True循环(或其他类型的无休止循环)中。你知道吗

这是你需要的吗?你知道吗

while True:
    n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
    i = 1
    if (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    
    if (n.lower() != "right") and (n.lower() != "left"):
        n = input("Invalid Input\nYou are in the Lost Forest\n****************\n****************\n :(\n****************\n****************\nGo left or right? ")    
    if (n.lower() == "left"):
        print("\nYou got out of the Lost Forest!\n\o/")
        break

相关问题 更多 >