-1

Going from Javascript to Python really just means that scope is Satan reincarnated.

With this code, everything is fine:

a = 10

def elFunction():
    print a
    if (4 > 2):
        print a

elFunction()

With this code, I die a little inside

a = 10

def elFunction():
    a += 1
    if (4 > 2):
        print a

elFunction()

Why does this code draw an error?

Oli
  • 81
  • 2
  • 8
  • 3
    You haven't declared `global a` in your function, so you can't modify it. See e.g. https://infohost.nmt.edu/tcc/help/pubs/python/web/global-statement.html – kindall Jul 08 '16 at 18:54
  • Weirdly, I felt the same way about going from Python to Javascript. – Karl Knechtel Sep 09 '22 at 15:41

1 Answers1

3

Make your a a global variable:

a = 10

def elFunction():
    # Specify that a is global
    global a
    a += 1
    if (4 > 2):
        print a

elFunction()

This prints 11

Bahrom
  • 4,752
  • 32
  • 41