Python While Loop with Multiple Conditions

Learn how to use multiple conditions in a Python while loop using and, or, not, parentheses, and two-condition examples. Understand when the loop stops and how to avoid infinite loops.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Python While Loop with Multiple Conditions

You can put more than one test in a Python while header by combining boolean expressions with and, or, and not. Python re-evaluates the full condition before every iteration; when it becomes false, the loop stops. This page is only about multiple conditions in one while statement—for syntax, break, continue, and else, see the main Python while loop tutorial.

Quick reminder: a single-condition loop looks like while condition: with an indented body. Multiple conditions use the same shape—the header just contains a compound expression, for example while x > 0 and not done:.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


How to use multiple conditions in a while loop

Write one while line and combine tests with boolean operators:

Operator Loop continues when…
and Every part is true
or At least one part is true
not The following expression is false

Use parentheses when mixing operators so the order of evaluation matches what you mean:

python
while (count < limit) and (status != "done"):
    ...
Output

Update the variables each part depends on inside the body. If nothing ever makes the combined condition false, you get an infinite loop—the same rule as a one-condition while.

Nested while loops (one loop inside another) are different from multiple conditions: nested means two separate while statements; multiple conditions means one while with several tests in the header.


Method 1: while loop with and condition

Use and when every check must stay true—typical patterns include staying in range and waiting until a flag changes.

When count must stay below two limits at once:

python
a = 3
b = 2
count = 0
while count < a and count < b:
    print("GoLinuxCloud is the best website ever!")
    count += 1
Output

The loop runs while count is below both limits. Here b is 2, so after two iterations count < b is false and the loop stops—even though count is still less than a. You should see two lines of output.

Another common shape is two flags—keep working while the job is active and there is still work left:

python
active = True
has_work = True
processed = 0
while active and has_work:
    print("processing", processed)
    processed += 1
    if processed >= 2:
        has_work = False
Output

You should see processing 0 and processing 1, then the loop stops when has_work becomes false.


Method 2: while loop with or condition

Use or when any one reason is enough to keep looping—for example, while a counter is below either of two limits, or while a value is still out of range.

While either bound allows another iteration:

python
a = 3
b = 5
count = 0
while count < a or count < b:
    print("GoLinuxCloud is the best website ever!", ", Count : ", count)
    count += 1
Output

The loop continues while count < a or count < b is true. It stops only when both are false—here when count reaches 5. You should see five lines with Count : 0 through Count : 4.

To skip bad values until one is acceptable, stay in the loop while the value is too low or too high:

python
values = [-1, 150, 42]
i = 0
while i < len(values) and (values[i] < 0 or values[i] > 100):
    print("reject", values[i])
    i += 1
print("accept", values[i])
Output

The inner or keeps the loop running for -1 and 150; it stops when values[i] is 42. You should see two reject lines, then accept 42.


Method 3: while loop with not condition

Use not to keep looping while something has not happened yet—often paired with and for a safety cap.

Cap attempts with not attempts >= 3 (same idea as attempts < 3):

python
running = True
attempts = 0
while running and not attempts >= 3:
    print(f"attempt {attempts}")
    attempts += 1
Output

You should see attempt 0 through attempt 2, then the loop exits.

Retry until the task succeeds or you run out of attempts:

python
attempts = 0
max_attempts = 3
ok = False
results = ["fail", "fail", "ok"]
while not ok and attempts < max_attempts:
    ok = results[attempts] == "ok"
    print(f"try {attempts + 1}: {'ok' if ok else 'fail'}")
    attempts += 1
Output

You should see two fail lines, then try 3: ok.

Membership with not works well for status or input checks:

python
status = "pending"
allowed = {"done", "failed", "skipped"}
attempts = 0
while status not in allowed and attempts < 3:
    attempts += 1
    status = "done"

print(status)
Output

The loop runs until status lands in allowed or attempts hit the limit. With the values above, print shows done.

Read input until the choice is allowed—replace the list with input() in a real program:

python
choice = ""
allowed = ("y", "n", "q")
inputs = ["maybe", "y"]
i = 0
while choice not in allowed and i < len(inputs):
    choice = inputs[i]
    print("input:", choice)
    i += 1
print("accepted:", choice)
Output

You should see input: maybe, then input: y, then accepted: y.


Method 4: while loop with grouped conditions

Parentheses make mixed logic easier to read. They document intent when you combine and, or, and not in one header.

Exclude one value while counting down:

python
value = 10
while (value > 0) and (value != 5):
    print(value)
    value -= 1
Output

You should see 10 down through 6; at 5 the second part is false, so the loop stops before printing 5.

Inclusive range with two comparisons (parentheses optional but clear):

python
n = 1
while (n >= 1) and (n <= 5):
    print(n)
    n += 1
Output

That prints 1 through 5.

When you mix and and or, group sub-expressions explicitly. Work continues while there is queue data and shutdown has not been requested, unless force mode is on:

python
queue = [1, 2]
shutdown = False
force = True
while (queue and not shutdown) or force:
    if queue:
        print("pop", queue.pop(0))
    else:
        force = False
Output

Without parentheses, and binds tighter than or, which changes the meaning. The grouped form reads as (queue and not shutdown) or force.

Validate numeric input while you still have candidates—note the grouped or inside the and:

python
candidates = [0, 12, 7]
idx = 0
num = candidates[idx]
while idx < len(candidates) and (num < 1 or num > 10):
    print("out of range:", num)
    idx += 1
    if idx < len(candidates):
        num = candidates[idx]
print("valid:", num)
Output

You should see out of range: 0, then out of range: 12, then valid: 7.


Summary

Combine multiple tests in one Python while header with and (all must be true), or (any can keep it running), and not (invert a test). Group sub-expressions with parentheses when you mix operators or when several flags and bounds apply together. The loop runs until the whole condition is false—then move on to the next statement after the loop body.


Further reading

Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …