English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Python advanced knowledge

Python reference manual

Python program to swap two variables

Python example collection

In this example, you will learn to swap two variables using a temporary variable (and without using a temporary variable).

To understand this example, you should understand the followingPython programmingTopic:

Source code: Using temporary variables

# Python program to swap two variables
x = 5
y = 10
# Accept user input
#x = input('Enter the value of x: ')
#y = input('Enter the value of y: ')
# Create a temporary variable and swap 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 result

The value of x after swapping: 10
The value of y after swapping: 5

In this program, we use the temp variable to temporarily save the value of x. Then, we put the value of y in x, and then put the value of temp in y. In this way, we can swap the values.

Source code: Without using temporary variables

In Python, there is a simple structure that can be used to swap variables. The following code is the same as the above code, but does not use any temporary variables.

x = 5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)

If all variables are numbers, you can use arithmetic operations to perform the same operations. At first glance, it may not seem intuitive. However, if you think about it, it is easy to understand. Here are some examples

Addition and subtraction

x = x + y
y = x - y
x = x - y

Multiplication and division

x = x * y
y = x / y
x = x / y

XOR swap

This algorithm is only applicable to integers

x = x ^ y
y = x ^ y
x = x ^ y

Python example collection