Python-函数输出?

发布于 2021-01-29 19:35:52

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

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

def foo():
    x = 'hello world'

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

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

关注者
0
被浏览
72
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看