This is an archived version of the course. Please see the latest version of the course.

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 Java either). You can use if-elif-else for this. Alternatively, use a dict to simulate this (which is much more efficient and easier to read).

>>> key = "c"
>>> choices = {"a": 1, "b": 2, "c": 3}
>>> result = choices.get(key, -1)
>>> print(result)

The code above attempts to simulate the following Java code snippet:

// This is Java code, not Python!!
class Switch {
    public static void main(String[] args) {
        char key = 'c';
        int result;

        switch(key) {
            case 'a':
                result = 1;
                break;
            case 'b':
                result = 2;
                break;
            case 'c':
                result = 3;
                break;
            default:
                result = -1;
        }
        
        System.out.println(result);
    }
}

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)