Loading search index…
No recent searches
No results for "Query here"
Switch statements express conditionals across many branches. ```python import time def main(): # Here’s a basic switch. i = 2 print(f"Write {i} as ", end='') match i: case 1: print("one") case 2: print("two") case 3: print("three") # You can use commas to separate multiple expressions in the same case statement. # We use the optional default case in this example as well. match time.strftime("%A"): case "Saturday" | "Sunday": print("It's the weekend") case _: print("It's a weekday") # switch without an expression is an alternate way to express if/else logic. # Here we also show how the case expressions can be non-constants. t = time.localtime() match t.tm_hour: case _ if t.tm_hour < 12: print("It's before noon") case _: print("It's after noon") # A type switch compares types instead of values. You can use this to discover the type of a dynamic variable. # In this example, the variable item_type will have the type corresponding to its clause. def what_am_i(item): match item: case bool(): print("I'm a bool") case int(): print("I'm an int") case _: print(f"Don't know type {type(item)}") what_am_i(True) what_am_i(1) what_am_i("hey") if __name__ == "__main__": main()
$ python switch.py Write 2 as two It's a weekday It's after noon I'm a bool I'm an int Don't know type <class 'str'>