If, Elif, Else Statements

Programming starts and ends at control flow. Decisions need to be made to carry out the functions you write. We make decisions use the if, elif, and else statement. Like any other programming language, the semantics of the statements work the same, but the syntax differs. Let's try some examples.


In [7]:
you = "ready"

if you == "ready":
    print("Vamanos!")
else:
    print("What's wrong?")


Vamanos!

Imagine you've written a magic number program, and the system outputs a message to indicate your correctness. Here, the if checks the most specific condition -> if the user is right. As we move down, we become more general. This is the typical layout of control flow in programming.


In [5]:
magic_number = 24
my_guess = 29

if my_guess == magic_number:
    print("Correct!")
elif magic_number == (my_guess-1) or magic_number == (my_guess+1):
    print("So, so close!")
else:
    print("Wrong!")


Wrong!

Let's output a message depending on where you are going.


In [6]:
my_place = "Grocery store"

if my_place == "work":
    print("Clock out early!")
elif my_place == "Grocery store":
    print("Run those errands!")
else:
    print("Where are you going?")


Run those errands!

We can nest ifs, elifs, and elses, too!


In [10]:
# A simple pet and breed printer
pet = "Dog"
breed = "Labrador"

if pet == "Cat":
    print("Pet: cat")
    if breed == "Siberian":
        print("Breed: Siberian")
    else:
        print("Breed: Not specified clearly")
elif pet == "Dog":
    print("Pet: Dog")
    if breed == "Labrador":
        print("Breed: Labrador")
    elif breed == "Husky":
        print("Breed: Husky")
    else:
        print("Breed: Not specified clearly")
else:
    print("I have no idea what that is!")


Pet: Dog
Breed: Labrador

In [ ]: