In Python, while loops are very useful to loop over a collection of data. We can easily define a while loop with multiple conditions using logical operators.

count = 1

while count < 10 and count % 4 != 0:
    print(count)
    count = count + 1

#Output:
1
2
3

In Python, loops allow us to iterate over collections of data and perform various operations many times. Both while loops and for loops are useful, but in certain cases, while loops can be better.

When dealing with complex situations in our Python programs, we may need to create a while loop with multiple conditions.

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

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

Logically, those two conditions are as follows:

count < 10 and count % 4 != 0

We can use these conditions in a while loop easily.

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

count = 1

while count < 10 and count % 4 != 0:
    print(count)
    count = count + 1

#Output:
1
2
3

Using the Logical Operator or with Multiple Conditions in a Python While Loop

We can also use the or operator to create a while loop 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 while loop using the logical or operator in Python.

count = 1

while count < 10 or count % 4 != 0:
    print(count)
    count = count + 1

#Output:
1
2
3
4
5
6
7
8
9
10
11

Using the Logical Operator not with Multiple Conditions in a Python While Loop

We can also use the not operator to create a while loop with multiple conditions.

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

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

count = 15

while not(count < 10 and count % 4 != 0):
    print(count)
    count = count - 1

#Output:
15
14
13
12
11
10

This example is equivalent to the following while loop.

count = 15

while not(count < 10) or not(count % 4 != 0):
    print(count)
    count = count - 1

#Output:
15
14
13
12
11
10

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

Categorized in:

Python,

Last Update: March 15, 2024