Python variable exchange
The following examples are two variables input by a user, and exchange:
# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.w3big.com # 用户输入 x = input('输入 x 值: ') y = input('输入 y 值: ') # 创建临时变量,并交换 temp = x x = y y = temp print('交换后 x 的值为: {}'.format(x)) print('交换后 y 的值为: {}'.format(y))
Execute the above code output results:
输入 x 值: 2 输入 y 值: 3 交换后 x 的值为: 3 交换后 y 的值为: 2
The above example, we created a temporary variable temp, the temp variable, then assign the value of y and x values are stored x, y finally temp assignment to a variable.
Do not use temporary variables
We can not create a temporary variable, with a very elegant way to exchange variables:
x,y = y,x
So the above example would be modified as follows:
# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.w3big.com # 用户输入 x = input('输入 x 值: ') y = input('输入 y 值: ') # 不使用临时变量 x,y = y,x print('交换后 x 的值为: {}'.format(x)) print('交换后 y 的值为: {}'.format(y))
Execute the above code output results:
输入 x 值: 1 输入 y 值: 2 交换后 x 的值为: 2 交换后 y 的值为: 1