Chapter 3.2.1 - if statement review¶
The most basic if statements syntax is as follows:
if (test):
codeIn this example, code will only run if test is True.
Much like the evaluation order for setting variables, test is the first thing that is processed in the if statement.
The only requirement for test is that it is a single bool after it is evaluated. This is simple if only one test is used:
temperature = 50
if (temperature > 95):
codeIn this case, temperature > 95 is recognized by Python as a test that needs to be changed into a bool. Since 50 is not greater tha 95, the bool in this case is False.
Chapter 3.2.2 - Complex conditions¶
What if you needed multiple tests? For example, say that you need to make sure the temperature was between 0 C and 100 C:
temperature = 20
condition1 = temperature >= 0
condition2 = temperature <= 100How can we use both condition1 and condition2? By using the following keywords:
andor&: this combines two tests by requiring both tests to beTrueto result inTrueoror|: this combines two tests by requiring at least one test to beTrueto result inTrue
Here is a basic example with two conditions a and b combined with and:
a = True
b = False
print("A =", a)
print("B =", b)
if a and b:
print("both a and b are True")
else:
print("a, b, or both a and b are False")A = True
B = False
a, b, or both a and b are False
Here is the same example, except combined with or
a = True
b = False
print("A =", a)
print("B =", b)
if a or b:
print("Either a is True, b is True, or both a and b are True")
else:
print("both a and b are False")A = True
B = False
Either a is True, b is True, or both a and b are True
We can combine as many tests as we like, as long as you can simplify the tests down to a single bool
Try to change a, b, c, and d to get a different result.
a = True
b = False
c = True
d = False
print("A =", a)
print("B =", b)
print("C =", c)
print("D =", d)
if (a and b) or (c and d):
print("either a and b are both True OR c and d are both True")
else:
print("either a and b are False AND either c or d are False")A = True
B = False
C = True
D = False
either a and b are False AND either c or d are False
Slowing down: Different ways to think about this:¶
1. Use bool math:
A very low-level way to look at this is to convert True to 1 and False to 0 in your head.
If you have two conditions that are either True (1) or False (0), and will require the sum to be 2 to result in True, whereas or will require the sum to be at least 1 to result in True.
This can be helpful for complex conditions:
a = True
b = False
c = True
d = False
e = True
f = FalseDo order of operation from left to right and based on the parentheses:
Complex condition to solve -> (a or b) and (c or (d and e)) or (f)
(a or b)->(True or False)-> (1 + 0) -> 1 (Truesince 1 is >= 1 for OR) -> 1(d and e)->(False and True)-> (0 + 1) -> 1 (False1 < 2 for AND) -> 0(c or (d and e))->(True or (False))(1 + (0)) -> 1 (Truesince 1 is >= 1 for OR) -> 1(a or b) and (c or (d and e))->(True) and (True)-> (1) + (1) -> 2 (Truesince 2 >= 2 for AND)(a or b) and (c or (d and e)) or (f)->(True) or (False)-> (1) + (0) -> 1 (Truesince 1 >= 1 for OR)
This will result in True. How would you change the code below to result in False?
a = True
b = False
c = True
d = False
e = True
f = False
(a or b) and (c or (d and e)) or (f)True2. Use “truth tables”
You can look at every possible combination of two bool by using truth tables. These tables simulate what would happen if one of the four possible combinations of and or or occurred:
and truth table:
| Condition 1 | Condition2 | Condition 1 and Condition 2 |
|---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
or truth table:
| Condition 1 | Condition2 | Condition 1 or Condition 2 |
|---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Example: if Condition 1 is False and Condition 2 is True, we can interpret the truth tables as follows:
and truth table:
| Condition 1 | Condition2 | Condition 1 and Condition 2 | Result |
|---|---|---|---|
True | True | True | |
False | False | False | |
True | True | False | ✔ |
False | False | False |
or truth table:
| Condition 1 | Condition2 | Condition 1 or Condition 2 | Result |
|---|---|---|---|
True | True | True | |
True | False | True | |
False | True | True | ✔ |
False | False | False |
Combining or and and to see all possible combinations for both cases, and specifically if a is False and b is True:
| Variable 1 | Variable 2 | Conditional Test 1 | Conditional Test 2 | Result |
|---|---|---|---|---|
a | b | a and b | a or b | |
True | True | True | True | |
True | False | False | True | |
False | True | False | True | ✔ |
False | False | False | False |
Try modifying the numbers below to see how it changes the results.¶
What does the following code do “in English”?
temperature = 0
humidity = 100
if (temperature <= 32) and (humidity == 100):
print("freezing fog")
elif (temperature >= 32) and (humidity == 100):
print("fog")
else:
print("clear")freezing fog
Chapter 3.2.3 - Practice¶
You have an observation that includes (unit or format, data type):
temperature (degrees F, float)
year (YYYY, int)
month (MM, int)
state (abbreviation, str).
You want to print temperature only if the following conditions are met:
The
yearis before 2000The
monthis either June, July, or AugustThe
stateis Illinois
Write a complex condition that combines multiple tests using and or or in an if / else statement to determine if you should print the temperature:
temperature = input("What is the temperature?")
year = input("What is the year?")
month = input("What is the month (1 - 12)?")
state = input("What is the state (abbreviation)?")
#### Your code below
print(temperature, year, month, state)What is the temperature? 85
What is the year? 2026
What is the month (1 - 12)? 9
What is the state (abbreviation)? IL
85 2026 9 IL
Create a complex condition using if / elif / else that you may need for your own project:
Chapter 3.2.4 - Match Statements¶
Another way to organize the if/elif logic is to use a match statement. The idea is to make it easier to use the if/elif logic in situations that do not require ranges of values, but instead need certain code blocks to be matched with specific patterns. Additionally, if there is no need to do anything if none of the conditions are met, there is no requirement for an else code block.
The typical pattern of a match statement for a string variable named variablename when testing if it is equivalent to "certain value 1" or "certain value 2" is as follows:
variablename = "certain value 1"
match variablename:
case "certain value 1":
print("Do stuff when variablename is certain_value1")
case "certain value 2":
print("Do stuff when variablename is certain_value1")Like an if/elif/else statement, once a match occurs, that code block is executed and then the match statement is exited. In the example, Python would print:
Do stuff when variablename is certain_value1
Consider the following situation where units need to be applied:
if/elif/else:
variablename = 'temperature'
if variablename == 'temperature' or variablename == 'dewpoint':
unit = 'F'
elif variablename == 'precipitation':
unit = 'mm'
elif variablename == 'windspeed':
unit = 'm/s'
else:
unit = ''
print(unit)F
match:
variablename = 'temperature'
unit = ''
match variablename:
case 'temperature' | 'dewpoint':
unit = 'F'
case 'precipitation':
unit = 'mm'
case 'windspeed':
unit = 'm/s'
print(unit)F
These two examples produce the same result. For these specific string values, the match statement avoids repeating the variable name and the == equality operator. Initializing unit to an empty string before the statement provides a default value if none of the patterns match. Alternatively, a final case _: block could assign that default, similar to the else block. This could make the above example a bit cleaner and more self-contained:
variablename = 'temperature'
match variablename:
case 'temperature' | 'dewpoint':
unit = 'F'
case 'precipitation':
unit = 'mm'
case 'windspeed':
unit = 'm/s'
case _:
unit = ''
print(unit)F
One difference in syntax is that alternative patterns are separated with | rather than or. For example, case 'temperature' | 'dewpoint': matches either string. The keywords and and or, and the operator &, cannot be used to combine patterns this way.
When selecting actions based on specific values, a match statement may be easier to read than an if/elif/else statement. For ranges or more complex Boolean conditions, if/elif/else is often more straightforward. Pattern matching can also recognize and unpack data structures, although these examples focus on matching individual strings.
Below, you can experiment with modifying the input variable value and see how that modifies the resulting printed message:
variablename = input("Provide a value for variablename")
match variablename:
case 'temperature' | 'dewpoint':
unit = 'F'
case 'precipitation':
unit = 'mm'
case 'windspeed':
unit = 'm/s'
case _:
unit = ''
print(f"variable {variablename} unit is {unit}")Provide a value for variablename temperature
variable temperature unit is F
Chapter 3.2.5 - match Practice¶
Rewrite the following
if/elif/elseas amatchstatement. Make sure that all of thevariablepossibilities work.
variable = 'pressure'
if variable == 'temperature':
instrument = 'thermometer'
elif variable == 'pressure':
instrument = 'barometer'
elif variable == 'windspeed':
instrument = 'anemometer'
elif variable == 'precipitation':
instrument = 'rain gauge'
else:
instrument = 'Unknown instrument'
print(instrument)Rewrite the following
if/elif/elsestatement as amatchstatement. Make sure all of the month possibilities produce the correct output.
month = 'January'
if month == 'December' or month == 'January' or month == 'February':
season = 'Winter'
elif month == 'March' or month == 'April' or month == 'May':
season = 'Spring'
elif month == 'June' or month == 'July' or month == 'August':
season = 'Summer'
elif month == 'September' or month == 'October' or month == 'November':
season = 'Autumn'
else:
season = 'Unknown month'
print(season)Convert the following
matchstatement to anif/elif/elsestatement. Make sure that the three possible station codes produce the correct output.
station = 'KORD'
match station:
case 'KORD':
location = "Chicago O'Hare"
case 'KDEN':
location = 'Denver'
case 'KATL':
location = 'Atlanta'
case _:
location = 'Unknown station'
print(location)Rewrite the following
matchstatment using anif/elif/elsestatement and theortest:
weather = 'snow'
match weather:
case 'rain' | 'drizzle':
color = 'green'
case 'snow' | 'flurries':
color = 'blue'
case 'sleet' | 'freezing rain':
color = 'purple'
case 'clear':
color = 'yellow'
case _:
color = 'gray'
print(color)The following code contains a logic error. Think about the following when you are starting to “debug” the code:
Without running the code, what should it output?
Why does the
precipitationcase not work?How would you fix the code to make
precipitationproduce the correct output?
variable = 'precipitation'
match variable:
case 'temperature' | 'precipitation':
category = 'Temperature variable'
case 'precipitation' | 'snowfall':
category = 'Precipitation variable'
case _:
category = 'Other variable'
print(category)Temperature variable
After you fix the code, rewrite it as an if/elif/else statement below: