This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: If statements

Multi-way selection

face Josiah Wang

We have also looked at how you can nest a selection block inside another selection block.

Nested selection block

if user_guess == 42:
    print("Correct")
else:
    if user_guess < 42:
        print("Too low")
    else:
        print("Too high")

But this might get a bit too messy and hard to read if you overdo it.

if user_guess == 42:
    print("Correct")
else:
    if user_guess == 41:
        print("Very very very close")
    else:
        if user_guess == 40:
            print("Very very close")
        else:
            if user_guess == 39:
                print("Very close")
            else:
                if user_guess == 38:
                    print("Close")
                else:
                    if user_guess == 37:
                        print("Close-ish")
                    else:
                        ...

Python offers a more elegant solution for this: a multi-way selection statement.

The multi-way selection block

if user_guess == 42:
    print("Correct")
elif user_guess == 41:
    print("Very very very close")
elif user_guess == 40:
    print("Very very close")
else:
    print("Incorrect")

elif means “else if”. It’s just shorter (aligns better with else)!