While loop is a popular looping construct in Python. Just like the for loop, the while loop is used to repeat an action any given number of times. Unlike the for loop, the while loop continues to loop until the condition for the loop becomes False.
The while loop consists of the following steps:
- Initializing a flag
- Test expression
- Action/Updating the flag
The syntax for the while loop is shown below:
number = 1 while number < 11: print(number) number += 1 #outputs #1 #2 #3 #4 #5 #6 #7 #8 #9 #10
In the above example, the variable number, which is also known as the control flag is initialized to 1.
The test expression is number < 11. This means that the loop continues as long as the number is less than 11.
Inside the body of the loop is an action, which is print(number).
Then, the flag is updated using the increment operator +=.
Getting user inputs using the input() function
Instead of writing programs that produce only outputs, with the input() function you can be able to interact with the user by prompting them for information.
name = input() print(name)
The above example prompts the user for information and assigns it to the variable name.
If you run this code, you will only get a blank line and no description of the kind of data or information to supply.
Interestingly, you can provide a description of the information that you seek to get from your user, as an argument to the input() function in the form of a string.
name = input('please enter your name: ") print(name)
Now, let’s use the while loop together with the input() function for counting.
number = input('enter any number: ') count = 0 while count < int(number): count += 1 print(f'counting {count}') #output # enter any number: 10 # counting 1 # counting 2 # counting 3 # counting 4 # counting 5 # counting 6 # counting 7 # counting 8 # counting 9 # counting 10
Finding the sum and average of numbers
The following example uses the while loop together with the input() to get numbers from users. Thereafter, a sum and an average of the numbers are computed.
count = 0 sum = 0 while count < 10: number = int(input('enter any number: ')) sum += number count += 1 avg = sum/10 print(f'sum: {sum} \nAverage: {avg}') #output # enter any number: 34 # enter any number: 65 # enter any number: 23 # enter any number: 75 # enter any number: 34 # enter any number: 8 # enter any number: 23 # enter any number: 87 # enter any number: 43 # enter any number: 76 # sum: 468 # Average: 46.8
Keep in mind that the input() function returns a string. As you can see from the above examples, numbers obtained through the input() function are converted to integers using the int() functions in order to use it like a number.
Also, you will notice that the program determined how many times to prompt for numbers from the users.
The example below is a modified version of the previous one. The program can loop as many times as possible, prompting the user for information until the user decides to stop the iteration.
You can define a quit value that keeps the program running as long as the value is not entered.
sum = 0 count = 0 value = input('enter any number or quit to stop: ') while value != 'quit': number = int(value) sum += number count += 1 value = input('enter any number or quit to stop: ') avg = sum/count print(f'sum: {sum} \nAverage: {avg}') #output # enter any number or quit to stop: 12 # enter any number or quit to stop: 34 # enter any number or quit to stop: 16 # enter any number or quit to stop: 50 # enter any number or quit to stop: 23 # enter any number or quit to stop: quit # sum: 135 # Average: 27.0
Examples with the while loop
Now, let’s explore other different ways of using the while loop in solving real-life problems with examples.
printing items in a list using a while loop
The example below uses the while loop to iterate over the items in a sequence and print the values of the item as a result.
It keeps track of the iteration using the variable count, and at the same time uses it as the index of the item to fetch in the list.
fruits = ['apple', 'orange', 'mango', 'grape', 'banana'] count = 0 while count < len(fruits): print(fruits[count]) count += 1 #outputs # apple # orange # mango # grape # banana
printing letters of a word
Since strings are sequences of characters, the letters composing a string can be fetched with a while loop taking advantage of the indexes of the characters.
fruit = 'apple' count = 0 while count < len(fruit): print(fruit[count]) count += 1 #outputs # a # p # p # l # e
Squares of numbers using the while loop
Consider a list consisting of numbers. With the while loop, you can create a new list containing the squares of the values in the list.
numbers = [1,2,3,4,5] squares = [] count = 0 while count < len(numbers): squares.append((numbers[count])**2) count+=1 print(squares) #[1, 4, 9, 16, 25]
reversing a number
Now, let’s use the while loop to reverse the order of digits in a number.
num = 123 string_number = str(num) count = -1 chars = [] while count >= -(len(string_number)): chars.append(string_number[count]) count-=1 char_num = ''.join(chars) #convert to number new_num = int(char_num) print(initial Number: {num} \nReversed Number: {new_num}')
finding factorial of a number
Factorial in mathematics is a product of all the numbers positive integers less than the number and the number.
The example below uses the while loop to calculate the factorial of a given number.
num = 5 factorial = 1 count = 1 while count < num+1: factorial *= count count += 1 print(f'The factorial of {num} is {factorial}') #output # The factorial of 5 is 120