If, Elif and Else Statements in Python




If statements allow you to examine the current state of a program and respond appropriately to that state.

You can write a simple if statement that checks one condition, or you can create a complex series of if statements that identify the exact conditions you’re looking for.

We will create a program to check if someone is old enough to vote

age = 19
if age >= 18:
    print("You're old enough to vote!")

Here is an example of a simple if statement – The program will compare the value stored for age (in this case 19) and the value 18. If the age is greater than or equal to 18, the program will print out You’re old enough to vote! Otherwise, if the age was less than 18 no statement will be printed

What about if we wanted to tell the user that they are not old enough to vote? we can expand the previous by the previous program by adding an else statement

age = 10
if age >= 18:
    print("You're old enough to vote!")
    print("You can't vote yet.")

Now if we run the program it will compare the age to 18, as 10 is smaller than 18 it will skip the first print statement just like the previous program. Instead of printing nothing the program will print the else statement in this case You can’t vote yet.

What about if we wanted to check multiple conditions? We can use elif

We will create a program which checks a users age and decides what the entry fee should be:

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
    price = 10
print("Your cost is $" + str(price))

This program will first compare the age to 4, In this case the age is 12 which is grater than 4 so the first statement is skipped. The next statement checks to see if age is less than 18, in this case it is so we price is set to 5. The else statement is skipped so the final output is Your cost is $5

The basic structure for an if statment is:

if condition:
elif condition:
  • The if,elif and else must be in lower case
  • The condition does not need to be in brackets
  • There needs to be a colon (:) after the statement
  • The statement must be indented but does not need any type of brackets around it;