tags:

views:

60

answers:

3

A really simple question, and I'm sure I knew it but must have forgotten

When running this code:

x = 0
def run_5():
    print "5 minutes later"
    x += 5
    print x, "minutes since start"

run_5()
print x

I get x isn't defined. How can I have x used in the function and effected outside of it?

A: 

Put global x at the start of the function.

However, you should consider if you really need this - it would be better to return the value from the function.

Daniel Roseman
Hush! We don't *want* people to know about `global` before they know about `return`. In a perfect world, they'd even understand how bad globals are before they learn about `global`.
delnan
+1  A: 

Just return a value ?

x = 0
def run_5():
    print "5 minutes later"
    x += 5
    return x

x=run_5()
print x
ghostdog74
A: 

Just to make sure, the x that is not defined is the one on line 4, not the one on the last line.

The x outside the function is still there and unaffected. It's the one inside that can't have anything added to it because, as far as Python is concerned, it does not exist when you try to apply the += operator to it.

eje211