Lesson 7: Conditional Statements#

This lesson is modified from conditional statement from geo-python.

Binder


Objectives#

By the end of this lesson, you will be able to

  • make choices in our code using conditional statements (if, elif, else)

  • use boolean values (True, False) in your code

  • use for loop and if condition together in your code


1. Basics of conditional statements#

Conditional statements can change the code flow based on certain conditions. The idea is simple: If a condition is met, then a set of actions are performed.

1.1 A simple conditional statement#

Let’s look at a simple example with temperatures, and check if the temperature 17 (celsius degrees) is hot or not.

temperature = 17

if temperature > 25:
    print(f"{temperature} is hot!")
else:
    print(f"{temperature} is not hot!")
17 is not hot!

What did we do here? First, we used the if and else statements to determine what parts of the code to execute.

What do these tests do? The if statement checks to see whether the variable value for temperature is greater than 25. If this condition were true, '17 is hot' would be written to the screen. Since 17 is smaller than 25, the if condition is false and thus the code beneath else is executed.

Notice that the code indented under the if statement is not executed if the condition is not true. Instead, code under the else statement gets executed. The code under the else statement will run and only run whenever the if condition is false.

Check your understanding#

Update the value of temperature to a “hot” temperature and write an if statement that prints something like “30 is hot!”.

Hide code cell content
# Here's one possible solution
temperature = 30

if temperature > 25:
    print(f"{temperature} is hot!")
else:
    print(f"{temperature} is not hot!")
30 is hot!

if without else?

The combination of if and else is very common, but the else statement is not strictly required. Python simply does nothing if the if statement is False and there is no else statement.

Try it out yourself by typing in the previous example without the else statement:

temperature = 17

if temperature > 25:
    print(f"{temperature} is greater than 25")

Makes sense, right? Conditional statements always check if the conditional expression evaluates as True or False. If True, the code under the conditional statement gets executed.

In the case above, nothing is printed to the screen if temperature is less than or equal to 25.

Another example#

As it turns out, we all use logic similar to if and else conditional statements daily. Imagine you’re getting ready to leave your house for the day and want to decide what to wear. You might look outside to check the weather conditions. If it is raining, you will wear a rain jacket. Otherwise, you will not. In Python we could say:

weather = "rain"

if weather == "rain":
    print("Wear a raincoat!")
else:
    print("No raincoat needed.")
Wear a raincoat!

Note here that we use the == operator to test if a value is exactly equal to another.

Note the syntax

Similar to for loops, Python uses colons (:) and whitespace (indentations) to structure conditional statements. If the condition is True, the indented code block after the colon (:) is executed. The code block may contain several lines of code, but they all must be indented identically. You will receive an IndentationError, a SyntaxError, or unwanted behavior if you haven’t indented your code correctly.

Check your understanding#

We might also need some other rainwear on a rainy day. Let’s add another instruction after the weather == rain condition so that the code would tell us to:

Wear a raincoat
Wear rain boots
Hide code cell content
# Here's one possible solution
weather = "rain"

if weather == "rain":
    print("Wear a raincoat")
    print("Wear rain boots")
else:
    print("No rainwear needed")
Wear a raincoat
Wear rain boots

1.2 Comparison operators#

Comparison operators such as > and == compare the values on each side of the operator. Here is the full list of operators used for value comparisons in Python:

Operator

Description

<

Less than

<=

Less than or equal to

==

Equal to

>=

Greater than or equal to

>

Greater than

!=

Not equal to

Boolean values#

Comparison operations yield boolean values (True or False). In Python, the words True and False are reserved for these Boolean values, and can’t be used for anything else.

Let’s check the current value of the conditions we used in the previous examples:

temperature > 25
False
weather == "rain"
True

Here is an example#

israining=False
if israining:
    print("A coat is needed")
else:
    print("A coat is not needed")
A coat is not needed

Check your understanding#

Given the boolen variable below write a code that reduces the maximum velocity by 20% when it is raining otherwise the maximum velocity remains the same.

max_velocity = 60  #mph
israining=True 
if israining:
    max_velocity *= 0.8
