Python for C++ Programmers
Chapter 6: Control flow
Control flow
If-elif-else statements
Besides if and if-else statements, Python also offers a if-elif-else statement. elif is just short for “else if”, and also aligns better with else!
if user_guess == 42:
print("Correct!")
elif user_guess < 42:
print("Too low")
else:
print("Too high")
Switch statements
There are no switch statements in Python before version 3.10. You can use if-elif-else for this. Alternatively, use a dict (which is much more efficient).
>>> key = "c"
>>> choices = {"a": 1, "b": 2, "c": 3}
>>> result = choices.get(key, -1)
This attempts to simulate the following C++ code snippet:
// This is C++ code, not Python!!
int result;
char key = 'c';
switch(key) {
case 'a':
result = 1;
break;
case 'b':
result = 2;
break;
case 'c':
result = 3;
break;
default:
result = -1;
}
Switch statements in Python 3.10
Python 3.10 (released 4th October 2021) introduced a new Structural Pattern Matching feature with a match...case statement.
# Python >=3.10 only!
key = "c"
match key:
case "a":
result = 1
case "b":
result = 2
case "c":
result = 3
case _:
result = -1
print(result)