小编典典

Python-函数输出?

python

我有一个非常基本的问题。

假设我调用一个函数,例如

def foo():
    x = 'hello world'

如何获得以返回x的功能,以便可以将x用作另一个函数的输入或在程序主体中使用变量?

当我使用return并在另一个函数中调用变量时,我得到了NameError。


阅读 225

收藏
2020-12-20

共1个答案

小编典典

def foo():
x = ‘hello world’
return x # return ‘hello world’ would do, too

foo()
print x    # NameError - x is not defined outside the function

y = foo()
print y    # this works

x = foo()
print x    # this also works, and it's a completely different x than that inside
           # foo()

z = bar(x) # of course, now you can use x as you want

z = bar(foo()) # but you don't have to
2020-12-20