Alterna · учебный материал
Wile Cycle
36.2: Whyle Cycle: Short theory, one example, and Python stepway.
Что в этом материале
- How it works.
- One example in execution
- Remember
Содержание и основные понятия
while repeats the body as long as the condition is true. It is chosen when the number of repetitions is unknown in advance, but the criterion of continuity is known.
substance and practice
Grade 8
OGE No. 6
OGE No. 16
EGE No. 25
01
How it works.
while repeats the body as long as the condition is true. It is needed when the end of processing is determined by the data, not the pre-known number of repetitions.
Initialization.
Creates a state before the first test.
Condition.
It is checked for each iteration; the false condition immediately completes the cycle.
Progress.
At least one variable condition should bring the cycle closer to stopping.
Sentinel.
A special value completes the data stream and is not always included in the processing.
02
One example in execution
Start the short program and go over the lines. The visualiser only shows the code, current line, variables and output.
Cycle
while n > 0
naturally takes out positive numbers because
n //= 10
It reduces it.
n = 0
The body will not be fulfilled, so the zero number will be treated separately if the condition so requires.
break
Leaves immediately the nearest cycle;
continue
Both operators are rarely needed: before applying them, try to express the rule as a normal condition.
Algorithm map
Read from left to right, then run the code.
1
Start
2
Take the following value
3
Is the value equal to 0?
4
Yes: finish · No: check
5
Add Allowable to Total
03
Remember
Check that the variable is really changing.
Sentinel 0 shouldn't accidentally get paid unless the condition requires it.
For n = 0 cycle while n > 0 has zero iterations: handle this case separately if you need an answer 1.
Syntax of this page
while condition:
It repeats the block as long as it's true.
break
Immediately completes the next cycle.
continue
Moving on to the next cycle test, missing the rest of the body.
//=
Shortened whole division, often reducing the number in the numerals.
True
Logical constant; while True requires a clear break.
int(input())
Reads another number of flows.
print
It's the end of the line after the stop.