Wednesday, October 19, 2022

[FIXED] How do I get a result (output) from a function? How can I use the result later?

Issue

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.


Solution

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


Answered By - Tim Pietzcker
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.