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
is_valid = False
while not is_valid:
password = input("Enter your password: ")
if password == "password123":
is_valid = True
else:
print("Invalid password. Try again.")
print("Login successful!")
Multiple Conditions
The loop will continue executing as long as either of the conditions (count < a or count < b)
is true and the count is less than max_iterations
.
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:
Do comment if you have any doubts or suggestions on this Python while loop topic.
Note: IDE: PyCharm 2021.3.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.