Computer Science, asked by AnanyaCharming, 5 months ago

swapping value of variables in python

Answers

Answered by Anonymous
3

Answer:

Method 1: Using Naïve approach

The most naïve approach is to store the value of one variable(say x) in a temporary variable, then assigning the variable x with the value of variable y. Finally, assign the variable y with the value of the temporary variable.

Method 2: Using comma operator

Using the comma operator the value of variables can be swapped without using a third variable.

Method 3: Using XOR

The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number which has all the bits as 1 wherever bits of x and y differ. For example XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111) and 5 (0101) is (0010).

Method 4: Using arithmetic operators

The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.

Explanation:

Answered by atrs7391
0

a = input('Enter First Value: ')

b = input('Enter Second Value: ')

print("Value of a before swapping: ", a)

print("Value of b before swapping: ", b)

c = a

a = b

b = c

print("Value of a after swapping: ", a)

print("Value of b after swapping: ", b)

Similar questions