-1

I get a confusion...

why they have different errors?

or like JavaScript?

print(val1) #NameError: name 'val1' is not defined
val1 = 20


def foo1():
    print(val2)  # NameError: name 'val2' is not defined
foo1()


def foo2():
    print(val3)  # UnboundLocalError: local variable 'val3' referenced before assignment
    val3 = 20
foo2()
ayhan
  • 70,170
  • 20
  • 182
  • 203
nameless1
  • 203
  • 1
  • 6
  • Unless you are a language lawyer, I think you can use the statements "first assignment of `val` in this scope" and "definition of `val` in this scope" interchangeably. The error itself is explained in the duplicate. – timgeb Jan 06 '19 at 12:50
  • Defined means to create the human readable variable name, assignment means to give it a value. It's tricky to see the difference in python because variable types are not explicit, but in C `int size = 5;` would be defining and assigning a variable in one go and `int size; /* maybe some other code */ size = 5;` would be splitting defining a variable and assigning to it. – Michael Jan 06 '19 at 12:54

1 Answers1

0

Because the last one has an assignment to the value in the scope of the function and python detects that you have an assignment of value after calling the print.

In the second case python can not find the any definition and in the first case as you are assigning a value to in the global scope it cannot resolve that value is for the previous val or not (as it is not in the local scope).

OmG
  • 18,337
  • 10
  • 57
  • 90