An interactive introduction to programming in Python, for human beings and whoever else
Chapter 12
When we last were talking about meowing cats, our code looked like this.
sound = input("What sound does the animal make?") if sound == 'meow meow': print("It's a cat!")
If we answered the prompt with meow meow
, Python says it’s a cat, but if we say woof woof
she doesn’t say anything. Did she even hear us??? I don’t like to be ignored, so let’s make a little tweak! I also want to run some code when the sound is not meow meow
.
sound = input("What sound does the animal make?") if sound == 'meow meow': print("It's a cat!") else: print("It's not a cat.")
Try to run it and answer it with both meow meow
and woof woof
.
When you’re writing an if statement, you can also add an else
onto it. If the condition isn’t true — in this case, if sound
is not 'meow meow'
— Python skips down to the else
part and runs the indented code there. Notice that else
has a :
after it, and the next line is indented, just like we did with if
.
Python only runs the else
part if the sound is not meow meow
.
Right now we only check to see if the sound is a cat. Add to the code below to also check if the animal is a dog.
"It's a dog!"
"It's not a dog."
Be sure you’re only adding extra code - it should still check for a cat, too.
sound = input("What sound does the animal make?") if sound == 'meow meow': print("It's a cat!") else: print("It's not a cat.")
woof woof
, it should print It's not a cat.
It's a dog!
print("It's not a cat")
input
onceThat’s better, I guess! But I mean, obviously a cat isn’t a dog, it seems silly to print both "It's not a cat"
and "It's a a dog!"
, right?
I think it would make sense to only check if the animal is a dog if we know it is not a cat. So one final adjustment:
sound = input("What sound does the animal make?") if sound == 'meow meow': print("It's a cat!") elif sound == 'woof woof': print("It's a dog!") else: print("I don't know what animal it is.")
Try to run it, testing what happens if you type meow meow
, woof woof
, or anything else.
elif
stands for else if
, which is like an else
(run if things are false) plus an if
statement (check if something is true). In this example…
"It's a cat!"
and stops."It's a dog!"
and stops."I don't know what animal it is."
If we wanted to, we could put dozens of elif
statements in row, one for each kind of animal we can think of! It might get boring to type it all out, but it’s definitely possible.
Whew, okay. Let’s just practice this for a million years until we get it down.
We learned about a few other types of if statements, like how to use elif
and else
to only run certain pieces of code when the if
gets a “no” answer.
I thought we were doing enough already, but if you’d like yet another vocabulary word, this is also called flow control.