Using a variable outside of function in Python

2020-02-29 06:44发布

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?

标签: python
4条回答
时光不老,我们不散
2楼-- · 2020-02-29 06:58

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

查看更多
欢心
3楼-- · 2020-02-29 07:02

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.

查看更多
forever°为你锁心
4楼-- · 2020-02-29 07:04

Just return a value ?

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

x=run_5()
print x
查看更多
▲ chillily
5楼-- · 2020-02-29 07:05

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.

查看更多
登录 后发表回答