Using a variable outside of function in Python
A really simple question, and I'm sure I knew it but must have forgo开发者_如何转开发tten
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?
Just return a value ?
x = 0
def run_5():
print "5 minutes later"
x += 5
return x
x=run_5()
print x
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.
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.
I think you need to define a variable outside the function, if you want to assign it a return value from the function.
The name of the variable can be different than the name in function as it is just holding it
精彩评论