if elif else
After working through this lesson, you’ll be able to
- Write Python code using if else statements.
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.
Sometimes a problem will have multiple conditional cases.
- 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.
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
- 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":
elif gas == "plus":
elif gas == "premium":
elif gas == "diesel":
print("Invalid Gas Type")