Switch in Latex
Here’s how the switch
statement in the provided code can be translated to Python, along with detailed explanations:
Our first example demonstrates basic switch
statements using the match
statement introduced in Python 3.10.
def main():
i = 2
print("Write", i, "as", end=" ")
match i:
case 1:
print("one")
case 2:
print("two")
case 3:
print("three")
if __name__ == "__main__":
main()
Here’s a more complex example showing how you can use a match
statement to handle multiple expressions.
import datetime
def main():
today = datetime.datetime.now().strftime('%A')
match today:
case 'Saturday' | 'Sunday':
print("It's the weekend")
case _:
print("It's a weekday")
if __name__ == "__main__":
main()
A match
statement without an expression is a way to express an if-else logic. Here’s an example showing how case expressions can be non-constants.
import datetime
def main():
t = datetime.datetime.now()
match t.hour:
case h if h < 12:
print("It's before noon")
case _:
print("It's after noon")
if __name__ == "__main__":
main()
A type match statement compares types instead of values. You can use this to discover the type of a variable. In this example, the variable i
will have the type corresponding to its case.
def what_am_i(i):
match type(i):
case bool:
print("I'm a bool")
case int:
print("I'm an int")
case _:
print(f"Don't know type {type(i)}")
def main():
what_am_i(True)
what_am_i(1)
what_am_i("hey")
if __name__ == "__main__":
main()
To run the program, save the code in a .py
file and use the python3
command.
$ python3 switch_example.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'>
Now that we can run and build basic Python programs, let’s learn more about the language.