首页 > 解决方案 > 即使我将变量设置为重新启动它,循环也不会重​​新启动

问题描述

我对 python 很陌生,并决定尝试基于文本的冒险作为学习基础知识的起始项目。

如果用户输入了错误的单词,我有这个 while 循环会以 var valid_input 重新启动。它可以工作,但我注意到即使它应该已经重新启动,它仍然会读取最后的 else 语句,并给出一个额外的打印,我只打算在用户输入错误操作时显示。

while valid_input == False:
    dec2 = input("Do you shout aloud or try to use something to light the place (shout/light)")
    if dec2 == "light":
        if "lighter" in inventory:
            print(">You use the lighter to light up the room")
            print(">You find yourself in a large cavernous structure")
            room_visible = 1
            valid_input = True
            break
        else:
            print(">You don't seem to have anything to light up the place.")
            valid_input = False
        if dec2 == "shout":
            print(">You shout at the top of your lungs and see what that does.")
            valid_input = True
            break
        else:
            print("Invalid action")
            valid_input = False

更新#1

我修复了代码并尝试正确缩进,因为这是建议。尽管它仍然打印出“无效操作”消息,但这对我来说很有意义。

我决定在 else 语句中随机放置一个 valid_input = True ,它似乎有效。这是当前有效的代码,尽管我不明白它为什么有效。希望有人能解释一下!

while valid_input == False:
    dec2 = input("Do you shout aloud or try to use something to light the place (shout/light)")
    if dec2 == "light":
        if "lighter" in inventory:
            print(">You use the lighter to light up the room")
            print(">You find yourself in a large cavernous structure")
            room_visible = 1
            valid_input = True
            break
        else:
            valid_input = True
            print(">You don't seem to have anything to light up the place.")
            valid_input = False
    elif dec2 == "shout":
        print(">You shout at the top of your lungs and see what that does.")
        valid_input = True
        break
    else:
        print("Invalid action")
        valid_input = False

标签: python

解决方案


最后if dec2=="shout" ... else ...是在代码块里面if dec2=="light"。如果用户输入“light”,则将执行此 if-else 组合。因为dec2light,所以不是shout,因此解释器进入else块并打印"Invalid action"

您可能需要以下代码

while valid_input == False:
    dec2 = input("Do you shout aloud or try to use something to light the place (shout/light)")
    if dec2 == "light":
        if "lighter" in inventory:
            print(">You use the lighter to light up the room")
            print(">You find yourself in a large cavernous structure")
            room_visible = 1
            valid_input = True
            break
        else:
            print(">You don't seem to have anything to light up the place.")
            valid_input = False
    elif dec2 == "shout":
        print(">You shout at the top of your lungs and see what that does.")
        valid_input = True
        break
    else:
        print("Invalid action")
        valid_input = False

推荐阅读