簡體   English   中英

如何將局部變量從一個函數傳遞到另一個函數?

[英]How to pass local variables from one function into another?

我正在嘗試制作基於文本的游戲,但是在將一些變量從一個函數傳遞到另一個函數時遇到了麻煩。 我想出了如何在函數內修改變量並返回新值以覆蓋原始值。

我需要什么幫助是如何獲得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()

您可以pass返回變量將變量從一個函數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

但是,如果您不能在函數體內調用函數,而是想使用該函數的局部變量,則可以將該變量聲明為兩個函數的全局變量。

這是一個例子:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print globvar     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM