0

python(tuple)

def fibo (n): a ,b = 0,1 for i in range(n): print(a) a,b = (b , a+b) we say tuples are immutable and we cant change the vale of tuples but in this function which follows the Fibonacci sequence the value of a & b are changing each time the for loop runs how it can be? the a & b are not tuple or what?

20th Apr 2020, 11:30 AM
nima rasi
10 Answers
+ 1
a,b are integers not tuple!
20th Apr 2020, 11:37 AM
george
george - avatar
+ 3
In the line a,b = (b, a+b), the tuple is being "unpacked". a is taking on the value of b, b is taking on the value of a+b. The tuple then ceases to exist. In fact, the line will work the same without parentheses - a,b = b, a+b
20th Apr 2020, 11:34 AM
Russ
Russ - avatar
+ 1
If you write a=0,1 or b=0,1 it this case these variables recognized as tuples, but a,b=0,1 is multiple definition with assign. so this entry the same as a=0 b=1 but in python code manner
20th Apr 2020, 11:39 AM
george
george - avatar
+ 1
)))) you have inccorect code. There are not fibonachi numbers)))) So loook 0,1 1,1+1 2,2+2
20th Apr 2020, 11:59 AM
george
george - avatar
+ 1
)))) oooooo loooook you really forgot that operator = is from right to left. In your first code everything was ok. So your code was in python manner. Thrn you change code on c++ code manner but forgot than you need But in this case a eq b and b = a+b not the same as python a,b= b,a+b)))
20th Apr 2020, 12:03 PM
george
george - avatar
+ 1
So 1 code ok. But there are not tuple they are integers. A,b=b,a is the python swapping code. So a,b=0,1is a0 b1 But a,b=b,a is the same as c=a a=b b=c And this procedure do in python interpeter.
20th Apr 2020, 12:06 PM
george
george - avatar
0
Thanks russ and george
20th Apr 2020, 11:45 AM
nima rasi
0
def fibbi(n): a = 0 b = 1 for i in range(n): print(a) a = b b = a + b ok i change the method because you say a and b are int but the output answers are not true
20th Apr 2020, 11:53 AM
nima rasi
0
Sorry could youplease add full code. I could not understand what you mean about output answers are not true
20th Apr 2020, 11:55 AM
george
george - avatar
0
n in both is 5 def fibbi(n): a = 0 b = 1 for i in range(n): print(a) a,b = b,a+b n = int(input()) fibbi(n) anwsers : 0 1 1 2 3 ******************** def fibbi(n): a = 0 b = 1 for i in range(n): print(a) a = b b = a+b n = int(input()) fibbi(n) anwsers : 0 1 2 4 8
20th Apr 2020, 11:59 AM
nima rasi