The while statement is used to loop through the program and the loop can be repeatedly executed to process the same task.
The basic form of while loop:
while judgement conditions:
Execution statement……
An execution statement can be a single statement or a block of statements. The judgment condition can be any expression. When the condition is false, the loop ends.
Source Code
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
count = 0
while (count < 9):
print ('The count is:%d', count)
count = count + 1
print('hello')
Output:
The count is:%d 0 The count is:%d 1 The count is:%d 2 The count is:%d 3 The count is:%d 4 The count is:%d 5 The count is:%d 6 The count is:%d 7 The count is:%d 8 hello
Tips
The while statement has two other important commands: continue and break. Continue is used to skip the following statements in the loop, break is used to exit the loop. In addition, the “judgment condition” can be set to be a non-zero constant value, indicating that the loop will continue until hitting the target. This can be used in some situations like word guessing games. User can have as many attempts as possible until they guess the word correctly.
- While + continue
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
i = 1
while i < 10:
i += 1
if i % 2 > 0: #Skip output when non-double
continue
print(i)
Output:
2
4
6
8
10
- While + break
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
i = 1
while 1: #The loop condition is 1 must be established
print(i)
# Output 1~10
i += 1
if i > 10: # Jump out of the loop when i is greater than 10
break
Output:
1
2
3
4
5
6
7
8
9
10