-1

A global variable cannot be accessed within a function since it has local scope inside the variable. But if you try to print a variable defined outside a function inside the function, it works.

v = 5
def func():
    print(v)
func()

This is perfectly valid code

v = 5
def func():
    v += 1
    print(v)
func()

Now this errors out. Why?

  • you need to use `global v` inside the function if it needs an update. – shaik moeed Aug 23 '23 at 03:18
  • This was simply a Python design decision. If you assign a new value to a name anywhere in a function, that name becomes a local variable, unless you have a `global` statement. `v += 1` assigned a new object to `v`, so it becomes function local, and that means there's no initial value to increment. – Tim Roberts Aug 23 '23 at 03:23

0 Answers0