Python While Loop with Multiple Conditions

From the syntax of Python While Loop, we know that the condition we provide to while statement is a boolean expression.

This boolean expression can contain one condition or multiple conditions. Python evaluates the complete expression before every iteration. The loop continues only while that expression evaluates to True.

To write a simple condition, we can use Python comparison operators such as ==, !=, >, <, >=, and <=.

To write a Python while loop with multiple conditions, combine individual conditions using logical operators such as and, or, and not. The operator you choose determines whether all conditions, any condition, or the opposite of a condition must be true for the loop to continue.

Syntax of a Python While Loop with Two or More Conditions

The following syntax shows the common forms of a while loop containing multiple conditions.

</>
Copy
while condition1 and condition2:
    # statements

while condition1 or condition2:
    # statements

while (condition1 and condition2) or condition3:
    # statements

With and, every joined condition must be true. With or, at least one joined condition must be true. Parentheses can be used when a condition combines several logical operators and you want the grouping to be explicit.

Example 1 – While Loop with Multiple Conditions joined by AND

In this example, we will write a while loop with condition containing two simple boolean conditions joined by and logical operator.

Python Program

</>
Copy
i = 20
j = 15

while i > 0 and j > 0 :
    print((i,j))
    i -= 3
    j -= 2

Output

(20, 15)
(17, 13)
(14, 11)
(11, 9)
(8, 7)
(5, 5)
(2, 3)

The condition is i > 0 and j > 0. Therefore, both comparisons must remain true. After each iteration, i decreases by 3 and j decreases by 2.

After the tuple (2, 3) is printed, the values become i = -1 and j = 1. At the next condition check, i > 0 is false. Because the conditions are connected with and, the entire expression becomes false and the loop stops.

Example 2 – While Loop with Multiple Conditions joined by OR

In this example, we will use Python OR logical operator to join simple conditions to form a compound condition to use for while loop condition.

Python Program

</>
Copy
i = 20
j = 15

while i > 0 or j > 0 :
    print((i,j))
    i -= 3
    j -= 2

Output

(20, 15)
(17, 13)
(14, 11)
(11, 9)
(8, 7)
(5, 5)
(2, 3)
(-1, 1)

Here the loop uses i > 0 or j > 0. Only one of the two comparisons has to be true for another iteration to run. This is why the loop continues even after i becomes negative: j is still positive.

After (-1, 1) is printed, the values become i = -4 and j = -1. Both comparisons are then false, so the or expression becomes false and the loop ends.

Choosing AND or OR in a Python While Loop

The difference between and and or is important when deciding when a loop should stop.

ConditionLoop continues whenLoop stops when
A and BBoth A and B are trueEither A or B becomes false
A or BAt least one of A or B is trueBoth A and B become false

Use and when every requirement must remain valid. For example, a loop may continue only while an attempt limit has not been reached and a valid result has not yet been obtained.

Use or when the loop should continue as long as any one of several conditions remains true.

Python While Loop with Three Conditions

A while loop is not limited to two conditions. You can combine three or more conditions in the same Boolean expression.

</>
Copy
count = 0
score = 80
active = True

while count < 3 and score >= 50 and active:
    print(count, score)
    count += 1
    score -= 10

Output

0 80
1 70
2 60

The loop runs only while all three conditions are true: count must be less than 3, score must be at least 50, and active must be true. When count becomes 3, the first condition fails and the loop terminates.

Combining AND and OR Conditions with Parentheses

A more complex Python while loop can contain both and and or. Python evaluates and before or, but parentheses make the intended grouping easier to see and reduce mistakes when the condition is changed later.

</>
Copy
attempts = 0
has_password = False
has_pin = True

while attempts < 3 and (not has_password or not has_pin):
    print("Authentication data is incomplete")
    attempts += 1

    if attempts == 2:
        has_password = True
        has_pin = True

Output

Authentication data is incomplete
Authentication data is incomplete

The outer and requires the attempt count to remain below 3 and the grouped authentication condition to remain true. Inside the parentheses, or means the loop continues when either the password or PIN is still missing.

Using NOT in a Python While Loop Condition

The not operator reverses a Boolean value. It is useful when the loop should continue until a flag becomes true.

</>
Copy
finished = False
step = 1

while not finished and step <= 3:
    print("Step", step)
    step += 1

    if step > 3:
        finished = True

Output

Step 1
Step 2
Step 3

not finished is true while finished is false. Once the flag changes to true, not finished becomes false and the loop cannot continue.

Loop Until User Input Meets Multiple Conditions

Multiple conditions are also useful when validating user input. For example, the following loop keeps asking for a number until the value is within the allowed range.

</>
Copy
number = int(input("Enter a number from 1 to 10: "))

while number < 1 or number > 10:
    print("Value must be between 1 and 10.")
    number = int(input("Enter a number from 1 to 10: "))

print("Accepted:", number)

The condition uses or because a value is invalid when it is either below 1 or above 10. The loop stops only when both invalid cases are false, which means the number is between 1 and 10 inclusive.

Exit a While Loop When an Additional Condition Is Met

Sometimes the main while condition describes the normal repetition rule, while another condition inside the loop should stop execution immediately. In that case, use break.

</>
Copy
count = 0
limit = 10

while count < limit:
    count += 1

    if count == 5:
        break

    print(count)

Output

1
2
3
4

The while condition would normally allow values up to 9, but the break statement exits the loop when count == 5. Use this pattern when the extra stopping condition is easier to detect after some work has been performed inside the loop.

Avoiding Infinite While Loops with Multiple Conditions

A while loop becomes infinite when its complete condition never changes to false. With multiple conditions, this can happen when one of the variables participating in an or expression is never updated.

</>
Copy
x = 3
y = 3

while x > 0 or y > 0:
    print(x, y)
    x -= 1
    y -= 1

In this example, both variables are updated, so eventually both comparisons become false. If y were never reduced, y > 0 would remain true and the or expression could keep the loop running indefinitely.

When reviewing a while loop with several conditions, check each variable or flag used in the expression and identify what can cause that part of the expression to change.

Short-Circuit Evaluation in Multiple While Conditions

Python uses short-circuit evaluation for logical expressions. With and, Python stops evaluating as soon as it finds a false operand because the entire expression must then be false. With or, Python stops as soon as it finds a true operand because the entire expression must then be true.

</>
Copy
items = [10, 20, 30]
index = 0

while index < len(items) and items[index] > 0:
    print(items[index])
    index += 1

Checking index < len(items) first is significant. When the index reaches the length of the list, that comparison becomes false and Python does not evaluate items[index]. This prevents an attempt to access an element beyond the end of the list.

Common Mistakes in Python While Loops with Multiple Conditions

  • Using or when every requirement must be true: or keeps the loop running while any joined condition is true, which may make the loop run longer than intended.
  • Using and when any condition should keep the loop running: an and expression stops as soon as one condition becomes false.
  • Forgetting to update a condition variable: if a value used in the while expression never changes, the loop may never terminate.
  • Writing a complex expression without clear grouping: use parentheses to show how conditions using and, or, and not belong together.
  • Repeating the wrong boundary comparison: decide whether endpoint values should be accepted and use <, <=, >, or >= accordingly.

Python While Loop with Multiple Conditions: Key Takeaways

Concluding this Python Tutorial, a while loop can use any Boolean expression, including one made from several conditions. Join conditions with and when all of them must remain true, use or when any one of them may keep the loop running, and use not when a condition needs to be reversed.

For compound expressions, use parentheses where they make the intended logic clearer. Also make sure that values participating in the while condition can change during execution so that the loop has a defined path to termination.