本文介绍了Python - 函数的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个非常基本的问题.
I have a very rudimentary question.
假设我调用了一个函数,例如
Assume I call a function, e.g.,
def foo():
x = 'hello world'
如何让函数返回 x 以便我可以将其用作另一个函数的输入或在程序体内使用变量?
How do I get the function to return x in such a way that I can use it as the input for another function or use the variable within the body of a program?
当我使用 return 并在另一个函数中调用该变量时,我得到一个 NameError.
When I use return and call the variable within another functions I get a NameError.
推荐答案
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
这篇关于Python - 函数的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!