In Python, if statements are very useful to control the flow of your program. We can easily define an if statement with multiple conditions using logical operators.

num = 5

if num < 10 and num % 4 != 0:
    print(num)

#Output:
5

In Python, if statements allow us to control the flow of data and perform various operations based on conditions.

When dealing with complex situations in our Python programs, we may need to create an if statement with multiple conditions.

Fortunately, we can use logical operators to create complex logical statements to handle if statements with multiple conditions. We can use the logical operators and, or, and not to create if statements with multiple conditions easily.

Let's say we want to create an if statement with two conditions. The first condition is that we want a numeric variable to be less than 10. The second condition is we want the division of our value by 4 to have a remainder not equal to 4.

Logically, those two conditions are as follows:

num < 10 and num % 4 != 0

We can use these conditions in an if statement easily.

Below is an example of a multiple condition if statement using the logical and operator in Python.

num = 5

if num < 10 and num % 4 != 0:
    print(num)

#Output:
5

Another example of this is if you want to check if a number is between two numbers.

Below is a simple function which will check if a number is between two numbers using a multiple condition if statement in Python.

def between_two_numbers(num,a,b):
    if a < num and num < b: 
        return True
    else: 
        return False

print(between_two_numbers(10,5,15))

#Output:
True

Using the Logical Operator or with Multiple Conditions in a Python if Statement

We can also use the or operator to create an if statement with multiple conditions.

The or operator is true when at least one of the logical statements it joins are true, and is false if all of the statements are false.

Below is an example of a multiple condition if statement using the logical or operator in Python.

num = 15

if num < 10 or num % 4 != 0:
    print(num)

#Output:
15

Using the Logical Operator not with Multiple Conditions in a Python if Statement

We can also use the not operator to create an if statement with multiple conditions.

The not operator negates the boolean value returned by a logical statement.

Below is an example of a multiple condition if statement using the logical not operator in Python.

num = 15

if not(count < 10 and count % 4 != 0):
    print(num)

#Output:
15

This example is equivalent to the following if statement.

num = 15

if not(num < 10) or not(num % 4 != 0):
    print(num)

#Output:
15

Hopefully this article has been helpful for you to learn how to use if statements with multiple conditions in Python.

Categorized in:

Python,

Last Update: March 15, 2024