Python 2.x gotchas and landmines

后端 未结 23 2278
北恋
北恋 2020-11-28 17:47

The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things sp

23条回答
  •  执笔经年
    2020-11-28 18:18

    If you assign to a variable inside a function, Python assumes that the variable is defined inside that function:

    >>> x = 1
    >>> def increase_x():
    ...     x += 1
    ... 
    >>> increase_x()
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 2, in increase_x
    UnboundLocalError: local variable 'x' referenced before assignment
    

    Use global x (or nonlocal x in Python 3) to declare you want to set a variable defined outside your function.

提交回复
热议问题