0

The code

A stupid question about python function. We know that a local variable needs to be defined in the function before referring to it. However, in the code, the two variables are treated differently. Variable "b" is considered to be an error (and I can easily understand it), but object "a" is considered to be correct. Why is "a" correct? Why can we directly use it before defining it locally in the function? Thanks.

  • 1
    You need the `global` keyword if you are assigning to a global variable, but not if you're just calling a method on said global variable. – SuperStormer May 18 '21 at 04:03
  • 1
    Does this answer your question? [Use of "global" keyword in Python](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – SuperStormer May 18 '21 at 04:03
  • 3
    Because you're not assigning anything to `a`, you're just referring to it and functions can access variables out of their scope. `b += 1` is a shorthand for `b = b + 1`, the moment you have any assignment in your function (e.g. `variable = ...`) it will treat this variable as local (because you didn't declare to treat it as global). You'll encounter the same problem with `a` if you added, after the working insert, `a = None`. – zwer May 18 '21 at 04:03
  • @zwer Thanks. I thought before that everything non-global to be referred in a function must be defined locally. – QuestionStudent May 18 '21 at 04:15

0 Answers0