Skip to content

Chapter 5

Jarlin Almanzar edited this page Oct 28, 2019 · 2 revisions

IF Statements

We use If statements to examine a set of conditions and deciding which action to take based on actions.

if and else Example

cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car is 'audi':
        print(car.upper())
    else:
        print(car.lower())

Conditions

car = 'bmw'
car == 'bmw'
car is 'bmw'

Conditions like equal are sensitive to case
Conditions: =, !=, >, <, >=, <=

toppings = ['Pepper', 'mushroom']
for topping in toppings:
    if topping is not 'mushroom':
        print(topping)

Multiple Conditions

age = 19
if age < 21:
   print("You can not drink")
else: 
   print("You can drink")

if age > 18 and age < 21:
   print("You are an adult but you can not legally drink")

Checking whether a value is in the list

# in
req_tops = ['mushrooms', 'onions', 'onions', 'pineapple']
is_in = "mushrooms"
print(is_in in req_tops)

Boolean Expressions

A boolean expression is just another name for a conditional test, that result being True or False

If Statements

if conditional_test:
do something

If-elif-else

age = 12
if age < 4:
    print("Admission Cost is $0")
elif age < 18:
    print("Admission Cost is $25")
else: 
    print("Admission Cost is $40")

Omitting the Else block

The else block is not required in python, thus you can have a chain of Elif blocks without needing an else statement.

Alien color

alien_color = ['red', 'yellow', 'green']
alien = alien_color[2]

if alien is "green":
    print("You have earned 5 points")
elif alien is "yellow":
    print("You have earned 1 points")
elif alien is "red":
    print("You have earned 2 points")

Stages of life elif

age = 24

if age < 2:
    print("You are a baby")
elif age > 2 and age <= 4:
    print("You are a toddler")
elif age > 4 and age <= 13:
    print("You are a kid")
elif age > 13 and age <= 20:
    print("You are a teenager")
elif age > 20 and age <= 65:
    print("You are an Adult")
elif age > 65:
    print("You are an elder")

List and if-else

toppings = ['Pepper', 'mushroom', 'pep', 'onions', 'bbq']

for top in toppings:
    if top is 'Pepper':
        print(f"Adding {top}")

Checking that a list is not empty

toppings = ['Pepper', 'mushroom', 'pep', 'onions', 'bbq']

if toppings:
    for top in toppings:
        if top is 'Pepper':
             print(f"Adding {top}")
else:
     print("Are you sure you want a plain pizza")