Python Program to Swap Two Variables

Here’s an example Python code to swap the values of two variables:

# Take input from the user
a = input("Enter the value of a: ")
b = input("Enter the value of b: ")

# Swap the values of a and b
a, b = b, a

# Print the values of a and b after swapping
print("After swapping:")
print("a =", a)
print("b =", b)

In this code, we use the input() function to prompt the user to enter the values of a and b, and assign them to the variables a and b.

Next, we swap the values of a and b using a single line of code: a, b = b, a. This is possible in Python because Python allows multiple assignment, which means we can assign the values of two or more variables simultaneously.

Finally, we use the print() function to output the values of a and b after swapping.

When you run this code, it should prompt you to enter the values of a and b. Once you enter those values and press enter, it should output the values of a and b after swapping. For example:

Enter the value of a: 5
Enter the value of b: 8
After swapping:
a = 8
b = 5

Note that you can replace 5 and 8 with any other values you want to swap.

Related Examples

1. Python Program to Print Hello world!

2. Calculate the multiplication and sum of two numbers

3. Python Program to Find the Square Root

4. Python Program to Calculate the Area of a Triangle

5. Python Program to Solve Quadratic Equation

6. Python Program to Generate a Random Number

7. Return the count of a given substring from a string

8. Print the following pattern

9. Python Program to check if the given number is a palindrome number

10. Python Program to print multiplication table form 1 to 10

11. Print downward Half-Pyramid Pattern with Star (asterisk)

12. Python Program to Convert Kilometers to Miles

13. Python Program to Check if a Number is Positive, Negative or 0

14. Python Program to Find the Sum of Natural Numbers

15. Print the sum of the current number and the previous number in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial