If Else Usage in Python

Itacen Sabacok | Jan 7, 2022

NOTE

  • a == b   # Equals
  • a != b    # Not Equals
  • a > b     # Greater than
  • a < b     # Less than
  • a >= b   # Greater than or equal to
  • a <= b   # Less than or equal to

If - Elif - Else Usage

 1x = 50
 2y = 100
 3z = 200
 4
 5if x > y:
 6  print("x is greater than y")
 7elif x == y:
 8  print("x and y are equals")
 9else:
10  print("y is greater than x")

If Else Single Line Usage

1# if else single line statement
2print("x > y") if x > y else print("y > x")
3
4# if else single line with multiple else statements
5print("x > y") if x > y else print("x == y") if x == y else print("x < y")

If Else AND OR Usage

1# if else AND usage
2if y > x and y < z:
3  print("both conditions are TRUE")
4
5# if else OR usage
6if y > x or y > z:
7  print("at least one condition is TRUE")

Pass Usage

1# If you have loop or function etc. that is not implemented yet, you can use pass command as an empty body. if you dont write pass command the interpreter would give an error. So, you can use the pass statement to construct a body that does nothing.
2x = 50
3y = 100
4
5if y > x:
6  pass

Nested If

 1# nested if
 2x = 50
 3y = 100
 4
 5if x > 20:
 6  print("x is greater than 20")
 7  if x > 30:
 8    print("x is also greater than 30")
 9    if x > 40:
10      print("x is also greater than 40")
11    else:
12      print("x is between 30 and 40")
13else:
14  print("x is less than 20")