Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 3.2 - Complex conditions

Chapter 3.2.1 - if statement review

The most basic if statements syntax is as follows:

if (test):
    code

In 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):
    code

In 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 <= 100

How can we use both condition1 and condition2? By using the following keywords:

  • and or &: this combines two tests by requiring both tests to be True to result in True

  • or or |: this combines two tests by requiring at least one test to be True to result in True

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 = False

Do 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)

  1. (a or b) -> (True or False) -> (1 + 0) -> 1 (True since 1 is >= 1 for OR) -> 1

  2. (d and e) -> (False and True) -> (0 + 1) -> 1 (False 1 < 2 for AND) -> 0

  3. (c or (d and e)) -> (True or (False)) (1 + (0)) -> 1 (True since 1 is >= 1 for OR) -> 1

  4. (a or b) and (c or (d and e)) -> (True) and (True) -> (1) + (1) -> 2 (True since 2 >= 2 for AND)

  5. (a or b) and (c or (d and e)) or (f) -> (True) or (False) -> (1) + (0) -> 1 (True since 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)
True

2. 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 1Condition2Condition 1 and Condition 2
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

or truth table:

Condition 1Condition2Condition 1 or Condition 2
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Example: if Condition 1 is False and Condition 2 is True, we can interpret the truth tables as follows:

and truth table:

Condition 1Condition2Condition 1 and Condition 2Result
TrueTrueTrue
FalseFalseFalse
TrueTrueFalse
FalseFalseFalse

or truth table:

Condition 1Condition2Condition 1 or Condition 2Result
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Combining or and and to see all possible combinations for both cases, and specifically if a is False and b is True:

Variable 1Variable 2Conditional Test 1Conditional Test 2Result
aba and ba or b
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse

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):

  1. temperature (degrees F, float)

  2. year (YYYY, int)

  3. month (MM, int)

  4. state (abbreviation, str).

You want to print temperature only if the following conditions are met:

  1. The year is before 2000

  2. The month is either June, July, or August

  3. The state is 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

  1. Rewrite the following if/elif/else as a match statement. Make sure that all of the variable possibilities 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)
  1. Rewrite the following if/elif/else statement as a match statement. 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)
  1. Convert the following match statement to an if/elif/else statement. 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)
  1. Rewrite the following match statment using an if/elif/else statement and the or test:

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)
  1. 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 precipitation case not work?

    • How would you fix the code to make precipitation produce 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: