Python if statements with multiple conditions (and + or) (2023)

A simple Python if statement test just one condition. That condition then determines if our code runs (True) or not (False). If we want to evaluate more complex scenarios, our code has to test multiple conditions together. Let’s see how we code that in Python.

IN THIS ARTICLE:

# Test multiple conditions with a single Python if statement

To test multiple conditions in an if or elif clause we use so-called logical operators. These operators combine several true/false values into a final True or False outcome (Sweigart, 2015). That outcome says how our conditions combine, and that determines whether our if statement runs or not.

We evaluate multiple conditions with two logical operators (Lutz, 2013; Python Docs, n.d.):

  • The and operator returns True when both its left and right condition are True too. When one or both conditions are False, the outcome that and makes is False too.
  • The or operator returns True when its left, right, or both conditions are True. The only time that or returns False is when both conditions are False too.

Don’t worry if this sounds abstract or vague; the examples below make this more practical. Speaking of which, let’s take a look at those examples.

# Multiple True conditions in an if statement: the and operator

When an if statement requires several True conditions at the same time, we join those different conditions together with the and operator. Such a combined condition becomes False as soon as one condition tests False. Let’s look at some examples.

# If statement that needs two True conditions

So when we combine conditions with and, both have to be True at the same time. Here’s an if statement example of that:

# Current temperaturecurrentTemp = 30.2# Extremes in temperature (in Celsius)tempHigh = 40.7tempLow = -18.9# Compare current temperature against extremesif currentTemp > tempLow and currentTemp < tempHigh: print('Current temperature (' + str(currentTemp) + ') is between high and low extremes.')

First we make the currentTemp variable with the current temperature. Then we create two other variables, tempHigh and tempLow. Those represents all-time records for a particular weather station.

Now we want to know if the current temperature is between those extremes. So we have an if statement test two conditions. The first sees if the temperature is above the record low (currentTemp > tempLow). The other looks if the temperature is under the record high (currentTemp < tempHigh).

We combine those conditions with the and operator. That makes our if statement only run when both are True. Since they are, that code executes and has print() display the following:

Current temperature (30.2) is between high and low extremes.

# If statement that requires several True conditions

The and operator can combine as many conditions as needed. Because each condition we add with and looks for a particular thing, our if statement can run in very specific situations.

Let’s say that a fastfood restaurant offers 4 optional extras to customers with each order. If our code should look if someone ordered all four extras, we do:

# Check which extras the customer ordereddietCoke = Truefries = Trueshake = FalseextraBurger = Trueif dietCoke and fries and shake and extraBurger: print("The customer wants:") print("- Diet instead of regular coke") print("- Extra french fries") print("- A milkshake") print("- An extra burger")else: print("The customer doesn't want diet coke, " + "extra fries, a milkshake, *and* an extra burger.")

First we make four true/false variables (dietCoke, fries, shake, and extraBurger). Those represent what extras the customer wants.

Then we code an if/else statement. To make its if code run, four conditions have to be True at the same time. That’s because we join all four true/false variables with the and operator. Sadly, one of them is False: shake since the customer didn’t want a milkshake.

That makes the entire tested condition False too. And so the if code doesn’t run, but the else code does. There the print() function says the customer doesn’t want all four extras:

The customer doesn't want diet coke, extra fries, a milkshake, *and* an extra burger.

# One True condition in an if statement: the or operator

Another option is the or operator. When we combine conditions with that operator, just one has to be True to make the entire combination True. Only when each condition is False does our if statement test False too. Let’s see some examples of that.

# If statement that needs just one of two conditions

So when we combine conditions with or, just one has to be True. Here’s how we can use that behaviour with an if statement:

# Current temperaturecurrentTemp = 40.7# Extremes in temperature (in Celsius)tempHigh = 40.7tempLow = -18.9# Compare current temperature against extremesif currentTemp > tempLow or currentTemp < tempHigh: print('Temperature (' + str(currentTemp) + ') is above record low or ' + 'below record high.')else: print("There's a new record-breaking temperature!")

We first make three variables. currentTemp has the current temperature reading; tempHigh and tempLow contain the weather station’s all-time extremes.

An if/else statement then compares the current temperature against those extremes. The if portion checks two conditions. First we see if the current temperature is above the all-time low (currentTemp > tempLow). Then we check if the temperature is below the highest reading (currentTemp < tempHigh).

Since we join those two conditions with the or operator, just one has to test True before Python runs the if code. Because the current temperature is above the minimum (but not below the maximum), our entire condition does test True thanks to or.

So the if code executes. There the print() function says the current temperature is either above the coldest or hottest record:

Temperature (40.7) is above record low or below record high.

# If statement that needs one True condition amongst several

With the or operator we can combine as many conditions as needed. When we do, we still need just one True condition to make the entire combination True as well. This usually means that the more conditions we combine with or, the greater the odds that the entire condition is True.

Here’s an example program that test multiple or conditions:

# Check which extras the customer orderednoSalt = TruedietCoke = Falsefries = Falseshake = False# Handle the customer's orderif noSalt or dietCoke or fries or shake: print("Optional extras for order:") print("No salt:\t\t", noSalt) print("Diet coke:\t\t", dietCoke) print("French fries:\t", fries) print("Milkshake:\t\t", shake)else: print("No extras needed for this order. Please proceed.")

This program handles customer orders at a fastfood restaurant. We first make four variables (noSalt, dietCoke, fries, and shake). Each gets a True or False based on what the customer ordered.

Then we process that order with an if/else statement. The if portion combines the four variables with the or operator into a single condition. So just one True variable is enough to make the if code run. And sure enough, one variable (noSalt) is indeed True.

