Control flow
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")
(No) switch statements
There are no switch
statements in Python (and I honestly do not use it much in C++ either). 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;
}
Update!
Python 3.10 (released 4th October 2021) introduced a new Structural Pattern Matching feature with a match...case
statement. Thanks to the anonymous student on the EdStem board for the tip!
Do note that we are still using Python 3.8 this term, so do not use this new feature in your courseworks!
# 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)