Python while 2 conditions | Example code

Use logical operators to combine two conditional expressions into one while loop in Python. In the same way, you can use Multiple condition expressions in a while loop.

For example while 2 conditions in Python

Simple example code combines multiple conditional expressions in a while loop. We will do use or and and to make a while loop with multiple conditions.

Logical AND “&” Operator

while True and True: #Will run
while True and False: #Won't run
while False and True: #Won't run
while False and False: #Won't run

The and operator says to evaluate them separately and then consider their results as a whole. If (and only if) both A and B are true, then the loop body will execute.

a = 5
b = 10
count = 0

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

Output:

Python while 2 conditions

Logical OR “| |”Operator

while True or True: #Will run
while True or False: #Will run
while False or True: #Will run
while False or False: #Won't run

The or operator says to evaluate them separately and then consider their results as a whole. Now, however, the loop body will execute if at least one of the conditional expressions is true.

a = 5
b = 10
count = 0

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

Output:

Count 0
Count 1
Count 2
Count 3
Count 4
Count 5
Count 6
Count 7
Count 8
Count 9

Do comment if you have any doubts and suggestions on this Python while tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

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