如何从另一个函数调用变量到另一个函数
How do I call variable into another function from another function
我正在开发一款游戏,但卡在了应该用钥匙打开房间门的部分。现在,经过一番搜索,我发现我无法将存在于一个函数中的变量调用到另一个函数中:正如我一直在尝试通过在 [= 中的条件下设置即 key_picked = True
17=]厨房功能。然后,在 room 函数 中使用条件,在 key_picked
中使用布尔表达式。
那么,我该如何解决这个问题?
def kitchen(already_there=False):
if choice02_key == "pick key" or choice02_key == "0" or choice02_key == "key":
print("---------------------------------------------------------")
print "You picked the key. It probably unlocks some door."
key_picked = True
kitchen(already_there=True)
def room01(already_there=False):
if key_pick == True:
print("---------------------------------------------------------")
print "You unlocked the room using the key."
else:
print "This room is locked."
entrance_hall(already_there=True)
您可以在参数中传递变量。例如:
- 在
room01
中定义keyPicked
。
- 从
room01
呼叫 kitchen(already_there, keyPicked)
。
- 完成你想要的作业。
- 然后,你就会在
keyPicked
中得到你想要的值。
例如,假设我有一个将数字加 10 的函数。这将比 return 值更好,但它只是向您展示如何做到这一点。
def add_ten(number):
number = number + 10
def main():
number = 5
print('Number is:', number)
add_ten(number)
print('Number is:', number)
输出:
Number is: 5
Number is: 15
我正在开发一款游戏,但卡在了应该用钥匙打开房间门的部分。现在,经过一番搜索,我发现我无法将存在于一个函数中的变量调用到另一个函数中:正如我一直在尝试通过在 [= 中的条件下设置即 key_picked = True
17=]厨房功能。然后,在 room 函数 中使用条件,在 key_picked
中使用布尔表达式。
那么,我该如何解决这个问题?
def kitchen(already_there=False):
if choice02_key == "pick key" or choice02_key == "0" or choice02_key == "key":
print("---------------------------------------------------------")
print "You picked the key. It probably unlocks some door."
key_picked = True
kitchen(already_there=True)
def room01(already_there=False):
if key_pick == True:
print("---------------------------------------------------------")
print "You unlocked the room using the key."
else:
print "This room is locked."
entrance_hall(already_there=True)
您可以在参数中传递变量。例如:
- 在
room01
中定义keyPicked
。 - 从
room01
呼叫kitchen(already_there, keyPicked)
。- 完成你想要的作业。
- 然后,你就会在
keyPicked
中得到你想要的值。
例如,假设我有一个将数字加 10 的函数。这将比 return 值更好,但它只是向您展示如何做到这一点。
def add_ten(number):
number = number + 10
def main():
number = 5
print('Number is:', number)
add_ten(number)
print('Number is:', number)
输出:
Number is: 5
Number is: 15