Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - output from functions? [duplicate]

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.

like image 387
Darren J. Fitzpatrick Avatar asked Jun 16 '10 11:06

Darren J. Fitzpatrick


2 Answers

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
like image 73
Tim Pietzcker Avatar answered Oct 01 '22 17:10

Tim Pietzcker


>>> def foo():
    return 'hello world'

>>> x = foo()
>>> x
'hello world'
like image 24
SilentGhost Avatar answered Oct 01 '22 16:10

SilentGhost