-2
a = 2
def alter_a():
    a = a * 2
    return a

Why doesn't this work? I know it won't change the value of the global variable, but can't it work inside the function?

Sssign a new value to a... which is the old value * 2. Why isn't this possible?

BrowserM
  • 61
  • 1
  • 6

1 Answers1

2

The a inside the function lives inside the function scope, if you want to reference the outer one use global:

a = 2
def alter_a():
    global a
    a = a * 2
Netwave
  • 36,219
  • 6
  • 36
  • 71