如何将局部变量从一个函数传递到另一个函数?
问题描述:
我正在尝试制作基于文本的游戏,但我遇到了将一些变量从一个函数传递给另一个函数的麻烦。我想出了如何修改函数中的变量并返回新值来覆盖原文。如何将局部变量从一个函数传递到另一个函数?
我需要的是如何让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
通过返回变量从一个功能到另一个变量。然而,为了做到这一点,该函数调用的函数体内其他功能,例如:
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
希望这有助于!
嗨@jabeydoe如果这或任何答案已解决您的问题,请点击复选标记,考虑[接受它](http://meta.stackexchange.com/q/5234/179419)。这向更广泛的社区表明,您已经找到了解决方案,并为答复者和您自己提供了一些声誉。没有义务这样做。 –