0

I just started self-learning Python and I stumble a sorting activity base on user input.

This is the code:

a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
c = int(input("Enter Num3:"))
d = int(input("Enter Num4:"))

if a > b: b, a = a, b
if b > c: c, b = b, c
if c > d: d, c = c, d
if a > b: b, a = a, b
if b > c: c, b = b, c
if a > b: b, a = a, b

print(d, c, b, a)

I have a basic knowledge in if-else statement but I'm lost on what happened in this line if a > b: b, a = a, b. Please explain it to me. Thank you

Yuu
  • 619
  • 3
  • 13
  • 34

2 Answers2

1

its a swap operation assigns value of a to b and vice versa.

a, b = 3, 4 # assign 3 to a, 4 to b
a, b = b, a
print(a, b) # prints "4 3"
Ach113
  • 1,775
  • 3
  • 18
  • 40
0

x, y is decomposed tuple, where x is first element of ordered pair and y is second. = is assignment operator. So basically b, a = a, b swaps values: b becomes a and a becomes b.

pair = (1, 2)
(x, y) = pair
x, y = pair  # you can omit parenthesis
x, y = y, x  # assign new values
Zazaeil
  • 3,900
  • 2
  • 14
  • 31