Image of Writing a Python While Loop with Multiple Conditions

Introduction

Iteration is the procedure by which a plan repeats a series of steps a certain number of times or while a certain condition is met. These two forms of iteration are known as definite (often implemented using a for loop) and indefinite (often implemented using a while loop).

In this article, you'll take a more than advanced await at indefinite iteration in Python. More than specifically, you'll learn how to write a Python while loop with multiple conditions. Let's get started!

Review of Python While Loops

In Python, indefinite iteration generally takes the following form:

          while ( Conditional EXPRESSION ): 	EXECUTE STATEMENTS                  

You initiate the loop with the while keyword, and then set the condition to be whatever conditional expression. A conditional expression is a statement that evaluates to Truthful or False. As long as the condition is true, the loop body (the indented block that follows) volition execute any statements information technology contains. Every bit soon as the status evaluates to faux, the loop terminates and no more statements volition exist executed.

The simplest while loops in Python are while True and while Simulated:

          >>> while Truthful: ...     print("I'll print forever") ... I'll impress forever I'll print forever I'll print forever I'll print forever I'll print forever ...                  

In this instance, the condition is always True, so the loop will run forever. In order to terminate it, you'll need to close the interpreter or send Python a KeyboardInterrupt by pressing CTRL+C.

A "while Truthful" loop is ever truthful and runs forever. A "while False" loop, on the other hand, is never true:

          >>> while Imitation: ...     impress("I'll never run") ... >>>                  

Since the condition is never true to begin with, the loop body never executes, and no statement is printed.

Python While Loop with One Condition

Ane of the most common uses of while loops in Python is to execute a serial of steps a specific number of times. Often, you lot'll utilize a "counter" variable to control how many times the loop executes. For example:

          >>> count = 5 >>> while count > 0: ...     impress("Current value of count: ", count) ...     count -= 1 ... Current value of count:  5 Electric current value of count:  four Electric current value of count:  3 Current value of count:  2 Current value of count:  ane >>>                  

Here, you define a counter and set it to the number 5. As long as the counter is greater than zero, you want the loop body to execute, so your conditional expression is count > 0. The output shows that the loop body successfully executes for the five iterations where the value of count is greater than cypher. Each iteration prints the electric current value of count, then decrements count past ane. On the terminal iteration, count is now equal to zero, and the conditional expression is now false. The while loop terminates, and the loop body stops execution.

In this example, you lot know the value of the counter ahead of time. However, while loops are a form of indefinite iteration, and that usually ways you lot won't know how many times the loop trunk should execute beforehand. You may want to change this value depending on the goals of your code, how many records are in your database, or how soon yous want your machine learning algorithm to converge. The possibilities are endless, but the underlying while loop structure is much the same.

Allow'southward define a variable max_iterations to simulate an unknown number of iterations:

          >>> import random >>> max_iterations = random.randint(0,10)                  

The Python random module has a method .randint() that allows you to choose whatsoever random integer between two numbers. Here, you lot set the max number of iterations to a random number between 0 and 10.

You don't know what the number is, but you lot can employ a while loop to discover out. To do this, set your counter to 0. The conditional expression will exist "while the value of the counter is less than the maximum number of iterations." Hither's what that looks similar in code:

          >>> count = 0 >>> while count < max_iterations: ...     print(f"count is {count}. max_iterations is {max_iterations}") ...     impress(f"Incrementing count by 1.") ...     count += i ... count is 0. max_iterations is four Incrementing count by 1. count is i. max_iterations is 4 Incrementing count by ane. count is 2. max_iterations is 4 Incrementing count by one. count is 3. max_iterations is 4 Incrementing count by 1.                  

On each iteration, Python will cheque to run into if the current value of count is less than the maximum number of iterations. If this is true, then the loop body executes. You tin see here that each iteration displays the value of both variables and increments the counter by 1. On the last iteration, where count is equal to max_iterations, the conditional expression becomes false and the loop terminates.

You lot can verify the value of max_iterations similar so:

          >>> max_iterations 4                  

So far, yous've seen how Python while loops work with ane conditional expression. Python compares the ii values and if the expression evaluates to true, it executes the loop trunk. Notwithstanding, it's possible to combine multiple conditional expressions in a while loop as well.

Python While Loop Multiple Weather

