Why is (a,b) equal to 22? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is (a,b) equal to 22?

a=1 b=a+1 a,b =2, a+1 print(a,b) Solution: 22 a = 1, so b = 1+1= 2 a,b = 2, a+1 # 1, 2 = 2 ,1+1 #So solution should be 1,2,2,2? Why is it just 22? Any help appreciated:)

27th Mar 2019, 2:38 AM
tristach605
tristach605 - avatar
6 Answers
+ 4
Python allows you to do multiple assignments in one step. Instead of a = 1 b = 2 c = 3 , you can just do: a, b, c = 1, 2, 3 Assignments are done from the right to the left, so the third value after the = (3) will be assigned to the third variable (c), the second value (2) to the second variable (b) and so on. So a, b = 2, a + 1 will first set b to a + 1 (which is 2) and then set a to 2. The value of a is only changed once. This syntax is particularly useful if you want to assign values of a list/tuple etc. to variables: l = [1, 2, 3] # list with three elements a, b, c = l This will assign 1 to a, 2 to b and 3 to c.
27th Mar 2019, 10:16 AM
Anna
Anna - avatar
+ 1
Because python takes everything in sequence. So a =1 /*simplified*/ a=2,b =early value of a (1) +1=2 So 22 is the output due to no space
27th Mar 2019, 3:23 AM
Anshumaan Mishra
+ 1
You can ignore the second line, b=a+1, because b will be redefined in the next line. a, b = 2, a+1 means: b = a+1 a = 2 a was 1 before (see first line), so now both a and b are 2. print(a, b) prints the values of a and b, separated by a space: 2 2 A variable can only have one value at a time. a = 1 # a is 1 a = 2 # now a is 2, the previous value (1) is lost a += 1 # now a is 3 (same as a = a + 1) a = 'hello' # now a is something entirely different
27th Mar 2019, 6:31 AM
Anna
Anna - avatar
+ 1
Thanks, Anna and Mishra:). So, what youre saying, is that on line 3 "(a,b =2, a+1)" a actually changes value 2 times? From 1, to 2 (as Anna kindly listed above)? Thanka for your help. I think I can see my mistake now.
27th Mar 2019, 10:08 AM
tristach605
tristach605 - avatar
0
Thanks for your help. Still not quite clear though. I can see how b would be "22". But the two numbers assigned to the value of "a" are "1" and "2". Where is the comman to make the "1" a "2"? Thanks:).
27th Mar 2019, 3:40 AM
tristach605
tristach605 - avatar
0
Thanks so much Anna! I really appreciate it. 👍🏻
27th Mar 2019, 10:31 PM
tristach605
tristach605 - avatar