0

Python: what is going on inside this for loop?

def f(n): x = y = 1.0 for i in range (1,n): x, y = y, x+y print(i) print(x) print (y) print("=================") return y/x print(f(3)) 1st iteration: i=1 x=1.0 y=2.0 2nd iteration: i=2 x=2.0 y=3.0 I do not understand the line x, y = y, x+y. I see this x+y expression, but it's not assigned to anything... so why does the x and y value increase?

14th Sep 2020, 6:41 PM
Solus
Solus - avatar
3 Answers
+ 3
In expression x,y=y,x+y y is assigned to x and x+y is assigned to y
14th Sep 2020, 6:45 PM
Abhay
Abhay - avatar
+ 2
thats a special feature in python. it allows multiple assignments in one row. (at least it looks like) x is assigned to y y is assigned to x+y
14th Sep 2020, 6:45 PM
Oma Falk
Oma Falk - avatar
+ 1
x, y = y, x+y: The expression above represents tuple unpacking. Consider this list. L=[1,2,3,4,5] If u wanted to assign members of the list to variables, u would use unpacking like this x, y,z,a,b = L Then x = 1, y=2 and so on. This is also applicable to tuples So for your example, expression on the right (y, x+y) is a tuple, you are simply assigning x and y the values of the tuple. So x=y and y=x+y
14th Sep 2020, 8:29 PM
Kirabo Ibrahim
Kirabo Ibrahim - avatar