While loop with multiple conditions in Python

In this Python tutorial, I will tell you what is while loop with multiple conditions in Python. In the process, we will see what are the different logical operators that we will be used to make multiple conditions in Python. We will also see some illustrative examples for Python while loop with multiple conditions.

A while loop in Python is used to repeatedly execute a block of statements as long as a certain condition is True. The general syntax for a while loop in Python is:

while condition:
    # code to execute

The loop will keep executing as long as the condition evaluates to True. If the condition is never True, the loop’s body won’t execute at all. It’s important to ensure that the condition will eventually become False, otherwise, we’ll have an infinite loop.

Example:

count = 0
while count < 5:
    print(count)
    count += 1

The output is:

0
1
2
3
4
While loop condition in Python

In Python, multiple conditions can be combined and evaluated using logical operators such as:

  • and: True if both conditions are true.
  • or: True if at least one condition is true.
  • not: Reverses the truthiness of the condition it precedes.

These logical operators in Python allow for the creation of more complex conditions by joining simpler ones.

Incorporating Multiple Conditions in While loop Python

Let’s take a look at these operators and how they’re used to create multiple conditions in Python while loop :

Example-1: Using the ‘and’ Operator within the While loop in Python

With the ‘and‘ operator, all conditions must be True for the loop to continue in Python.

For instance, Imagine we’re on a summer vacation and we want to visit national parks. We have two criteria: it shouldn’t be raining, and the temperature should be above 60°F.

For the sake of this simulation, it is assumed that the temperature drops by 3°F each day in this Python code.

rain = False
temperature = 65

days_visited = 0

while not rain and temperature > 60:
    days_visited += 1
    print(f"Visited the park for {days_visited} days!")

    temperature -= 3

print(f"You visited the park for a total of {days_visited} days.")

The output is: After the first day, the temperature drops to 62°F. On the second day, it drops further to 59°F. At this point, the condition temperature > 60 is no longer true, causing the loop to terminate.

Visited the park for 1 days!
Visited the park for 2 days!
You visited the park for a total of 2 days.
python while with two conditions with and operator

This way we can use the ‘and‘ logical operator with Python while two conditions.

Example-2: Using the ‘or’ Operator in a while loop with multiple conditions in Python

With the ‘or‘ operator, if any of the conditions are True, the loop continues in Python.

For example, We’re traveling across the USA, and we want to visit either the Statue of Liberty in New York or the Golden Gate Bridge in San Francisco.

statue_of_liberty = True
golden_gate_bridge = False
landmarks_visited = 0

while statue_of_liberty or golden_gate_bridge:
    landmarks_visited += 1
    break

print(f"You visited {landmarks_visited} landmarks.")

The Output is: Given the initial conditions (statue_of_liberty is True and golden_gate_bridge is False), the loop in Python will execute because the Statue of Liberty is on the visiting list.

You visited 1 landmarks.
while loop with multiple conditions in Python with or logical operator

This way we can use the ‘or‘ logical operator within a while with two conditions Python.

Example-3: Using the not Operator within Python while loop

The ‘not‘ operator inverts the result of the condition in Python. If a condition is True, not will make it False, and vice versa.

For instance, Imagine we’re collecting US state quarters, and we want to keep searching in our collection until we find the elusive Delaware quarter.

Here, The while loop in Python continues to execute as long as found_delaware remains False. The if statement in Python checks if the current quarter (indicated by the index value) is “Delaware”. If it is, it sets the found_delaware variable to True, which will eventually break out of the loop.

quarters = ["Georgia", "Maryland", "Washington", "Delaware", "New Jersey"]
found_delaware = False
index = 0

while not found_delaware:
    if quarters[index] == "Delaware":
        found_delaware = True
    index += 1

print(f"Found the Delaware quarter, It is at {index}!")

The output is: Once the “Delaware” quarter is found and the loop exits in Python, the program prints out the message.

Found the Delaware quarter, It is at 4!
while with multiple conditions python using not operator

This way we can use the ‘not‘ logical operator within while loop multiple conditions in Python.

Example-4: Python while loop with multiple conditions

Suppose we’re music enthusiasts and we’re collecting albums from two of our favorite genres: Rock and Jazz. We’ll stop collecting once we either reach a certain budget or if we have at least 3 albums from both genres, using a While loop with multiple conditional statements in Python.

rock_albums = 0
jazz_albums = 0
budget = 100

while (rock_albums < 3 or jazz_albums < 3) and budget > 20:

    if rock_albums < 3 and budget >= 30:
        rock_albums += 1
        budget -= 30
    elif jazz_albums < 3 and budget >= 25:
        jazz_albums += 1
        budget -= 25
    print(f"Rock Albums: {rock_albums}, Jazz Albums: {jazz_albums}, Remaining Budget: ${budget}")

print("Finished collecting albums!")

The Output is: The process stops either when we’ve collected enough albums or when we run out of budget in Python.

while loop multiple conditions python with logical operator

This way we can have multiple conditions in while loop Python.

Note: Avoid Infinite Loops, Ensure at least one of the conditions will eventually become false to prevent the loop from running indefinitely in Python.

Conclusion

Multiple conditions in a while loop in Python allow for nuanced control over its execution. So, in this article, we have seen what a Python while loop is and how does While loop works with multiple conditions in Python like and, or, and not with illustrative examples and providing instructions for Python while loop with multiple conditions.

You may like the following Python tutorials: