10

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.

Mel
  • 5,460
  • 10
  • 38
  • 41
Darren J. Fitzpatrick
  • 6,611
  • 14
  • 43
  • 49

3 Answers3

26
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
Tim Pietzcker
  • 313,408
  • 56
  • 485
  • 544
3
>>> def foo():
    return 'hello world'

>>> x = foo()
>>> x
'hello world'
SilentGhost
  • 287,765
  • 61
  • 300
  • 288
2

You can use global statement and then achieve what you want without returning value from the function. For example you can do something like below:

def foo():
    global x 
    x = "hello world"

foo()
print x

The above code will print "hello world".

But please be warned that usage of "global" is not a good idea at all and it is better to avoid usage that is shown in my example.

Also check this related discussion on about usage of global statement in Python.

Community
  • 1
  • 1
sateesh
  • 26,733
  • 7
  • 36
  • 45
  • 2
    Technically, this is a solution to Seafoid's question, but pythonically, it's the worst-case-scenario (as you already pointed out). – Tim Pietzcker Jun 16 '10 at 12:20