Swapping Using Two Variables in Python

Swapping Using Two Variables in Python

So, today we'll learn how we can swap using two variables only. using three variables is popular among programmers and they think it can't be done using two variables. 

But it's not the case it can be done, of course in certain conditions, such as only in numbers. We can use some maths and sort the values of variables easily. Let's how to do swapping in python using two variables only.

EASY CHEESY

So, here's the logic which you need to understand, instead of memorizing the code.

Let's consider:

a = 1

b = 2

So we'll do some maths in it to swap it.

a = 1 + 2, a is now equal to 3 

b = 3 - 2, b is now equal to 1 

and finally,

a = 3 - 1, a is now equal to 2.

swapping done using some simple maths. Here's how you can do it in python.


 




Comments

Popular posts from this blog

Pseudocode to Check, Number is Odd or Even

How to Create Marksheet in C