Python while loop multiple conditions | Example code

  • by

Use logical operator for Python while looping multiple conditions. With it, you can combine two conditional expressions into one while loop.

Logical AND Operator

while ( CONDITIONAL EXPRESSION A ) and ( CONDITIONAL EXPRESSION B ):
	EXECUTE STATEMENTS

Logical OR Operator

while ( CONDITIONAL EXPRESSION A ) or ( CONDITIONAL EXPRESSION B ):
	EXECUTE STATEMENTS

Logical NOT Operator

while ( not CONDITIONAL EXPRESSION ):
	EXECUTE STATEMENTS

Example while loop multiple conditions in Python

Simple example code.

Using AND &

If (and only if) both A and B are true, then the loop body will execute.

a = 1
b = 2
count = 0

while count < a and count < b:
    print(a, b)
    count += 1

Output: 1 2

Using OR |

The loop body will execute if at least one of the conditional expressions is true.

a = 1
b = 2
count = 0

while count < a or count < b:
    print(a, b)
    count += 1

Output:

1 2
1 2

Using NOT Operator

This operator simply reverses the value of a given boolean expression

Multiple Conditions

a = 1
b =2

max_iterations = 3
count = 0

while (count < a or count < b) and not count >= max_iterations:
    print(f"count: {count}, a: {a}, b: {b}")
    count += 1

Output:

Python while loop multiple conditions

Do comment if you have any doubts or suggestions on this Python while loop topic.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.