Python return 在上一个函数中触发 else

我试图在 python 中制作一个简单的基于文本的冒险游戏,并且遇到了一个小错误,即在我不希望它调用时调用了 else 命令。以下是我的代码中的一个小示例。


## inventory var ##

 inv=["torch"] 



## inventory function ##

 def ichk():

       print(f" You are carrying{inv}")

       return




##First room, links to a3##


    def a2():

    

    move=input("placeholder text.. You notice an exit to your 'east': ")


    if move==("e"):

            print("You exit to the east")

            a3()

    if move==("i"):

            ichk()


    if move==("q"):

            print("You find nothing of value")

            a2()

    else:

            print("You can't move in that direction")

            a2()

            

当函数 ichk() 被触发时(通过用户输入“i”),库存被打印,然而在返回到函数 a2() 的开头之前,else 打印语句也被打印。我是 python 的新手,所以我知道构造的参数可能不是高效/有效的编码,但我不确定为什么会触发它。


www说
浏览 139回答 2
2回答

翻阅古今

当你像那样链接它们时你需要使用elif语句,否则输入'i',if你拥有的第三条语句将为假并运行相关else语句:## inventory var ## inv=["torch"] ## inventory function ## def ichk():       print(f" You are carrying{inv}")       return##First room, links to a3##    def a2():        move=input("placeholder text.. You notice an exit to your 'east': ")    if move==("e"):            print("You exit to the east")            a3()    elif move==("i"):            ichk()    elif move==("q"):            print("You find nothing of value")            a2()    else:            print("You can't move in that direction")            a2()

犯罪嫌疑人X

在Python中,如果有多个条件语句,需要写成:if,elif,elif,elif,....,else## inventory var ## inv=["torch"] ## inventory function ## def ichk():       print(f" You are carrying{inv}")       return##First room, links to a3##    def a2():        move=input("placeholder text.. You notice an exit to your 'east': ")    if move==("e"):            print("You exit to the east")            a3()    elif move==("i"):            ichk()    elif move==("q"):            print("You find nothing of value")            a2()    else:            print("You can't move in that direction")            a2()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python