Using a variable outside of function in Python

后端 未结 4 1142
误落风尘
误落风尘 2021-01-03 08:18

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\"
           


        
相关标签:
4条回答
  • 2021-01-03 08:44

    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.

    0 讨论(0)
  • 2021-01-03 08:50

    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.

    0 讨论(0)
  • 2021-01-03 08:56

    Just return a value ?

    x = 0
    def run_5():
        print "5 minutes later"
        x += 5
        return x
    
    x=run_5()
    print x
    
    0 讨论(0)
  • 2021-01-03 09:02

    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

    0 讨论(0)
提交回复
热议问题