1

I'm currently learning Python, and couldn't get my mind around this variable position "paradox" (which exists only to the level of my "beginners knowledge" in Python).

Example 1

#creating a function which returns the elements of a list called i.

def var_i1():

    i = [1,2,3,4]

    for elt in i:

        print(elt)
var_i1()

#This successfully prints :

1
2
3
4

Example 2

#creating a function which returns the elements of a list called i. i is outside of the body var_i2()

i = [1,2,3,4]

def var_i2():

    for elt in i:
        print(elt)

var_i2()

#allthough i is outside of the function body (correct me if I'm wrong) this also successfully prints :

1
2
3
4

Example 3

i = 4 

def var_i3():

    if i >0:
    i += 1
    print(i)    
    
var_i3()

# UnboundLocalError: local variable 'i' referenced before assignment

#I don't understand why Python is okay with variable i as a list but not variable i as an integer

  • 1
    Please update your question with code formatting and also check the indentation of your code. – quamrana Nov 07 '20 at 16:14
  • There's a nice explanation here: https://stackoverflow.com/questions/10851906/python-3-unboundlocalerror-local-variable-referenced-before-assignment – Maja Ozegovic Nov 07 '20 at 16:23

1 Answers1

0

I don't understand why Python is okay with variable i as a list but not variable i as an integer

It is unrelated to the type.

The line i += 1 is treated by the interpreter as

i = i + 1

or, put differently,

i = "something"

because of this, the interpreter assumes that i in the context of this function is a local, not a global. However, it also appears in the line before, so, in terms of the interpreter, it is referencing it before it is defined.

If you explicitly make it global, it will work

i = 4

def var_i3():
    
    global i

    if i >0:
        i += 1
    print(i) 
    
var_i3()
5
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185