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.