【问题标题】:How do I call variable into another function from another function如何从另一个函数将变量调用到另一个函数中
【发布时间】:2017-11-04 10:04:30
【问题描述】:

我正在开发一款游戏,但卡在了本应用钥匙打开房间门的地方。现在,经过一番搜索,我发现我无法将一个函数中存在的变量调用到另一个函数中:正如我一直试图通过在 kitchen 中的条件下设置 iekey_picked = True函数。然后,在 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)

【问题讨论】:

  • 代码太多了!将其归结为几行示例怎么样。只是一些简单的东西来证明问题。
  • 听起来不错。我会编辑它
  • 将变量传递给函数?目前还不完全清楚问题是什么。
  • 一旦我在游戏中选择了钥匙,key_picked 在厨房功能中设置为 true。然而,现在当我想去房间时,我得到一个错误,“key_picked”没有定义。那么我该如何解决这个问题,或者有办法解决吗
  • 将变量传递给函数?

标签: python-2.7 function boolean conditional variable-assignment


【解决方案1】:

您可以在参数中传递变量。例如:

  1. room01 中定义keyPicked
  2. room01 致电kitchen(already_there, keyPicked)
    1. 做你想要的作业。
  3. 然后,您将在keyPicked 中获得您想要的值。

例如,假设我有一个将 10 加到一个数字上的函数。这会更好地返回值,但它只是向您展示如何做到这一点。

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

【讨论】:

    猜你喜欢
    • 2019-04-07
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    相关资源
    最近更新 更多