Python - 从函数输出? [英] Python - output from functions?
本文介绍了Python - 从函数输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def foo():
x ='hello world'
如何获得函数返回x的方式,以便我可以将它用作另一个函数的输入或在程序的主体中使用变量?
当我使用return并在另一个函数中调用变量时,我得到一个NameError。
解决方案
def foo():
x ='hello world'
return x#return'hello world'也会这样做
$ b foo()
print x#NameError - x没有在函数外定义
y = foo()
print y#这个工程
x = foo()
print x# ,这是一个完全不同的x,比
$ foo()
z = bar(x)#里面的#当然,现在你可以使用x,因为你想要
z = bar(foo())#但你不必
I have a very rudimentary question.
Assume I call a function, e.g.,
def foo():
x = 'hello world'
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?
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 - 从函数输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文