首页 > 解决方案 > 我怎样才能从一个def跳转到另一个def

问题描述

当我输入4时,它显示Living_room2未定义,我怎样才能让它先跳转到另一个def表单。代码如下,如果你能提供帮助,不胜感激。

def Living_room():
    print("\nLiving room contents: a pot of soil, stairs going up, a dark entranceway, a ball of a string")
    print("1).Viewing the pot of soil") 
    print("2). Stairs going up")
    print("3). Dark entranceway")
    print("4). Pick Ball of string")
    choice = input(">");
    if "1" in choice:
        print(" it looks dry")
        Living_room()
    elif "2" in choice:
        room_attic()
    elif "3" in choice:
        room_bedroom()
    elif "4" in choice:
        print("picked up")
        Living_room2()
Living_room()
def Living_room2():
    print("\nLiving room dcontents: a pot of soil, stairs going up, a dark entranceway")
    print("1).Viewing the pot of soil") 
    print("2). Stairs going up")
    print("3). Dark entranceway")
    choice = input(">");
    if "1" in choice:
        print(" it looks dry")
        Living_room2()
    elif "2" in choice:
        room_attic()
    elif "3" in choice:
        room_bedroom2()
Living_room2()

标签: pythonpython-3.x

解决方案


Python 从上到下逐行运行。因此,在您的代码中,python 将其视为...

我需要创建一个名为Living_room. 伟大的。但是它Living_room()在读取该行之前就命中了def Living_room2()。所以现在 python 在Living_room()没有设置的情况下停止并运行该调用Living_room2

将您的代码更改为此...

def Living_room():
   # Living_room code here
   elif "4" in choice:
        print("picked up")
        Living_room2()

def Living_room2():
   # Living_room2 code here

Living_room()

推荐阅读