Lesson 8. Control Flow With if-elif-else

Creating branching structures is computer science 101. Practically every language has an if-if else-else structure that you can use. This is Python’s.

if-elif-else Syntax

if condition:
    #perform some task
elif condition:
    #if the initial condition isn't met and this condition is met, do this instead
elif condition:
    #if the previous condition are not met and this condition is met, do this instead
else:
    #if none of the preplanned conditions are met, perform this task

Examples

Basic If Else Example

age = 25

if age > 21:
    print('You can serve this person beer.')
elif 21 > age >=18:
    print('No beer. Mark hand with X.')
else:
    print('Call the bouncer and have this person thrown out.')

Nested If Else Example

age = 21
all_ages_show = True
birthday_on_id_equals_today = True

if age >= 21:
    print('You can serve this person beer.')
    if birthday_on_id_equals_today:
        print('HAPPY BIRTHDAY! FREE SHOTS!')
elif 21 > age >=18:
    if all_ages_show:
        print('No beer. Mark hand with X.')
    else:
        print('Call the bouncer and have this person thrown out.')
else:
    print('Why is there a child in the bar?!')

Now you try it!

Don't copy and past. Type the code yourself!

Last updated