image
image
image

while Loop in Python

image

In Python, the while loop is used to iterate over a block of program code as long as the test condition stays True. The while loop is used in contexts where the user does not know the loop cycles that are required. As indicated earlier, the while loop body is determined through indentation.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

image

Caution: Failing to include the value of the counter will lead to an infinite loop.

Practice Exercise

a.  Write a Python program that utilizes the while flow control statement to display the sum of all odd numbers from 1 to 10.

b.  Write a Python program that employs the while flow control statement to display the sum of all numbers from 11 to 21.

c.  Write a Python program that incorporates while flow control statement to display the sum of all even numbers from 1 to 10.