Even though all other variables are False, that one True variable is enough to run the if code. There print() displays what the customer ordered by outputting the value of each variable:

Optional extras for order:No salt: TrueDiet coke: FalseFrench fries: FalseMilkshake: False

# Complex conditions in Python’s if statements: and + or

To handle complex scenarios, our if statement can combine the and and or operators together. That way we turn several conditions into code, of which some have to happen simultaneously (and) while others need just one to be True (or).

When we code complex conditions, it’s a good idea to use parentheses (( and )). Sometimes they’re required to change Python’s order of operations. And at other times they simply make code easier to understand.

Let’s see how combining conditions with and and or looks. Here’s a quick example:

condition = (A and B) or C

This combined condition tests True in one of two scenarios:

  • When the combination of A and B is True.
  • Or when C is True.

When both the first and second condition are False, then this combination is False too.

Here’s another example:

condition = (A or B) and C

This combination is True when two things happen at the same time:

  • Either A or B is True.
  • And C tests True.

When A and B combine to False, and C is False, then the combined condition is False too. Now let’s consider some Python example programs to learn more.

# Example: if statement with and + or conditions

Let’s say that our program handles orders at a fastfood restaurant. To assign the right staff member to the order, we have to know if the customer wants an additional beverage or food. We evaluate that with an if/else statement:

# Check the extras the customer ordereddietCoke = Falseshake = Truefries = Trueburger = True# Evaluate the customer's orderif (dietCoke or shake) and (fries or burger): print("The customer wants an extra drink " + "(diet coke and/or shake) and extra food " + "(french fries and/or burger).")else: print("The customer doesn't want both an " + "extra drink *and* extra food.")

We first make four variables: dietCoke, shake, fries, and burger. Each indicates if a customer wants that particular extra (True) or not (False).

Then we process the order with an if/else statement. There we evaluate two groups of conditions, joined with and. That means both groups have to be True before the if code runs.

The first group sees if the customer ordered a diet coke or milkshake (dietCoke or shake). Because we join those expressions with or, just one has to be True to make this group True. (Since shake is True, the outcome is indeed True.)

Now for the second group. Here we see if the customer ordered extra French fries or a burger (fries or burger). Again we use the or operator so one True value is enough to make this group True. (Because both are True, the outcome is True as well.)

Since the left and right group are both True, joining them with and gives a True value as well. And so the if code runs. There the print() function says which extras the customer wants:

The customer wants an extra drink (diet coke and/or shake) and extra food (french fries and/or burger).

Note that we aren’t very precise about what the customer wants. Since multiple situations can trigger the if code, we cannot say what made that code run. This is a consequence of the or operator.

In general, the more conditions you combine with or, the less precise you can be about what caused the code to run.

# Other ways to handle conditions of if statements

Besides testing several scenarios, there are other ways to code if conditions:

  • In compare values with if statements we explore how we code greater than and smaller than scenarios.
  • In logical negation with if statements we discuss how code can check if a specific situation did not happen.
  • And in if statement membership tests we have the in operator test whether some value is present in another value.

For more about Python’s if statements, see the if statements category.

# Summary

To evaluate complex scenarios we combine several conditions in the same if statement. Python has two logical operators for that.

The and operator returns True when the condition on its left and the one on its right are both True. If one or both are False, then their combination is False too. That programs strict scenarios: only when several conditions are True at the same time will our if statement run.

The or operator is different. This one returns True when its left and/or right condition are True. Only with both False does the or combination return False too. That makes our if statement more flexible: now one True value is enough to run its code.

For complex scenarios we combine the and and or operators. With parentheses we then clarify our code and specify how Python should process the different conditions.

References

Lutz, M. (2013). Learning Python (5th Edition). Sebastopol, CA: O’Reilly Media.

Python.org (n.d.). Expressions. Retrieved on August 5, 2019, from https://docs.python.org/3/reference/expressions.html

Sweigart, A. (2015). Automate The Boring Stuff With Python: Practical Programming for Total Beginners. San Francisco, CA: No Starch Press.

Published .

  • Compare values with Python’s if statements: equals, not equals, bigger and smaller than

    Python’s if statements can compare values for equal, not equal, bigger and smaller than. This article explains those conditions with plenty of examples.

  • Python’s nested if statements: if code inside another if statement

    A nested if statement is an if clause placed inside an if or else code block. They make checking complex Python conditions and scenarios possible.

  • Python’s cascaded if statement: test multiple conditions after each other

    Python’s cascaded if statement evaluates multiple conditions in a row. When one is True, that code runs. If all are False the else code executes.

  • If statements that test the opposite: Python’s if not explained

    Most Python if statements look for a specific situation. But we can also execute code when a specific condition did not happen. We do that with not.

  • Python’s if/else statement: choose between two options programmatically

    The if/else statement has Python make decisions. When the condition tests True, code intended under if runs. Otherwise the else code executes.

« All Python if/else articles

Top Articles
Latest Posts
Article information

Author: Errol Quitzon

Last Updated: 03/30/2023

Views: 5823

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Errol Quitzon

Birthday: 1993-04-02

Address: 70604 Haley Lane, Port Weldonside, TN 99233-0942

Phone: +9665282866296

Job: Product Retail Agent

Hobby: Computer programming, Horseback riding, Hooping, Dance, Ice skating, Backpacking, Rafting

Introduction: My name is Errol Quitzon, I am a fair, cute, fancy, clean, attractive, sparkling, kind person who loves writing and wants to share my knowledge and understanding with you.