dàn âm thanh hội trường, âm thanh lớp học, âm thanh phòng họp, loa trợ giảng

Python Swap Two Variables

Python Swap Two Variables

In computer programming, swapping two variables specifies the mutual exchange of values of the variables. It is generally done by using a temporary variable.

SGK, sách ôn thi, sách tham khảo giá rẻ

See more: Python Solve Quadratic Equation

For example, before swapping: var_1 = 1  and var_2 = 5. After swapping, var_1 = 5 and var_2 = 1.

Python Swap Two Variables Using Temporary Variable

We use a temporary variable temp to store the value of var_1, then assign the value of var_2 to var_1. Finally, we assign the value of temp to var_2.

var_1 = input('The fisrt variable = ')
var_2 = input('The second variable = ')

temp = var_1
var_1 = var_2
var_2 = temp

print(var_1, var_2)

input()

Python Swap Two Variables Using Assign Multiple Variables

var_1 = input('The fisrt variable = ')
var_2 = input('The second variable = ')

var_1, var_2 = var_2, var_1

print(var_1, var_2)

input()

Python Swap Two Numbers Without Using a Temporary Variable

When the type of two variable is number (integer, float…) we can swap them without using a temporary variable.

SGK, sách ôn thi, sách tham khảo giá rẻ
var_1 = float(input('The fisrt variable = '))
var_2 = float(input('The second variable = '))

var_1 = var_1 + var_2
var_2 = var_1 - var_2
var_1 = var_1 - var_2

print(var_1, var_2)
input()

 


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *