Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
a = 3 and b = 8. Write code that swaps them, so that a is 8 and b is 3.
Keep the first value safe before you overwrite it, or use a, b = b, a.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
The problem. If we write a = b first, the old value of a is lost.
Method 1. A spare variable.
spare = a keeps 3 safe.a = b makes a equal to 8.b = spare makes b equal to 3.Method 2. The Python way. a, b = b, a. Python works out the right side first, then stores both values.
Check. The program shows 8 3, and after the second swap 3 8 again.
Log in to join the discussion.
Loading…