The first program works, when the variable var
is defined outside the function f
. The value 232 is outputted successfully. In the second program, var
is again defined outside the function f
, but I get an error saying that var is not defined when the print statement in the function is run.
Why does the first program work, but the second program doesn't work?
First program:
var = 232
def f():
print (var)
f()
The second program:
var = 232
def f():
print (var)
var +=1
f()
The output of the first program is expected - it outputs the value 232.
The output of the second program should be 232, and it then increments var
, but a local variable error occurs at the print statement at line 3.