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

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python program to swap two variables

Complete Python examples

In this example, you will learn to swap two variables using a temporary variable (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 the swap: {}'.format(x))
print('The value of y after the swap: {}'.format(y))

Output result

The value of x after the swap: 10
The value of y after the swap: 5

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

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 no temporary variables are used.

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

Complete Python examples