print(f"The maximum velocity is {max_velocity} mph") 
The maximum velocity is 48.0 mph

1.3 if, elif and else#

We can link several conditions together using the “else if” statement elif. Python checks the elif and else statements only if previous conditions were False. You can have multiple elif statements to check for additional conditions.

Let’s create a chain of if, elif, and else statements that are able to tell us whether the temperature is above freezing, exactly at the freezing point, or below freezing.

temperature = -3
if temperature > 0:
    print(f"{temperature} degrees celsius is above freezing")
elif temperature == 0:
    print(f"{temperature} degrees celsius is at the freezing point")
else:
    print(f"{temperature} degrees celsius is below freezing")
-3 degrees celsius is below freezing

Check your understanding#

Let’s assume that yesterday it was 14°C, it is 10°C outside today, and tomorrow it will be 13°C. The following code compares these temperatures and prints something to the screen based on the comparison.

yesterday = 14
today = 10
tomorrow = 13

if yesterday <= today:
    print("A")
elif today != tomorrow:
    print("B")
elif yesterday > tomorrow:
    print("C")
elif today == today:
    print("D")

Which of the letters A, B, C, and D would be printed to the screen?

Hide code cell content
# Here is the solution
yesterday = 14
today = 10
tomorrow = 13

if yesterday <= today:
    print("A")
elif today != tomorrow:
    print("B")
elif yesterday > tomorrow:
    print("C")
elif today == today:
    print("D")
B

1.4 Combining conditions#

We can also use and and or to combine multiple conditions using boolean values.

Keyword

Example

Description

and

a and b

True if both a and b are True

or

a or b

True if either a or b is True

if (1 > 0) and (-1 > 0):
    print("Both parts are true")
else:
    print("At least one part is not true")
At least one part is not true
if (1 < 0) or (-1 < 0):
    print("At least one test is true")
At least one test is true

Note the syntax

You can also use the bitwise operators & for and, and | for or.

Check your understanding#

Let’s return to our example about making decisions on a rainy day. Imagine that we consider not only the rain, but also the wind speed. If it is windy or raining, we’ll just stay at home. If it’s not windy or raining, we can go out and enjoy the weather!

8 m/s is the limit for a “fresh breeze” and we can set that as our comfort limit in the conditional statement. In this example, let’s imagine that forecast is strong winds in Fort Myers. Let’s see what our Python program tells us to do.

Hide code cell content
# Here is the parameters
weather = "rain"
wind_speed = 9

# If  there is rain or wind above 8 m/s, print "Stay at home", 
# else print "Go out and enjoy the weather!"
if (weather == "rain") or (wind_speed >= 8):
    print("Just stay at home")
else:
    print("Go out and enjoy the weather! :)")
Just stay at home

2. Combining for-loops and conditional statements#

Finally, when coding you will be often combining for-loops and conditional statements. Let’s iterate over a list of temperatures, and check whether the temperature is hot, nice, cold.

Try this out. For each temperature:

  • if the temperature is less than 50 degrees F then print “… is cold”

  • if tempature is less than 85 degrees F degree then print “… is nice”

  • if tempature is larger than or equal 85 degrees F degree then print “… is hot”

Here is an sample of your output:

0 degrees Fehrenheit is cold
51 degrees Fehrenheit is nice
86 degrees Fehrenheit is hot
... 

Try to write this code

temperatures = [0, 28, 49, 50, 51, 84,85,86]

# For each temperature print if temp is cold, nice, or hot
for temperature in temperatures:
    if temperature < 50:
        print(f"{temperature} degrees Fehrenheit is cold")
    elif temperature < 85:
        print(f"{temperature} degrees Fehrenheit is nice")
    else:
        print(f"{temperature} degrees Fehrenheit is hot")
0 degrees Fehrenheit is cold
28 degrees Fehrenheit is cold
49 degrees Fehrenheit is cold
50 degrees Fehrenheit is nice
51 degrees Fehrenheit is nice
84 degrees Fehrenheit is nice
85 degrees Fehrenheit is hot
86 degrees Fehrenheit is hot