|
The while StatementIn Python, you use the while statement to specify code that is to be executed as long as a specified condition is true. Because this code can execute more than once, the while statement is sometimes referred to as a loop. Here is a simple example of a loop created using while:
In this example, the while statement checks whether x is less than or equal to 10. (As before, x <= 10 is the conditional expression for the loop.) If it is, the value of x is printed, and 1 is added to x. The process is repeated until x becomes greater than 10. Because x starts at 1, the loop is executed ten times, and the code displays the numbers from 1 to 10. The while statement uses the same comparison operators as the if statement. The statements included with the while condition must be indented.
|