if elif else

Objective

After working through this lesson, you’ll be able to

  • Write Python code using if else statements.

Introductory Problem

Write Python code that asks for a number and assigns the input to the variable num.

Write if statements that print the messages:

  • num is positive.

  • num is negative.

  • num is 0.

if elif else

Sometimes a problem will have multiple conditional cases.

Difference between if and if elif else

  • Python will evaluate all three if statements to determine if they are true.

  • Once a condition in the if elif else statement is true, Python stop evaluating the other conditions.

  • Because of this, if elif else is faster than three if statements.

The else is not required.

Example 1

Write Python code that asks what type of gas do you want. The average car holds about 17 gallons of gas. Print the total price based on the type of gas and 15 gallons of gas.

Type of Gas

Price per galloon

regular

$3.89

plus

$4.09

premium

$4.19

diesel

$4.59

  • If the user enters “regular”, print the total price

  • If the user enters “plus”, print the total price

  • If the user enters “premium”, print the total price

  • If the user enters “diesel”, print the total price

  • Else if the user enters something else, print invalid gas type

gas = input("What type of gas do you want? ")
if gas == "regular":
    print("Regular Gas:",3.89*17)
elif gas == "plus":
    print("Plus Gas:",4.09*17)
elif gas == "premium":
    print("Premium Gas:",4.19*17)
elif gas == "diesel":
    print("Diesel Gas:",4.59*17)
else:
    print("Invalid Gas Type")

Last updated