python while

By: Ashley J Viewed: 132 times  Printer Friendly Format    

Python while statement repeats execution of a statement or block of statements, until the loop condition is true. The syntax of the while statement:

while expression:

A while statement can also include an else clause, and break and continue statements.

Here’s a typical while statement:

count = 0
while x > 0:
    x //= 2            # truncating division
    count += 1
print('The approximate log2 is', count)

First, Python evaluates expression, which is known as the loop condition. When the condition is false, the while statement ends. When the loop condition is true, the statement or statements that make up the loop body execute again and again. Once the loop body finishes executing, Python evaluates the loop condition again from the top to check whether another iteration should execute. This process continues until the loop condition is false, at which point the while statement ends.

The loop body should contain code that eventually makes the loop condition false; otherwise, the loop becomes an infinite loop (unless the body raises an exception or executes a break statement). A loop within a function’s body also ends if the loop body executes a return statement, since in this case the whole function ends.

Most Viewed Articles (in Python )

Latest Articles (in Python)

Comment on this tutorial