How to use a Python while loop with multiple conditions

Published on Aug. 22, 2023, 12:16 p.m.

To use a Python while loop with multiple conditions, you can use logical operators like and, or, and not to connect two or more conditional expressions. Here’s an example:

i = 0
j = 5
while i < 10 and j > 0:
    print(i, j)
    i += 1
    j -= 1

In this example, the while loop has two conditions connected by the and operator: i < 10 and j > 0. The loop will continue to execute as long as both of these conditions are True. Inside the loop, the values of i and j are printed, and then i is incremented by 1 and j is decremented by 1.

The output of this program will be:

0 5
1 4
2 3
3 2
4 1

Note that logical operators can also be used with if statements, as well as other types of loops like for loops. This allows you to create more complex conditions that depend on multiple variables or other conditions.

Tags: