5  Conditional

5.1 IF statement

5.1.0.1 if elif else Structure

temp = 15

if temp > 30:
  print("Too hot")
elif temp > 20:
  print("It's about right")
else:
  print("It's cold")
  
print("Bye!")
It's cold
Bye!

5.1.0.2 Ternary Operator

This is long

score = 4

if score >= 5:
  msg = "pass"
else:
  msg = "fail"

print(msg)
fail

use Ternary Operator instead

value_if_true if condition else value_if_false
score = 7

msg = "pass" if score >= 5 else "fail"
msg
'pass'

5.1.0.3 Logical Operators

and or not they can be short-circuited.

high_income = True
good_credit = False
student = False

if (high_income or good_credit) and not student:
  print("eligible")
else:
  print("not eligible")
eligible

5.1.0.4 Chaining Comparison Operators

age = 23

if 18 < age < 60:
  print("eligible")
eligible

5.2 Execute based on argument type

def handle_float(x: float) -> None:
    print("x is float")

def handle_list(x: list) -> None:
    print("x is list")

def num_or_list(x: float | list) -> None:
    type_handler = {
        float: handle_float,
        list: handle_list,
    }
    handler = type_handler.get(type(x))
    if handler:
        handler(x)
    else:
        print("Unsupported type")
num_or_list(2.1)
x is float
num_or_list(["x", "y"])
x is list