Team members Beautiful Disaster by Kashif Baig

Python program to swap two numbers

  Swap two numbers by four easy methods 1) By Using a temporary variable

2) Without Using Temporary Variable 3) By Using addition and subtraction 4) Using multiplication and division 5) Using XOR swap. This algorithm works for integers only


x = 5

y = 10

# Using a temporary variable

 

temp = x

x = y

y = temp

print(f'By M-1 After swapping:x = {x}, y = {y}')

# Without Using Temporary Variable

 

x, y = y, x

print(f'By M-2 After swapping:x = {x}, y = {y}')

# Using addition and subtraction

x = x + y

y = x - y

x = x - y

print(f'By M-3 After swapping:x = {x}, y = {y}')

 

# Using multiplication and division

x = x * y

y = x / y

x = x / y

print(f'By M-4 After swapping:x = {x}, y = {y}')

 

# Using XOR swap. This algorithm works for integers only

x = int(x)

y = int(y)

x = x ^ y

y = x ^ y

x = x ^ y

print(f'By M-5 After swapping:x = {x}, y = {y}')


kashifbaig250

See more python programs to

🔗 1: Add Two Numbers 

🔗 2: Swap two numbers

🔗 3: Even or odd

🔗 4:  Python Program to find Largest of Two Numbers

🔗 5: Largest of Three Numbers

🔗 6: Centigrade to Fahrenheit and vice versa

🔗 7: Display calendar of the given month and year

🔗 8: Area of Triangle

🔗 9: Sum of digits & number of digits

🔗 10: Check Leap year or not

🔗 11: Make Simple Calculator by Using Functions

🔗 12: Find Quarqratic equation roots 

Previous
Next Post »

Pages