Boolean Expression to Determine if an Iteration Statement Will Execute Its Statement Sequence Again
8.iii. The while
Argument¶
In that location is some other Python statement that can also be used to build an iteration. It is called the while
statement. The while
statement provides a much more general machinery for iterating. Like to the if
argument, it uses a boolean expression to command the menstruation of execution. The trunk of while will be repeated every bit long as the controlling boolean expression evaluates to True
.
The following figure shows the flow of control.

We tin can apply the while
loop to create any type of iteration we wish, including annihilation that we have previously done with a for
loop. For example, the programme in the previous section could be rewritten using while
. Instead of relying on the range
function to produce the numbers for our summation, nosotros volition need to produce them ourselves. To to this, nosotros volition create a variable called aNumber
and initialize it to 1, the first number in the summation. Every iteration will add aNumber
to the running full until all the values have been used. In club to command the iteration, we must create a boolean expression that evaluates to True
as long as nosotros want to keep calculation values to our running total. In this instance, as long equally aNumber
is less than or equal to the bound, we should continue going.
Here is a new version of the summation programme that uses a while statement.
You lot tin almost read the while
statement as if it were in natural language. Information technology means, while aNumber
is less than or equal to abound
, continue executing the body of the loop. Inside the body, each time, update theSum
using the accumulator pattern and increment aNumber
. After the body of the loop, we get back up to the condition of the while
and reevaluate it. When aNumber
becomes greater than grow
, the condition fails and flow of command continues to the render
statement.
The same program in codelens volition allow y'all to observe the menstruation of execution.
Activity: CodeLens 8.3.three (ch07_while2)
More formally, here is the flow of execution for a while
statement:
-
Evaluate the status, yielding
False
orTrue
. -
If the status is
False
, exit thewhile
statement and continue execution at the next statement. -
If the condition is
True
, execute each of the statements in the body and then go back to step ane.
The torso consists of all of the statements beneath the header with the same indentation.
This type of catamenia is chosen a loop because the third stride loops back around to the acme. Notice that if the status is False
the first fourth dimension through the loop, the statements inside the loop are never executed.
Warning
Though Python's while
is very close to the English language "while", at that place is an important divergence: In English "while X, do Y", nosotros normally presume that immediately subsequently X becomes false, we stop with Y. In Python there is not an immediate stop: After the initial test, any post-obit tests come simply afterward the execution of the whole body, even if the status becomes false in the eye of the loop body.
The body of the loop should change the value of one or more variables and then that eventually the condition becomes Faux
and the loop terminates. Otherwise the loop volition repeat forever. This is called an infinite loop. An endless source of entertainment for estimator scientists is the observation that the directions written on the back of the shampoo bottle (soap, rinse, repeat) create an infinite loop.
In the case shown above, we tin can prove that the loop terminates because we know that the value of grow
is finite, and we can encounter that the value of aNumber
increments each fourth dimension through the loop, then somewhen it will have to exceed aBound
. In other cases, it is not so easy to tell.
Note
Introduction of the while statement causes us to think about the types of iteration we have seen. The for
statement will always iterate through a sequence of values like the list of names for the party or the list of numbers created by range
. Since we know that information technology will iterate in one case for each value in the collection, it is often said that a for
loop creates a definite iteration considering nosotros definitely know how many times nosotros are going to iterate. On the other hand, the while
statement is dependent on a condition that needs to evaluate to False
in lodge for the loop to terminate. Since we do not necessarily know when this will happen, it creates what we phone call indefinite iteration. Indefinite iteration but means that nosotros don't know how many times nosotros volition repeat but eventually the condition controlling the iteration volition fail and the iteration will finish. (Unless we have an space loop which is of course a trouble.)
What you will observe here is that the while
loop is more work for you — the developer — than the equivalent for
loop. When using a while
loop you have to control the loop variable yourself. Yous requite it an initial value, test for completion, then make certain you alter something in the body so that the loop terminates.
Then why have two kinds of loop if for
looks easier? The next section, Randomly Walking Turtles, shows an indefinite iteration where nosotros need the extra power that we get from the while
loop.
Note
This workspace is provided for your convenience. Yous can utilise this activecode window to effort out anything you lot like.
Check your understanding
- True
- Although the while loop uses a dissimilar syntax, information technology is just as powerful equally a for-loop and often more flexible.
- False
- Ofttimes a for-loop is more natural and convenient for a chore, but that same task can always be expressed using a while loop.
iter-3-5: True or Fake: Y'all can rewrite whatsoever for-loop as a while-loop.
- north starts at ten and is incremented by 1 each fourth dimension through the loop, so it will e'er be positive
- The loop will run as long as n is positive. In this instance, we can see that n will never become not-positive.
- answer starts at 1 and is incremented by due north each time, so it will always be positive
- While it is true that answer will always be positive, answer is not considered in the loop condition.
- Y'all cannot compare n to 0 in while loop. You must compare information technology to another variable.
- Information technology is perfectly valid to compare north to 0. Though indirectly, this is what causes the infinite loop.
- In the while loop body, we must set n to Fake, and this code does not exercise that.
- The loop condition must become False for the loop to terminate, just north by itself is not the condition in this case.
iter-3-half-dozen: The following code contains an infinite loop. Which is the best explanation for why the loop does not stop?
n = ten answer = 1 while north > 0 : answer = respond + n n = north + 1 impress ( reply )
- 4 seven
- Setting a variable then the loop condition would exist fake in the heart of the loop body does not go along the variable from actually beingness set.
- 5 7
- Setting a variable so the loop condition would exist simulated in the middle of the loop body does not stop execution of statements in the rest of the loop body.
- 7 15
- Afterward n becomes 5 and the test would be False, but the examination does not really come up until after the end of the loop - but then stopping execution of the repetition of the loop.
iter-3-7: What is printed past this lawmaking?
due north = 1 x = 2 while n < v : n = due north + 1 x = x + ane n = n + 2 x = x + n print ( due north , x )
You have attempted of activities on this page
Source: https://runestone.academy/ns/books/published/thinkcspy/MoreAboutIteration/ThewhileStatement.html
0 Response to "Boolean Expression to Determine if an Iteration Statement Will Execute Its Statement Sequence Again"
Post a Comment