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

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 ordereddietco*ke = Truefries = Trueshake = FalseextraBurger = Trueif dietco*ke and fries and shake and extraBurger: print("The customer wants:") print("- Diet instead of regular co*ke") print("- Extra french fries") print("- A milkshake") print("- An extra burger")else: print("The customer doesn't want diet co*ke, " + "extra fries, a milkshake, *and* an extra burger.")

First we make four true/false variables (dietco*ke, 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 co*ke, 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 = Truedietco*ke = Falsefries = Falseshake = False# Handle the customer's orderif noSalt or dietco*ke or fries or shake: print("Optional extras for order:") print("No salt:\t\t", noSalt) print("Diet co*ke:\t\t", dietco*ke) 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, dietco*ke, 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 co*ke: 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 ordereddietco*ke = Falseshake = Truefries = Trueburger = True# Evaluate the customer's orderif (dietco*ke or shake) and (fries or burger): print("The customer wants an extra drink " + "(diet co*ke 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: dietco*ke, 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 co*ke or milkshake (dietco*ke 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 co*ke 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

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

FAQs

How do you pass multiple conditions in an if statement in Python? ›

Using Multiple Conditions in Python if-else Statements

# Using Multiple Conditons in Python if-else val1 = 2 val2 = 10 if val1 % 2 == 0 and val2 % 5 == 0: print("Divisible by 2 and 5.") else: print("Not divisible by both 2 and 5.") # Returns: Divisible by 2 and 5.

Can you have 3 conditions in an if statement Python? ›

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

Can I use 2 IF statements in Python? ›

It works that way in real life, and it works that way in Python. if statements can be nested within other if statements. This can actually be done indefinitely, and it doesn't matter where they are nested. You could put a second if within the initial if .

How do you write an if statement with multiple conditions? ›

When you combine each one of them with an IF statement, they read like this:
  1. AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False)
  2. OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False)
  3. NOT – =IF(NOT(Something is True), Value if True, Value if False)

Can you pass multiple arguments in Python? ›

A Function is the Python version of the routine in a program. Some functions are designed to return values, while others are designed for other purposes. We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.

How do you pass multiple exceptions in Python? ›

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

How do you satisfy three conditions in an if statement? ›

You can use the following formulas to create an IF function with 3 conditions in Excel:
  1. Method 1: Nested IF Function =IF(C2<15, "Bad", IF(C2<20, "OK", IF(C2<25, "Good", "Great")))
  2. Method 2: IF Function with AND Logic =IF(AND(A2="Mavs", B2="Guard", C2>25), "Yes", "No")
Jul 24, 2022

Can IF statement have more than 2 conditions? ›

The multiple IF conditions in Excel are IF statements contained within another IF statement. They are used to test multiple conditions simultaneously and return distinct values. The additional IF statements can be included in the “value if true” and “value if false” arguments of a standard IF formula.

Can IF function have 3 conditions? ›

The IF Function has 3 arguments: Logical test. This is where we can compare data or see if a condition is met. Value if true.

Can I use and && in same if statement? ›

You can use the logical operators && (AND), || (OR) , and ! (NOT) within control expressions in an if statement. You must be careful to use extra parentheses in some situations since && (AND) executes before || (OR) according to the order of operations.

Can IF function have two results? ›

The IF function allows you to make a logical comparison between a value and what you expect by testing for a condition and returning a result if True or False. So an IF statement can have two results. The first result is if your comparison is True, the second if your comparison is False.

What is the difference between nested if and multi way if statements? ›

In a multi-way 'if' statement, you only get to eat out of one of them. In a nested 'if' statement, the bowls are nested together. You might eat the chips out of the outer one, and maybe dip them into the salsa in the middle. This helped very much.

What does Elif mean in Python? ›

The elif keyword is used in conditional statements (if statements), and is short for else if.

What is Elif in Python? ›

In Python, elif is short for "else if" and is used when the first if statement isn't true, but you want to check for another condition. Meaning, if statements pair up with elif and else statements to perform a series of checks. A full if/elif/else block is in the code example below.

What are the 3 arguments of the IF function? ›

IF is one of the Logical functions in Microsoft Excel, and there are 3 parts (arguments) to the IF function syntax: logical_test: TEST something, such as the value in a cell. value_if_true: Specify what should happen if the test result is TRUE. value_if_false: Specify what should happen if the test result is FALSE.

How can you accept multiple arguments into a function? ›

*args : Receive multiple arguments as a tuple

If you define a parameter preceded by * like *args , the function can receive any number of arguments. In the function, multiple arguments are received as a tuple. In the example, a tuple is passed to the sum() function to calculate the sum.

Is it possible to pass multiple arguments to a function? ›

Functions can accept more than one argument. When calling a function, you're able to pass multiple arguments to the function; each argument gets stored in a separate parameter and used as a discrete variable within the function.

How many arguments can I pass to a function in Python? ›

In Python, we can define two types of parameters that have variable lengths. They can be considered special types of optional parameters. In other words, there is no limit to the number of arguments that are passed to the parameter when we call this function.

What are the 3 types of exceptions? ›

There are three types of exception—the checked exception, the error and the runtime exception.

How do you pass multiple values in a variable in Python? ›

You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.

How are multiline statements given in Python? ›

Multi-line Statement in Python:

