Python local vs global variables

前端 未结 4 1679
无人共我
无人共我 2020-12-01 21:52

I understand the concept of local and global variables in Python, but I just have a question about why the error comes out the way it is in the following code. Python execut

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 22:14

    This is because, in python, you need to tell that you are going to modify the value of a global variable. You do that as:

    def test():
      global a
      print a  #line 4, Error : local variable 'a' referenced before assignment
      a=0      #line 5
    

    With global a, you can modify variables in the function. You may want to have a look at this:

    • Python: Why is global needed only on assignment and not on reads?

提交回复
热议问题