Conditionals
0. Learning objectives
- Understand how to make decision in a program
- Use conditional statements to change the flow of execution of your program
1. Conditionals We talked about how to write and call functions to perform calculations that are abstracted
in terms of some input variables. However, we were still pretty much using
It would be nice to be able to make decision about what statement to execute based, maybe on the value of a variable. Why is this useful? What if you want to write a program that users from different parts of the world can use? You might want to be able to ask the users about their favorite language and, based on their answer show messages in that language. In order to do this, your code has to be able to choose between different chunk of code to execute. We can do this using conditionals. Conditionals are control structures that allow us to perform different calculations (choose which
block of code to execute) depending on a condition that should evaluate to either
Remember the comparison operators we saw when discussing expressions? They're really
useful for making decisions in your programs. As an example, think about how your
alarm works. How does it know when to wake you up? Let's assume it keeps track of a
|
Whenever a squirrel reaches a fork in a tree, it must decide which branch to continue on next in order to reach it's nest. |
But how does the alarm know that time has reached wake_up? Here is where the
idea of condition comes in. The alarm will ring if some condition is true. In our case, a
reasonable condition could be time == wakeUp (notice the ==). Whoever designed
your alarm probably implemented a conditional like this (and added other features like checking if you
hit the snooze button to determine if your alarm should go off).
The if statement
The simplest conditional is the made using an if statement. This construct allows you to
execute a code block if a condition evaluated to True
Let's look at a couple of examples by writing a couple of different functions that calculate the absolute value of a number $x$. Recall that the absolute value, denoted by $\lvert x\rvert$, is equal to $x$ if $x \ge 0$ and is equal to $-x$ if $x$ is $x \lt 0$.
The if...else statement
The if...else statement allows you to choose between two code blocks which one to execute
depending if the condition is True or False.
Let's look at some examples of if...else
The if...elif...else statement
This construct allows us to handle non-binary choices, where we might have to check for more than one
condition. Each condition will still have to evaluate to either True or False
but we can combine them to allows us to select between multiple options.
And here are is an example.
So, to summarize:
- Tell
Pythonyou are starting a conditional statement with theifkeyword. Any conditional must start with theifkeyword. - After the
ifkeyword, you need a conditional expression that evaluates toTrueorFalse, or a variable that contains a Boolean. A conditional expression will typically involve using a comparator (<,>,<=,>=,==,!=). - Use a colon (
:) after the conditional expression to tellPythonyou're ready to start branching (choosing between different code blocks) in the execution of your program. When your conditional expression evaluates toTruethen the block of code immediately after the conditional will be executed. Note that this block of code must be indented relative to yourifkeyword. - optional: use an
elifkeyword (aligned with the firstifkeyword) along with another conditional to control whether another block of code is executed in the event the previous conditional isFalse. Note: you can have as manyelifs as you want! -
optional: use an
elsekeyword (aligned with the firstifand the followingelif, if any) to control whether a block of code is executed in the event that allifandelifevaluated toFalse. Note: there is no conditional expression to write after theelsekeyword. Simply use a colon (:) after theelsekeyword and follow the same principle of indenting the code block you want executed. - At most one of the code blocks will be executed depending on your conditions.
Since if statements are nothing more than code, you can also nest if statements
within other if statements. It is totally legit!
Exercise: weather forecaster
As mentioned above, you can have an if statement nested within
other if statements. Write a function get_weather_forecast
that takes two arguments: a temperature T (degrees Fahrenheit) and a precipitation
P (in percent)and returns (not print) a message as to what the weather will be for
the day.
Here are the rules to ue to determine the message you should return for the different cases:
- If the temperature is below 36F and the precipitation is above 70%: return
it will be cold and snowy. - If the temperature is below 36F and the precipitation is above 30%, but below 70%: return
it will be cold and cloudy. - If the temperature is below 36F and the precipitation is below 30%: return
it will be cold and sunny. - If the temperature is above 36F and the precipitation is above 70%: return
it will be warm and rainy. - If the temperature is above 36F and the precipitation is above 30%, but below 70%: return
it will be warm and cloudy. - If the temperature is above 36F and the precipitation is below 30%: return
it will be warm and sunny.
You can write your function directly in the code editor below and check your results by running it!
You can use your very own weather forceaster function to determine which weather icon should be used for today's weather in Middlebury. You can visit the AccuWeather website to find the temperature and precipitation values for a particular day. Scroll down, click on the "+" next to "Today" and then "more details" to see the temperature and precipitation charts.
As an extra challenge, try to incorporate some "wind" variable (W) into your function and
change your code to also report if it will be windy if W is greater than 20 mph.