Write a program two swap two numbers without using any third variable | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Write a program two swap two numbers without using any third variable

Take two numbers and swap them don't use any other variables

27th Oct 2021, 2:57 PM
Prashant Chaudhari
3 Antworten
+ 5
a = 10 b = 20 a, b = b, a print(a, b) #When dealing with expressions in python, everything to the right of the ‘=’ operator, i.e. the assignment operator, is evaluated first then assigned to the variables to the left. Additionally, whenever you use a comma on the RHS, you’re telling python to create a tuple. Using a comma on the LHS tells python to unpack the tuple on the RHS into the variables on the LHS. "Remember number of variable at LHS need to be equal to length of tuple at RHS" or it will throw~ ValueError exception (too many values to unpack) eg. a, b = 10, 20 #Correct a, b = 10, 20, 30 #Wrong a, b, c = 10, 20, 30 #Correct a, b = 10, (20, 30) #Correct"
27th Oct 2021, 3:00 PM
I Am a Baked Potato
I Am a Baked Potato - avatar
+ 4
Sorry for late answering but it may also help you m = m + n n = m - n m = m - n print(m , n)
27th Oct 2021, 11:23 PM
𝓐𝓷𝓼𝓱𝓲𝓴𝓪 (Anshika)
𝓐𝓷𝓼𝓱𝓲𝓴𝓪 (Anshika) - avatar
+ 3
You can use tuple packing to accomplish this. Google or Bing it. It is also discussed in the python lessons here on Sololearn
27th Oct 2021, 3:01 PM
Paul K Sadler
Paul K Sadler - avatar