Looping Until a Condition Is Reached
for loops are useful only if you know how many iterations of the loop you need. In some situations, it is not known in advance how many loop iterations to execute. In a game program, for example, you can’t know whether a player is going to want to play again or quit. In these situations, we use a while loop. The general form of a while loop is as follows:
| | while expression: |
| | block |
The while loop expression is sometimes called the loop condition, just like the condition of an if statement. When Python executes a while loop, it evaluates the expression. If that expression evaluates to False, that is the end of the execution of the loop. If the expression evaluates to True, on the other hand, Python executes ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access