Ex33 Local variable x referenced before assignment


#1

I have finished the study drills of ex33, but I find something new that I am not sure about when I break the script again.
Here is my Script1:

def cycle(i, a, b, c):
	while i < a :
		print(f"At the top i is {i}")
		b.append(i)
		
		i = i + c
		print("Numbers now: ", b)
		print(f"At the bottom i is {i}")
	print("The numbers: ")

	for num in b:
		print(num)

a = int(input("integer i please> "))
b = int(input("integer a please> "))
c = list(input("elements of list please"))
d = int(input("integer increment please"))

cycle(a, b, c, d)

Script2:

numbers = []
b = int(input("Type in integer of range "))
c = int(input("Type in integer of increment "))

def cycle(a):
	a = range(0, b)
	for i in a:
		print(f"At the top i is {i}")
		numbers.append(i)

		print("Numbers now: ", numbers)
		print(f"At the bottom i is {i}")
	print("The numbers: ")

	for num in numbers:
		print(num)

cycle(b)

Script3:

numbers = []
a = int(input("Type in integer a please"))
i = 1

def cycle(a):
	#global i   without (global i):UnboundLocalError: local variable 'i' referenced before assignment
	while i < a :
		print(f"At the top i is {i}")
		numbers.append(i)

		i = i + 1
		print("Numbers now: ", numbers)
		print(f"At the bottom i is {i}")
		print("The numbers: ")

	for num in numbers:
		print(num)

cycle(a)

Script1 and 2 is operating normally, but I got a error in script3 as you can see that after #UnboundLocalError: local variable ‘i’ referenced before assignment. Error says ‘i’ is local variable but i thought that this variable is global. At the same time variable ‘b’ in script2 is global, I just want to know how python3.6 define local variables and global variables? Could someone give me some advice or clues?


#2

Yes, you have to tell the cycle function that it should use the i you defined outside of cycle. That’s what global does. Otherwise cycle just thinks you’re trying to use a variable it knows nothing about. Try also just moving i inside cycle instead:

def cycle(a):
    i = 1
    # rest of code here

Also, your text editor seems to be set to use real TAB characters instead of writing 4 spaces when you hit the tab key. Depending on your editor you should be able to fix that in preferences. Google for how to “set TAB to 4 spaces” for your text editor.