如何将本地变量从一个函数传递到另一个函数?

2024-09-28 21:55:29 发布

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

我试图做一个基于文本的游戏,但我有困难传递一些变量从一个函数到另一个函数。我发现了如何修改函数内部的变量并返回新值来覆盖原来的值。在

我需要帮助的是如何将room1()room2()变量返回到something1(x)something2(y)并进入main()以解锁if语句。在

我应该为something1(x)something2(y)使用两个不同的函数还是一个函数?在

这是我遇到的问题的一般示例代码:

def something1(x):
    x += 0
    return x

def something2(y):
    y += 0
    return y    

def main():
    print("1. Try to open door")
    print("2. Go to room1")
    print("3. Go to room2")
    choice = int(input("Enter selection: ")
    if choice == "1":

     # Trying to get this if statement to work with the variables
     # Don't know which function or parameters to pass in order to get it to work

        if x == 3 and y == 2:
            print("You're free")
        else:
            print("You're not free")
    elif choice == "2":
        room1()
    elif choice == "3":
        room2()
    else:
        print("ERROR")
        main()

def room1():
    print("1. Push thing1")
    print("2. Push thing2")
    print("3. Push thing3")
    print("4. Return to previous room")
    pushChoice = input("Enter selection: ")
    if pushChoice == "1":
        print("Thing1 pushed")
        room1()
    elif pushChoice == "2":
        print("Thing2 pushed")
        room1()
    elif pushChoice == "3":
        print("Thing3 pushed")

     # The modified variable x for something1(x)

        x = 3
        x = something1(x)
        room1()
    elif pushChoice == "4":
        main1()
    else:
        print("ERROR")
        room1()

def room2():
    print("1. Pull thingA")
    print("2. Pull thingB")
    print("3. Pull thingC")
    print("4. Return to previous room")
    pullChoice = input("Enter selection: ")
    if pullChoice == "1":
        print("ThingA pushed")
        room1()
    elif pullChoice == "2":
        print("ThingB pushed")

      # The modified variable y for something2(y)

        y = 2
        y = something1(y)       
        room1()
    elif pullChoice == "3":
        print("ThingC pushed")
        room1()
    elif pullChoice == "4":
        main1()
    else:
        print("ERROR")
        room1()

Tags: to函数ifdefelseprintpushedchoice
1条回答
网友
1楼 · 发布于 2024-09-28 21:55:29

通过返回变量,可以将变量从一个函数pass转换为另一个函数。但是,为了做到这一点,函数必须调用函数体中的另一个函数,例如:

def addandsquare(x, y):
    y = squarefunction(x+y) # sum x+y is passed to squarefunction, it returns the square and stores it in y.
    return y

def squarefunction(a):
    return (a*a) # returns the square of a given number

print(addandsquare(2, 3)) # prints 25

但是,如果不能在函数体中调用函数,但希望使用该函数的局部变量,则可以将该变量声明为两个函数的全局变量。在

下面是一个例子:

^{pr2}$

希望这有帮助!在

相关问题 更多 >