While
While
While[ cond ] ... End executes a script block repeatedly, as long as a condition holds.
Usages
While[ cond ] ... End
Checks cond, and if it is not False, executes the script between While and End. This is repeated until cond is False. If cond is False at the start, the block is never executed. As in If, comparisons such as < are evaluated in the condition.
| Example | in | out |
|---|---|---|
Count to 10. |
ii := 0 |
ii = 10 |
The condition is False at the start, so the block is not executed. |
ii := 20 |
ii = 20 |
Multiply by random numbers until the product is at least 100. |
total := 1 |
for example total = 189 |
Choose a new random number until it differs from x. |
x := RandomInt[{1, 10}] |
for example x = 3y = 7 |
Details
- Number of iterations: the block can be executed at most 101 times. If the condition still holds after that, the script stops with an error.
Warning
Make sure the condition becomes False. A condition that cannot be decided, such as y < 10 when y has no value, is treated as True, so the loop never ends and the script stops with an error after 101 iterations. Use Strict if the condition may be undecided: While[Strict[y < 10]].