While Loop in Python | Syntax, Example
While loop in Python is the most fundamental loop statement that repeatedly executes a statement or a group of statements, as long as the specified test condition or expression evaluates to true.
In other words, a while loop repeats the body of the loop as long as a given condition is true.
It evaluates the condition each time it executes the loop body, and it exits the loop when the condition becomes false. Each repetition of the body of loop is called iteration of loop.
Python while loop is the simplest of all the looping structures. It is an entry-controlled loop statement. In the entry-controlled loop, Python first evaluates the test condition. If the specified condition is true, then the loop body executes.
If the condition is false, then the loop body does not execute. In this way, the while loop statement executes a block of code repeatedly while the test condition is true.
You can use the while loop statement in Python when you don’t know how many times you want to repeat the code.
Syntax of While Loop in Python
The general syntax for using the while loop in Python is as:
Initialization
while test condition:
# Loop body
statement(s)
In the above syntax, the while loop starts with a while keyword that creates a loop. It is followed by test condition or expression, then a colon (:) character.
The test condition or expression consists of boolean expression that produces either true or false value depending on the counter control variable. A while loop doesn’t have a loop variable that sets a range of values. It has a loop condition.
In the syntax, statement(s) may be a single statement or a group of statements with uniform indentation.
How does While Loop work in Python?
Let’s understand how a while loop works in Python:
1. Python first evaluates the test condition or expression in the while() loop before the execution of statements in the while loop block.
2. When the test condition is true, then the loop body (i.e. a block of statements) executes. After the execution of loop body, the test condition once again evaluates to true.
3. If the specified condition is true, the loop body executes once again. This process of repeated execution of loop body continues by the Python interpreter until the condition or expression finally becomes false.
4. Once the test condition is false, the loop terminates and the program control immediately transfers out of the loop.
5. On exit, the program continues to execute the next statement immediately after the while loop. Each execution of the loop body refers to as an iteration (or repetition) of loop. The flowchart for while loop in Python has shown in the below diagram.
Now let us consider the following code segment below:
# Initialization: The variable count has defined outside the loop and will update inside the loop.
count = 0
# Declare the while loop statement.
# Loop continuation condition expression that must ends with a colon (:).
while count < 5:
# Body of the loop.
print('Hello Python') # This statement will execute as long as the condition is true.
count += 1 # It counts the number of executions, and increments count by 1.
print('Loop finished.') # Continue program if the condition is false.
From the above example, let us understand how the while loop actually works in Python. The flowchart for this script code has shown in the above diagram.
In this example code, the body of loop will execute 5 times for count = 0, 1, 2, 3, 4. Each time a statement “Hello Python” will print on the console.
When the count is equal to 5, the condition becomes false and the loop ends. The program control will transfer out of the loop to execute the rest of the code inside the program.
In the above example, count is a control variable that controls the number of executions. It increments by 1 after each repetition or loop. This kind of loop is called counter-controlled loop in Python.
Example Program based on Python While Loop Statement
Example 1:
Let’s write a simple Python program to print the first 5 natural numbers by using while loop statement.
# Program to display numbers from 1 to 5.
i = 1 # Initialization.
while i <= 5:
print('Current value of i is ',i)
i = i + 1 # Increment by 1.
Output: Current value of i is 1 Current value of i is 2 Current value of i is 3 Current value of i is 4 Current value of i is 5
In this example, we have assigned the value 1 to the variable i. The while loop block consists of print and increment statements and executes repeatedly until the variable i is greater than 5.
With each iteration, the current value of i is printed and then increased by 1. This process continues until the condition in the while statement evaluates to false.
Example 2:
Let us write a program in Python to print your name five times using while loop.
# Program to display your name five times.
i = 0 # Initialization.
name = input('Enter your name: ')
while i < 5:
print(name)
i = i + 1 # Increment by 1.
Output: Enter your name: Tripti Tripti Tripti . . Tripti
Example 3:
Let’s write a Python program to display numbers from 5 to 1 by using while loop statement.
# Program to display numbers from 5 to 1.
i = 5 # Initialization.
while i >= 1:
print(i)
i = i - 1 # decrement by 1.
print('Loop finished')
Output: 5 4 3 2 1 Loop finished
In the preceding example, the while loop prints number starting from 5 and going down to 1, until the specified condition i >= 1 evaluates to true. As the value of i is less than 1, the condition is false and the loop ends.
Example 4:
Let us write a program to calculate the average of n natural numbers where n is an input taken from the user.
# Program to display the average of n natural numbers.
num = int(input('Enter a number up to which you want to calculate average: '))
i = 0
sum = 0
count = 0 # Initialization.
while i < num:
i = i + 1 # Increment by 1.
sum = sum + i
count = count + 1
average = sum / count
print('Average of', num,'natural numbers = ', average)
Output: Enter a number up to which you want to calculate average: 5 Average of 5 natural numbers = 3.0
In this example, we have assigned the variable i, sum, count with a value 0. Python evaluates the expression i < num. Since it is true for the first iteration, the body of while loop executes.
The variable i increments by the value of 1 and it produces the required natural numbers. Variable sum adds the value of sum with the value of i. The variable count keeps the track of number of times the loop body gets executed.
Python repeats the loop until the test expression becomes to false. We calculated the average as sum/count and printed it on the console.
Example 5:
Let us write a program to calculate the sum of first 10 natural numbers using while loop. That is, 1 + 2 + 3 + . . . + 10 = 55.
# Program to display the sum of first 10 natural numbers.
sum = 0
count = 0 # Initialization.
while count <= 10:
sum = sum + count
count = count + 1
print('Sum of 10 natural numbers = ', sum)
Output: Sum of 10 natural numbers = 55
Some More Advanced Program based on While Loop
Example 6:
Let’s write a program in Python to find the sum of digits in a number.
# Program to display the sum of digits in a number.
num = int(input('Enter a number: '))
sum = 0
remainder = 0
while num != 0:
remainder = num % 10
sum = sum + remainder
num = int(num / 10)
print('Sum of all digits in number = ', sum)
Output: Enter a number: 123456 Sum of all digits in number = 21
In this example, we have used a function named input() to read an integer number from the user and stored it in a variable num. We have assigned the variables sum and remainder with value 0.
Then, we need to calculate the last digit of the number. To get the last digit of a number, we have used the modulus division by 10 and assigned it in the variable remainder.
Now we have added the obtained last digit with the sum variable. We removed the last digit from the number by dividing the number by 10 and cast it as int. This logic will continue until the variable num becomes 0. Finally, we will get the sum of digits in a variable sum.
Example 7:
Let’s write a program in Python to calculate the GCD of two positive numbers.
# Program to find the GCD of two +ve numbers.
n1 = int(input('Enter the first positive number: '))
n2 = int(input('Enter the second positive number: '))
if(n1 == 0 and n2 == 0):
print('Invalid input')
if(n1 == 0):
print('GCD = ',n2)
if(n2 == 0):
print('GCD = ',n1)
while(n1 != n2):
if(n1 > n2):
n1 = n1 - n2
if(n2 > n1):
n2 = n2 - n1
print('GCD of two numbers = ',n1)
Output: Enter the first positive number: 8 Enter the second positive number: 12 GCD of two numbers = 4
In this program, we have read two numbers using the function input() from the user and stored them into variables n1 and n2. We have used if statement to check the conditions.
If both n1 and n2 are zero, it is invalid input because zero cannot be divided by zero, which is indeterminate. If n1 or n2 is zero, the other one is gcd.
When the value of n1 > n2, then n1 = n1 – n2, or n2 > n1, then n2 = n2 – n1. This logic will continue repeatedly until the value of n1 is equal to the value of n2. Finally, the GCD will be n1.
Example 8:
Let’s write a program in Python using while loop to find the Fibonacci series of numbers till 30. The Fibonacci series is: 0, 1, 1, 2, 3, 5, 8, 13, . . . .
# Program to find the Fibonacci series of numbers till 30.
num1 = 0
num2 = 1
print('Fibonacci series of numbers till 30 are: ')
print(num1, num2, end = ' ')
while num2 < 21:
num1, num2 = num2, num1 + num2
print(num2, end = ' ')
Output: Fibonacci series of numbers till 30 are: 0 1 1 2 3 5 8 13 21
Example 9:
Let’s write a program in Python using while loop to display the following pattern.
* * * * *
* * * *
* * *
* *
*
# Program to print pattern.
nrows = int(input('Enter the number of rows: '))
while nrows >= 0:
x = '* ' * nrows
print(x)
nrows = nrows - 1
Output: * * * * * * * * * * * * * * *
Example 10:
Let’s write a program in Python to display the following pattern using while loop statement.
*
* *
* * *
* * * *
* * * * *
# Program to print pattern.
nrows = int(input('Enter the number of rows: '))
n = 1
while n <= nrows:
x = '* ' * n
print(x)
n = n + 1
Output: * * * * * * * * * * * * * * *
Example 11:
Let’s write a program in Python using the while loop to display the mathematical table of an input number.
# Program to print table of an input number.
num = int(input('Enter a number to find table: '))
count = 1
t = 1
while count <= 10:
t = num * count
print(num,'*',count,'=',t)
count = count + 1
Output: Enter a number to find table: 5 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20
In this tutorial, you have learned while loop statement in Python with the help of various example programs. I hope that you will have understood the basic syntax of while loop and practiced all example programs. Stay with our next tutorial where we will understand for loop in Python.
Thanks for reading!!!