In Python, the statements are usually written in a single line and the last character of these lines is newline. To extend the statement to one or more lines we can use braces {}, parentheses (), square [], semi-colon “;”, and continuation character slash “\”.

Which statement is used to check multiple conditions in Python? ›

Python's if-elif-else Statements

Notice the use of the comparison operator > in the if statement and of <= in the elif statement.

What are the 4 conditional statements? ›

What Are Conditionals?
  • General truth – If I eat breakfast, I feel good all day.
  • Future event – If I have a test tomorrow, I will study tonight.
  • Hypothetical situation – If I had a million dollars, I would buy a boat!
  • Hypothetical outcome – If I had prepared for the interview, I would have gotten the job.
May 18, 2021

What is a nested if statement? ›

One IF function has one test and two possible outcomes, TRUE or FALSE. Nested IF functions, meaning one IF function inside of another, allows you to test multiple criteria and increases the number of possible outcomes.

Is there a limit to nested if statements? ›

Microsoft Excel has limits to the levels of nested IFs. In Excel 2003 and lower, up to 7 levels were allowed. In Excel 2007 and higher, you can nest up to 64 IF functions in one formula.

How many conditions can be specified in a IF? ›

There isn't a limitation to the amounth of conditional statements in an if.

How do you handle 3 conditions in a ternary operator? ›

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

How many && and/or || operators can be used in an if statement? ›

There is no limit to the number of && you use in a statement.

Can we use A and or in Python if statement? ›

In Python, we can use logical operators (i.e., and, or) to use multiple conditions in the same if statement.

What is the difference between & and && in if statement? ›

The basic difference between the & and && operator is that the & operator evaluate both sides of the expression whereas, the && operator evaluates only the left-hand side of the expression to obtain the final result. Let us understand the other differences between & and && with the help of comparison chart.

Can we enter multiple if conditions in an IF formula? ›

It is possible to nest multiple IF functions within one Excel formula. You can nest up to 7 IF functions to create a complex IF THEN ELSE statement. TIP: If you have Excel 2016, try the new IFS function instead of nesting multiple IF functions.

Can you nest an IF functions in an OR or? ›

You can automate the evaluation of logical tests by NESTING the AND, OR, NOT functions inside a single IF function.

Which is more efficient than nested IF? ›

Prerequisite – Switch Statement, Decision making(if else) A switch statement is usually more efficient than a set of nested ifs.

What is the difference between multiple if and Elif? ›

Multiple if's means your code would go and check all the if conditions, where as in case of elif, if one if condition satisfies it would not check other conditions..

What is A += in Python? ›

The plus-equals operator += provides a convenient way to add a value to an existing variable and assign the new value back to the same variable. In the case where the variable and the value are strings, this operator performs string concatenation instead of addition.

What is nested if statement in Python? ›

If Inside If

You can have if statements inside if statements, this is called nested if statements.

What is an example of nested if statement in Python? ›

Example. #!/usr/bin/python var = 100 if var < 200: print "Expression value is less than 200" if var == 150: print "Which is 150" elif var == 100: print "Which is 100" elif var == 50: print "Which is 50" elif var < 50: print "Expression value is less than 50" else: print "Could not find true expression" print "Good bye! ...

What is the difference between Elif and if in Python? ›

Difference between if and if elif else

Python will evaluate all three if statements to determine if they are true. Once a condition in the if elif else statement is true, Python stop evaluating the other conditions. Because of this, if elif else is faster than three if statements.

What is the alternative of if-else in Python? ›

Switch Case is a cleaner and faster alternative to if-else conditions in your code. Python does not directly support Switch Case but it does provide some very useful and efficient workarounds.

How many times can I use Elif? ›

We can include as many elif statements as we want to without any strict limit, overlooking the possible limitations such as hardware. We can say that the elif statement is a resolved version of the Nested if-else. In case of more than one statement, we can put many elif conditions between the else and if.

How many arguments does the IIF function have? ›

The IIF function contains three parts, or arguments: A logical test, which is a value or formula, that can be evaluated as true or false. The value that is returned if the logical test is true.

What are the three types of IF statements? ›

There are three forms of IF statements: IF-THEN , IF-THEN-ELSE , and IF-THEN-ELSIF . The simplest form of IF statement associates a Boolean expression with a sequence of statements enclosed by the keywords THEN and END IF . The sequence of statements is executed only if the expression returns TRUE .

What are if/then arguments called? ›

If–then arguments , also known as conditional arguments or hypothetical syllogisms, are the workhorses of deductive logic. They make up a loosely defined family of deductive arguments that have an if–then statement —that is, a conditional—as a premise.

How many if conditions can be used in Python? ›

Python provides four conditional statements. In this tutorial, we will learn about conditional statements with brief descriptions, syntax, and simple examples for each of these conditional statements.

How many conditional statements do we have in the Python *? ›

Python has 3 key Conditional Statements that you should know: if statement. if-else statement. if-elif-else ladder.

What are conditional branching statements in Python? ›

A conditional branch instruction is a branch instruction that may or may not generate a transmission of control that relies upon the value of stored bits in the PSR (processor status register). It provides decision-making capabilities in the control unit.

What does Elif do in Python? ›

In Python, elif is short for "else if" and is used when the first if statement isn't true, but you want to check for another condition. Meaning, if statements pair up with elif and else statements to perform a series of checks. A full if/elif/else block is in the code example below.

Top Articles
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 6153

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.