How do I get ("return") a result (output) from a function? How can I use the result later?

Suppose I have a function like:

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? I tried using return and then using the x variable in another function, but I get a NameError that way.

For the specific case of communicating information between methods in the same class, it is often best to store the information in self. See Passing variables between methods in Python? for details.


  • You can use the return statement to return a value from a function, this does not make it so that the returned variable (value) becomes available in the scope of the caller. To use the value in the caller you can either use it directly in a statement or capture the value in a variable.

    Here's some code to demonstrate this:

    def foo():
        x = 'hello world'
        return x  # return 'hello world' would do, too
    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