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.
To swap two variables, you can use a temp variable.
a = 5
b = 7
print('a, b', a, b)
# swap these two
temp = a
a = b
b = temp
print('a, b', a, b)
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 = 12
y = 33
print('x, y', x, y)
#swap these two
x, y = y, x
print('x, y', x, y)
If both the variable is number, you can apply other tricks. Like the one below-
a = 5
b = 7
print('a, b', a, b)
# swap these two
a = a + b
b = a - b
a = a - b
print('a, b', a, b)
How would you swap two variables?
- Using two temporary variables
- My family doesn’t permit swapping
- Use something like: a, b= b, a
Show Answer
The answer is : 3
Use temp variable to swap two variables.
tags: programming-hero
python
python3
problem-solving
programming
coding-challenge
interview
learn-python
python-tutorial
programming-exercises
programming-challenges
programming-fundamentals
programming-contest
python-coding-challenges
python-problem-solving