Skip to content

Python while 2 conditions | Example code

  • by

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 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 the 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 the 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 or suggestions on this Python while tutorial.

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.

Leave a Reply

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