Loops – While-loop Examples in Python

While loops capture the scenario of looping until a specified event happens (like a repeat-until in Scratch).  The first action of execution in a while-loop is checking whether the event is already satisfied. A flowchart as shown below is an intuitive representation (some students find it helpful to understand the flow of execution).  while loop

Example 1 showed how to print the numbers from 1 to 99 using a for-loop. Here is the same problem using a while loop:

number = 1
while number < 100:
	print(number)
	number = number + 1

Examples 6, 7, and 8  present three problems that are naturally solved using a while loop.

Example 6: Sum up the digits in an integer  

Example 7: Guess a chosen letter in the alphabet 

Example 8: The use of a sentinel value in while loops