Write a program to Swap Two Variables in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Python program to swap two variables # To take input from the user x = input('Enter value of x: ') y = input('Enter value of y: ') # create a temporary variable and swap the values temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) |
Output:
The code you provided is a simple Python program that swaps the values of two variables, x
and y
.
The program starts by using the input()
function to prompt the user to enter the values of the variables x
and y
. The user’s input is stored as a string.
Next, the program creates a temporary variable temp
, and assigns the value of x
to it. Then it assigns the value of y
to x
and the value of temp
to y
. This effectively swaps the values of x
and y
.
Finally, the program uses the print()
function to output the values of x
and
yafter the swap to the console. The
format()method is used to insert the values of
xand
yinto the strings that are passed to the
print() function.
The output will depend on the input provided by the user. For example, if the user inputs “5” for x and “10” for y, the output will be “The value of x after swapping: 10” and “The value of y after swapping: 5”