To combine two conditional expressions into one while loop, you'll need to use logical operators. This tells Python how you want all of your conditional expressions to be evaluated as a whole.

Logical AND Operator

The first logical operator is and. Hither'due south how you would employ it to combine multiple conditional expressions:

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

Here, the while loop has ii provisional expressions, A and B, that it needs to evaluate. The and operator says to evaluate them separately and so consider their results as a whole. If (and only if) both A and B are truthful, then the loop body will execute. If even ane of them is fake, and then the entire while argument evaluates to false and the loop terminates.

Allow'south take a look at a code instance.

          >>> a = 5 >>> b = 10 >>> count = 0 >>> while count < a and count < b: ...     print(f"count: {count}, a: {a}, b: {b}") ...     count += 1 ... count: 0, a: 5, b: 10 count: 1, a: 5, b: ten count: ii, a: 5, b: ten count: 3, a: 5, b: x count: 4, a: five, b: 10                  

You define ii new variables, a and b, which are equal to 5 and 10, respectively. Once more, yous've defined a counter and prepare information technology to zilch. The while statement now contains two conditional expressions. The first checks to encounter if count is less than a, and the second checks to come across if count is less than b. The logical operator and combines these 2 conditional expressions and so that the loop torso will merely execute if both are true.

The loop runs for five iterations, incrementing count by 1 each time. In the terminal iteration, where the loop terminates, the value of count is now five, which is the same value every bit a. This means the first provisional expression is now simulated (5 is not less than 5), so the while loop terminates.

Notation that the second condition count < b is notwithstanding true, even when count is 5. What if you wanted the loop to keep running as long every bit count is less than one of the variables?

Logical OR Operator

Logical or is the second operator you can use to combine multiple conditional expressions:

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

At that place are nevertheless two conditional expressions, A and B, that demand to be evaluated. Like logical AND, the or operator says to evaluate them separately and then consider their results equally a whole. Now, however, the loop body volition execute if at to the lowest degree one of the conditional expressions is truthful. The loop will only finish if both expressions are faux.

Allow'southward have a await at the previous example. The only change is that the while loop now says or instead:

          >>> a = five >>> b = 10 >>> count = 0 >>> while count < a or count < b: ...     print(f"count: {count}, a: {a}, b: {b}") ...     count += 1 ... count: 0, a: 5, b: ten count: 1, a: 5, b: ten count: 2, a: 5, b: 10 count: 3, a: v, b: ten count: 4, a: 5, b: ten count: 5, a: 5, b: ten count: 6, a: v, b: 10 count: 7, a: 5, b: x count: viii, a: five, b: 10 count: 9, a: 5, b: 10                  

Now, the loop doesn't cease afterwards the count variable reaches the same value equally a. That's because the second condition, count < b, notwithstanding holds true. Since at to the lowest degree ane condition is true, the loop body continues to execute until count reaches a value of x. So, the second condition evaluates to false too, and the loop terminates.

Logical NOT Operator

There's 1 other logical operator that yous can use to write Python while loops with multiple conditions, and that'due south logical not:

          while ( non CONDITIONAL EXPRESSION ): 	EXECUTE STATEMENTS                  

This operator simply reverses the value of a given boolean expression. In other words, not Truthful will return fake, and not Imitation will return true.

Evaluating Multiple Conditions

Permit's add a tertiary conditional expression to the code. Earlier, y'all defined the random variable max_iterations to control the execution of the loop body. Define this again to set up a new random number and add information technology to the while argument:

          >>> a = v >>> b = ten >>> max_iterations = random.randint(0,ten) >>> >>> count = 0 >>> while count < a or count < b and non count >= max_iterations: ...     print(f"count: {count}, a: {a}, b: {b}") ...     count += 1 ... count: 0, a: v, b: ten count: i, a: 5, b: 10 count: 2, a: v, b: 10 count: 3, a: 5, b: 10 count: 4, a: 5, b: x count: five, a: five, b: 10 count: half dozen, a: 5, b: 10 count: seven, a: 5, b: x                  

This Python while loop has multiple atmospheric condition that all need to be evaluated together. The showtime condition checks whether count is less than a. The second condition checks whether count is less than b. The 3rd condition uses the logical not operator to check that the value of count has not reached the maximum number of iterations. Python has fix this value to a random number (here, max_iterations was 8). So, the loop runs for eight iterations and so terminates - only which condition caused this?

