Skip to content

Latest commit

 

History

History
73 lines (56 loc) · 1.91 KB

File metadata and controls

73 lines (56 loc) · 1.91 KB

Swap two variables

The problem

Swap two variables.

To swap two variables: the value of the first variable will become the value of the second variable. On the other hand, the value of the second variable will become the value of the first variable.

Hints

To swap two variables, you can use a temp variable.

Solution

a=5b=7print('a, b', a, b) # swap these twotemp=aa=bb=tempprint('a, b', a, b)

Try it on Programming Hero

Shortcut

You can use a python shortcut to swap two variables as well. How this works, would be a little bit tricky for you. So, for now, just remember it.

x=12y=33print('x, y', x, y) #swap these twox, y=y, xprint('x, y', x, y)

Try it on Programming Hero

Another solution

If both the variable is number, you can apply other tricks. Like the one below-

a=5b=7print('a, b', a, b) # swap these twoa=a+bb=a-ba=a-bprint('a, b', a, b)

Try it on Programming Hero

Quiz

How would you swap two variables?

  1. Using two temporary variables
  2. My family doesn’t permit swapping
  3. Use something like: a, b= b, a
Show Answer

The answer is : 3

Take Away

Use temp variable to swap two variables.

  Next Page  

tags: programming-heropythonpython3problem-solvingprogrammingcoding-challengeinterviewlearn-pythonpython-tutorialprogramming-exercisesprogramming-challengesprogramming-fundamentalsprogramming-contestpython-coding-challengespython-problem-solving

close