2.3 - If-else and if-elseif statements

You can use an else or elif (else-if) statement after the if clause to specify additional conditions. An else statement is used here to tell the user if the guess is incorrect:

correct_word = "module"
guess = "read"

if correct_word == guess:
    print("The word was correct!")
else:
    print("Sorry, the word was " + correct_word)

The code in the else clause will run when the if statement is not true. (correct_word != guess)

Let's create a yes/no picker which will use a elif statement.

elif is short for else if

The elif statement works just like the if statement.

selection = input("Yes or no?")

if selection == "yes":
    print("You said yes!")
elif selection == "no":
    print("You said no!")
else:
    print("You did not say yes or no!")

You don't need an else statement. This code is also valid:

if a == b:
    print("a is equal to b")
elif a == c:
    print("a is equal to c")

There was meant to be an ad here. Support us by turning off your ad blocker or donating.