the condition in a while loop must evaluate to what type of value?
viii.3. The while
Statement¶
There is another Python statement that can as well exist used to build an iteration. It is called the while
statement. The while
statement provides a much more general machinery for iterating. Similar to the if
statement, it uses a boolean expression to command the menstruum of execution. The trunk of while will exist repeated equally long as the controlling boolean expression evaluates to True
.
The following figure shows the flow of control.
We can apply the while
loop to create whatever type of iteration nosotros wish, including anything that we have previously done with a for
loop. For example, the program in the previous section could be rewritten using while
. Instead of relying on the range
part to produce the numbers for our summation, nosotros will need to produce them ourselves. To to this, we will create a variable chosen aNumber
and initialize it to 1, the first number in the summation. Every iteration will add together aNumber
to the running total until all the values take been used. In order to control the iteration, we must create a boolean expression that evaluates to Truthful
equally long as nosotros desire to go on adding values to our running total. In this case, as long every bit aNumber
is less than or equal to the bound, we should keep going.
Here is a new version of the summation program that uses a while argument.
You tin can almost read the while
statement as if it were in tongue. It means, while aNumber
is less than or equal to aBound
, keep executing the body of the loop. Within the body, each time, update theSum
using the accumulator blueprint and increment aNumber
. After the body of the loop, nosotros go support to the condition of the while
and reevaluate it. When aNumber
becomes greater than aBound
, the condition fails and flow of command continues to the return
statement.
The aforementioned program in codelens will allow you to observe the catamenia of execution.
More than formally, hither is the flow of execution for a while
statement:
-
Evaluate the condition, yielding
Imitation
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 trunk and then go back to footstep i.
The body consists of all of the statements below the header with the same indentation.
This type of period is called a loop because the tertiary stride loops dorsum around to the top. Notice that if the condition is False
the first time through the loop, the statements inside the loop are never executed.
Alert
Though Python's while
is very close to the English "while", there is an important difference: In English "while Ten, do Y", we ordinarily presume that immediately after Ten becomes false, nosotros terminate with Y. In Python there is not an firsthand cease: After the initial test, any following tests come merely after the execution of the whole body, fifty-fifty if the condition becomes simulated in the center of the loop body.
The trunk of the loop should change the value of one or more variables so that somewhen the status becomes False
and the loop terminates. Otherwise the loop will repeat forever. This is chosen an space loop. An countless source of amusement for computer scientists is the observation that the directions written on the back of the shampoo bottle (lather, rinse, repeat) create an infinite loop.
In the case shown higher up, we can prove that the loop terminates because we know that the value of aBound
is finite, and nosotros tin run across that the value of aNumber
increments each time through the loop, so eventually it will have to exceed aBound
. In other cases, information technology is not so piece of cake to tell.
Note
Introduction of the while statement causes usa to recall about the types of iteration nosotros have seen. The for
statement volition e'er iterate through a sequence of values like the listing of names for the party or the list of numbers created past range
. Since nosotros know that information technology will iterate once for each value in the drove, it is often said that a for
loop creates a definite iteration considering we definitely know how many times we are going to iterate. On the other hand, the while
argument is dependent on a condition that needs to evaluate to Faux
in order for the loop to stop. Since nosotros do not necessarily know when this will happen, information technology creates what nosotros telephone call indefinite iteration. Indefinite iteration merely means that we don't know how many times we volition repeat but eventually the status controlling the iteration volition neglect and the iteration volition stop. (Unless we have an infinite loop which is of course a problem.)
What you will notice here is that the while
loop is more work for you — the programmer — than the equivalent for
loop. When using a while
loop you take to control the loop variable yourself. You give it an initial value, test for completion, and so brand sure you change something in the body and then that the loop terminates.
And so why have 2 kinds of loop if for
looks easier? The adjacent department, Randomly Walking Turtles, shows an indefinite iteration where we need the extra power that we go from the while
loop.
Note
This workspace is provided for your convenience. Yous can use this activecode window to endeavor out anything you similar.
Check your agreement
- True
- Although the while loop uses a unlike syntax, it is just as powerful as a for-loop and oft more flexible.
- False
- Often a for-loop is more natural and convenient for a task, but that same task tin e'er be expressed using a while loop.
iter-3-5: True or False: You tin can rewrite whatsoever for-loop as a while-loop.
- n starts at ten and is incremented by ane each time through the loop, and so it volition always be positive
- The loop volition run as long as northward is positive. In this example, we tin can encounter that n will never become not-positive.
- answer starts at 1 and is incremented by n each time, so it will always exist positive
- While it is truthful that respond volition always be positive, reply is not considered in the loop status.
- You cannot compare north to 0 in while loop. You must compare it to another variable.
- It is perfectly valid to compare n to 0. Though indirectly, this is what causes the infinite loop.
- In the while loop trunk, nosotros must set up n to Simulated, and this lawmaking does not exercise that.
- The loop condition must become Fake for the loop to stop, only due north past itself is not the condition in this case.
iter-3-6: The following code contains an infinite loop. Which is the best explanation for why the loop does non terminate?
n = 10 answer = 1 while n > 0 : answer = reply + n n = northward + one print ( answer )
- 4 seven
- Setting a variable and then the loop condition would be false in the center of the loop body does not proceed the variable from actually existence set.
- 5 seven
- Setting a variable so the loop condition would exist fake in the middle of the loop body does not stop execution of statements in the rest of the loop torso.
- 7 15
- Subsequently north becomes 5 and the test would exist Faux, simply the test does not actually come up until afterwards the end of the loop - only then stopping execution of the repetition of the loop.
iter-3-7: What is printed by this lawmaking?
n = 1 ten = 2 while n < 5 : n = n + i x = ten + 1 north = n + 2 10 = 10 + n impress ( n , x )
Source: https://runestone.academy/ns/books/published/thinkcspy/MoreAboutIteration/ThewhileStatement.html
0 Response to "the condition in a while loop must evaluate to what type of value?"
Post a Comment