【问题标题】:How to put a variable under one function as an argument under another?如何将变量放在一个函数下作为另一个函数下的参数?
【发布时间】:2014-11-27 04:45:22
【问题描述】:

我想使用用户在一个函数下提供的输入作为另一个函数下的参数。示例:

def f(value):
    age = raw_input('>')
    return
def hello(age):
    print "You are %d years old" %age
    return

f(0)
hello(age)

当我这样做时,我得到了变量年龄未定义的错误。如何解决这个问题。

【问题讨论】:

  • 永远记住函数内部的变量有一个局部作用域!

标签: python python-2.7 variables arguments


【解决方案1】:

您需要从函数f 返回年龄并在hello() 中使用该值:

def f():
    age = raw_input('>')
    return age

def hello():
    return  "You are {} years old".format(f())

print hello()

你应该看看这个tutorial函数

【讨论】:

    【解决方案2】:

    你必须在hello函数中调用用户输入函数:

    def f():
      age = raw_input('>')
      return age
    
    def hello(age):
      print "You are %d years old" % (age)
      return age
    
    hello(f())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 2022-01-19
      • 2015-09-28
      相关资源
      最近更新 更多