如何在Python多层if语句中使用input函数并解决变量未定义问题
问题原因
你遇到的报错本质是变量未在所有代码执行路径中被定义,具体问题出在原有代码的逻辑结构上:
level_2变量仅在level_1 == "left"的条件分支中被赋值创建,当你输入right时,这个分支不会执行,level_2自然不存在,但你后续代码直接全局执行level_2.lower()以及level_2的取值判断,就会触发变量未定义的报错。- 同理,原有代码中
level_3仅在level_2 == "upstairs"的分支中被创建,如果选了basement,后续直接判断level_3的值也会触发同类报错,只是你之前没触发这个场景而已。 - 补充一个原有代码的隐藏问题:
level_1.lower()、level_2.lower()这两行写法是无效的,Python的字符串是不可变类型,调用lower()方法不会修改原变量,必须赋值回原变量才会生效,比如level_1 = level_1.lower(),不然用户输入大写的Right、LEFT这类内容时,判断逻辑会直接失效。
修正逻辑说明
你调整后的缩进和嵌套if写法是正确的:
- 用
elif替代平级if,避免不必要的分支判断 - 把
level_2、level_3的相关逻辑全部嵌套在上一级条件分支内,只有上一级条件满足、变量被成功创建后,才会执行后续相关操作,从根源上避免了访问未定义变量的问题。 - 小优化点:修正后的代码开头重复写了两次欢迎语,删除重复的两行即可,不影响核心逻辑。
原问题代码
print("Welcome to the dungeon.") print("Your mission is to find the ursine sword.") level_1 = input("there is two doors infront of you type 'right' for the right door and 'left' for the left door.\n" ) level_1.lower() if level_1 == "right" : print("this door is closed your level is too low to open it.\n") if level_1 == "left" : level_2 = input("you found a two ladder one leads to upstairs type 'upstairs' and another leads to the basement type 'basement'.\n ") level_2.lower() if level_2 == "basement" : print("hisssssss , you got bitten by snake game over") if level_2 == "upstairs" : level_3 =int(input("it seems like the final room thre is three swords infront of you two of them must be traps chose '1','2' or '3' ")) if level_3 == 1 : print("you released a powerful ghost you'r dead") elif level_3 == 3 : print("you opened a portal to a cater you're dead") elif level_3 == 2 : print("congratulations you found the ursine sword") else : print("game over.")
修正后代码
print("Welcome to the dungeon.") print("Your mission is to find the ursine sword.") level_1 = input("there is two doors infront of you type 'right' for the right door and 'left' for the left door.\n").lower() if level_1== "right": print("this door is closed your level is too low to open it.\n") elif level_1== "left": level_2 =input("you found a two ladder one leads to upstairs type 'upstairs' and another leads to the basement type 'basement'.\n ").lower() if level_2== "basement": print("hisssssss , you got bitten by snake game over") elif level_2== "upstairs": level_3 = int(input("it seems like the final room thre is three swords infront of you two of them must be traps chose '1','2' or '3' ")) if level_3 == 1 : print("you released a powerful ghost you'r dead") elif level_3 == 3 : print("you opened a portal to a cater you're dead") elif level_3 == 2 : print("congratulaitons you found the ursine sword") else : print("game over.")
内容的提问来源于stack exchange,提问作者Loay Alhefny
相关产品推荐
相关产品推荐