Python evaluates conditional expressions from left to right, comparison two expressions at a time. I tin can use parentheses to better visualize how this works:

          while ( Provisional EXPRESSION A or Conditional EXPRESSION B ) and not Conditional EXPRESSION C                  

Python groups the offset two conditional expressions and evaluates them together. In the code block above, count is compared to a and and then to b. The logical or operator that combines these two statements says to render true if either i of them is true. This is the instance for all 8 iterations of the loop (count is always less than a or b).

Next, Python combines the result of the first evaluation with the tertiary condition:

          while ( Effect and not Conditional EXPRESSION C )                  

Here, RESULT volition either exist true or false. Python uses the logical and operator to combine this with the tertiary condition. If both are true, then the loop body volition go along to execute. If ane is imitation, then the loop volition terminate.

Truth tables are a great tool to aid visualize how a Python while loop with multiple conditions will evaluate each one.

Note that the loop terminates on the 9th iteration. This is something you may not see in your terminal output. That's because the ninth iteration causes the while statement to evaluate to false. Here, count is still less than a or b, only the maximum number of iterations has been reached. Even though the second condition is still true, the logical and requires the third condition to exist truthful besides. Since information technology's faux, the loop torso terminates.

Grouping Multiple Conditions

Parentheses tin can assist you to see how Python evaluates while loops with multiple weather, only they can likewise be used to command how Python evaluates multiple provisional expressions.

Recall the previous example:

          while ( CONDITIONAL EXPRESSION A or Conditional EXPRESSION B ) and non Provisional EXPRESSION C                  

Here, you used parentheses to visualize how Python evaluates conditional expressions from left to correct. You tin as well apply parentheses directly in your lawmaking to tell Python which expressions should be considered together first.

Allow's set max_iterations to a smaller number to see this in action. Set it to 3 and start the while loop again, grouping the first two expressions in parentheses:

          >>> 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 ... count: 0, a: v, b: ten count: 1, a: five, b: ten count: 2, a: v, b: 10                  

The parentheses tells Python to group the commencement two statements together, and so to combine their outcome with whatever statement comes next. You've now reduced the multiple weather condition into 2 groups: "count is less than a or b AND count is not greater than or equal to max_iterations." This statement evaluates to imitation after the third iteration, and then the loop stops here.

What happens if y'all motion the parentheses and grouping the terminal 2 statements together? Let'southward accept a look:

          >>> 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 ... count: 0, a: v, b: ten count: ane, a: 5, b: x count: 2, a: 5, b: 10 count: 3, a: 5, b: ten count: iv, a: 5, b: ten                  

Here, the loop runs for 5 iterations, which is far higher up the maximum number of 3. What happened?

Python nevertheless evaluates the conditional expressions from left to correct. Offset, it checks to see whether count is less than a. If this is truthful, Python then moves to the side by side statement, which is a group of ii conditional expressions. Python and so considers this group every bit a whole, and combines the event with the first provisional statement. The multiple weather are again reduced into 2 groups: "count is less than a OR count is less than b and not greater than or equal to max_iterations." When count is 3 - the maximum number of iterations - the expression still evaluates to truthful due to the logical or. The loop runs until both the expression before the logical or and the grouped expressions after it cause the while argument to evaluate to false.

Summary

In this commodity, you learned how to write a Python while loop with multiple conditions.

Yous reviewed indefinite iteration and how while statements evaluate conditional expressions. Then, you saw how to use logical operators to combine multiple conditions in while statement. Lastly, you looked at how group multiple weather together in parentheses tin can assist both to visualize statement evaluation and control loop body execution.

Next Steps

If you're interested in learning more than about the nuts of Python, coding, and software development, cheque out our Coding Essentials Guidebook for Developers, where nosotros cover the essential languages, concepts, and tools that yous'll demand to become a professional developer.

Indefinite iteration is one of the first techniques you'll learn on your Python journey. For other start Python tutorials, bank check out our guides on functions in Python iii, the Python min() office, and the Python floor() office.

Thanks and happy coding! We promise you enjoyed this article. If you have any questions or comments, feel gratis to accomplish out to jacob@initialcommit.io.

Final Notes