21
If This... Then That
If learning to code with math examples are the bane of your existence, keep reading. This series uses relatable examples like animals.
Jump To:
Reading these types of statements properly will be immensely helpful to you while coding. For starters, we code from left to right. As you’re reading, the side you get to first is the part you want to pay attention to. If the little pointy side is first, on the left, then that is a less than sign. If the big open mouth side is first, on the left, then it is a greater than sign. Here’s a quick example to help you practice reading them correctly.
# common number of feet for each
dog_feet = 4
person_feet = 2
dog_feet > person_feet
person_feet < dog_feet
We can also say something is <=
or >=
. If you were deciding whether or not it is freezing outside, you may say “if the temperature is <= 32°F or 0°C, then it is freezing”.
temp_f = 30
freezing = temp_f <= 32
Now that you can definitely read these less than and greater than signs, let’s talk about what we use them for. Remember the type of data we called “boolean”? In code, we use them to help us know if a statement is True
or False
. In the feet comparison example we just used, both statements are true. Though, this isn’t always the case in code. Sometimes statements are true and sometimes they are false. These are typically used in if
statements to help us make decisions. We’ll go over those shortly.
# common number of feet for each
dog_feet = 4
fish_feet = 0 # I hope
fish_feet > dog_feet # this is False
dog_feet * 2 < fish_feet * 10 # this is also False
A quick reminder: variables use one equals sign =
to assign the value on the right to the variable name on the left. That’s not its only job though, the =
is overloaded with work. It has lots of jobs in programming. Its first job is to assign values to variables. Its other jobs are to help us compare things, but it will look a little different. If we use two equals signs ==
it means we are trying to compare whether or not the things on either side are of the same value. The side an item is on doesn’t matter. We just want to know if the items are the same integer, string, boolean, etc. I would read thing_1 == thing_2
as “thing_1 is the same value as thing_2”.
That’s great, but what if we specifically want to know if something is not the same as something else? I’m so glad you asked, we have something for that too. Instead of two equals signs, we use !=
. In programming, almost always !
translates to not
. So, this time, we’d read thing_1 != thing_2
as “thing_1 is not the same value as thing_2”.
Like <
or >
, ==
and !=
are also generally used with if
statements. Really, any time we are comparing things, you’re likely to see some version of an if
statement.
# common number of lungs for each
snail_lungs = 1
fish_lungs = 0
horse_lungs = 2
snails = 2 # we have 2 snails
fish_lungs == snail_lungs # this is False
snail_lungs == fish_lungs # yep, still False
snail_lungs * 2 == horse_lungs # finally, a True comparison
fish_lungs != snail_lungs # this is True
snail_lungs != fish_lungs # yep, still True
snail_lungs * 2 != horse_lungs # this one is False
house_cat_sound = "meow"
snow_leopard_sound = "meow"
cheetah_sound = "meow"
print(house_cat_sound == snow_leopard_sound == cheetah_sound)
print(house_cat_sound != snow_leopard_sound)
dog_sound = "woof"
print(house_cat_sound == snow_leopard_sound == cheetah_sound == dog_sound)
print(cheetah_sound != dog_sound)
Now that we know how to compare, let’s talk about Python’s logical operators. We use these operators, or words, to help us arrange things logically.
Imagine you have a bunch of things to do today. On your to-do list, you have: do laundry, play games, clean the kitchen, and feed dogs. From your to-do list, some of these things must be done and some could wait until later. We can use keywords to explain which ones are necessary, which are maybe getting done, and which ones are not going to be done today.
Here's our to-do list:
When conditions are optional, we use or
. You realize the kitchen isn’t actually that messy and you still have enough clothes for tomorrow. Now that you know you don’t have to do both, you will have time to play games. Now, let’s put this into code.
There is the option to do kitchen or laundry
, then we know we have to feed the dogs. So, we end up with kitchen or laundry and feed_dogs
. Wait, we need games too and only have energy for three things on our list! Today, we decide the kitchen will probably not get done.
With both and
and or
, we are checking to see if things are True
. With and
, the condition to the right of it must be True
. With or
, one or both of the conditions must be True
.
Next, we have not
, which is generally all by itself. This will use a boolean value, like True
, and make it the opposite. Imagine you want to know if it is raining. If someone says it is not raining
, that would make raining
, False
. In our to-do list example, the kitchen needs to be cleaned and we have kitchen = True
. If we say, not kitchen
, that means we have decided not to clean the kitchen. Here’s what this to-do list could look like in code.
# all tasks need to be done, so we start them as True
kitchen = True
laundry = True
games = True
feed_dogs = True
# if we had energy for all tasks
kitchen or laundry or games and feed_dogs
# only energy for three tasks
not kitchen # guess we’ll do it tomorrow
chores_done = (laundry or games) and feed_dogs
print(chores_done)
Notice how we have parentheses ()
. Just like in math, there is an order of how things are done. In Python, and
will always happen first, unless there are parentheses. We need them to show we have energy for laundry or games, but we also have to feed the dogs. Without the parentheses, we could be saying we have energy for games and feeding dogs or we have energy for laundry.
Wanna test this further? Try changing around the boolean values for the tasks.
Similar to <
or >
and ==
and !=
, or
, and
, and not
are also often used with if
statements.
Have you ever made a decision before? Maybe you’ve decided what to eat for dinner, what to wear today, or even what colors to mix to make another color. These are all things we can use code to help us with. The most basic way to make decisions is set up to be read like: “If something is True, then we will do this. If it isn’t True, we will do something else.”
First, let's talk about if
statements. I’ve mentioned them a few times and how we can use the comparison operators (<
, >
, <=
, >=
, ==
, !=
) and logical operators (or
, and
, not
) with them. If
statements/blocks only cover “If something is True, then we will do this”. Shall we jump into an example?
if current_c_temperature <= 15: # about 60F
print("chilly outside, wear warm clothes & limit time outside")
If the first line of our code, the if
statement, is True
then we will do the code in the if
block. An if
block is defined by the lines underneath the if
line that are tabbed in. The block ends when a line is no longer tabbed in. Great, we know what to do if it’s cold outside, but what if it’s not?
If your if
statement is False
, we can do something else. We can add an else
block. An else
block includes a line that says else:
and the tabbed in lines that happen if the if
statement was False
. With our temperature example, let’s add in an else
block.
if current_c_temperature <= 15: # about 60F
print("chilly outside, wear warm clothes & limit time outside")
else:
print("have fun outside, it’s not too cold")
If we were going to read this out loud, we’d say something like: “If the current celsius temperature is below 15 degrees, we should wear warm clothes and limit time outside. If the current celsius temperature is not below 15 degrees, we shall do something else. We will leave our jackets inside and have fun outside.”
Of course these aren’t the only possible temperatures, right? There’s more than just cold and not cold. For situations like this, we can have multiple test conditions.
For multiple conditions, we have elif
blocks. These look exactly like if
blocks, but with an el
in front of it. They go in between if and else blocks. Time to adjust our example again.
if current_c_temperature <= 15: # about 60F
print("chilly outside, wear warm clothes, limit time outside")
elif current_c_temperature >= 15 and current_c_temperature <= 28: # between ~60F and ~82F
print("have fun outside, it’s not too cold or too hot")
else:
print("Wear light clothes, avoid long time in sun, drink extra water")
Notice that only one of the blocks is actually going to be used. This is the goal. We want to use if-elif-else blocks to help us make decisions.
if sweater_sleeves == 8:
print("give to spider, squid, or octopus")
elif sweater_sleeves > 4 and sweater_sleeves <8:
print("give to butterfly, bumble bee, grasshopper")
elif sweater_sleeves == 4 or sweater_sleeves > 2:
print("give to 3 or 4 legged dog")
elif sweater_sleeves == 2 or sweater_sleeves == 1:
print("give sweater to human with 1 or 2 arms")
elif sweater_sleeves == 0:
print("give sweater to your snake friend")
else:
print("sweater is broken, make another one")
Here's some practice challenges. Let’s practice what we’ve learned so far. Go ahead and comment on this post with your answers. Do you remember? If not, you can always go back to read sections again.
Example | How you’d read it out loud | |
---|---|---|
Comparison Operators | ||
(< , > , <= , >= , == , != ) |
||
Logical Operator and
|
||
Logical Operator or
|
||
Logical Operator not
|
You are more than welcome to test these out. Don’t expect yourself to understand everything right away. Do test yourself first though.
True or False
|
|
---|---|
skyscraper_size < bicycle_size |
|
eat_food and drink_water |
|
your_age == parent_age |
|
num_dinosaurs_alive >= num_chickens_alive |
|
not millionaire |
|
cheetah_top_speed <= sloth_top_speed |
|
apple_weight != watermelon_weight |
|
snowing or !snowing |
|
dog_age_in_human_years * 7 > your_age |
Don’t forget that you can and probably should start with pseudocode.
Some ideas: when to play with dog, what’s for dinner, what movie you want to watch next, water flowing through pipes, or anything else.
# if something is True,
# then we do this
# if not that, maybe this is True, if it is
# then we do this
# if none of those, something else
# then we do this
Thank you to @andyhaskell for reviewing and the very first owner of Sleevonista™ Original sweater.
21