Loops in Python#
Loops in Python programming function similar to loops in C, C++, Java or other languages. Python loops are used to repeatedly execute a block of statements until a given condition returns to be False
. In Python, we have two types of looping statements, namely:
Python while
Loop#
Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while
loop in Python. We use a while
loop when we want to repeat a code block.
What is while
loop in Python?#
The while
loop in Python is used to iterate over a block of code as long as the expression/condition is True
. When the condition becomes False
, execution comes out of the loop immediately, and the first statement after the while
loop is executed.
We generally use this loop when we don’t know the number of times to iterate beforehand.
Python interprets any non-zero value as True
. None
and 0
are interpreted as False
.
Why and When to use while
loop in Python#
Now, the question might arise: when do we use a while
loop, and why do we use it.
Automate and repeat tasks: As we know,
while
loops execute blocks of code over and over again until the condition is met it allows us to automate and repeat tasks in an efficient manner.**Indefinite Iteration:**The
while
loop will run as often as necessary to complete a particular task. When the user doesn’t know the number of iterations before execution,while
loop is used instead of a for loop loopReduce complexity:
while
loop is easy to write. using the loop, we don’t need to write the statements again and again. Instead, we can write statements we wanted to execute again and again inside the body of the loop thus, reducing the complexity of the codeInfinite loop: If the code inside the
while
loop doesn’t modify the variables being tested in the loop condition, the loop will run forever.
Syntax:#
while condition:
body of while loop
In the
while
loop, expression/condition is checked first.The body of the loop is entered only if the expression/condition evaluates to
True
.After one iteration, the expression/condition is checked again. This process continues until the test_expression evaluates to
False
.
Note: An infinite loop occurs when a program keeps executing within one loop, never leaving it. To exit out of infinite loops on the command line, press CTRL + C.
# Example 1: Print numbers less than 5
count = 1
# run loop till count is less than 5
while count < 5:
print(count)
count = count + 1
1
2
3
4
# Example 2:
num = 10
sum = 0
i = 1
while i <= num:
sum = sum + i
i = i + 1
print("Sum of first 10 number is:", sum)
Sum of first 10 number is: 55
# Example 3:
a=10 # 'a' is my variable
while a>0: # Enter the body of while loop because condition is TRUE
print (("Value of a is"),a)
a=a-2
print ("Loop is Completed")
Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed
# Example 4:
n=153
sum=0
while n>0:
r=n%10 # r is the remainder of the division
sum+=r # sum+=r is equal to sum = sum+r
n=n/10
print (sum)
9.999999999999998
# Example 5: How many times a given number can be divided by 3 before it is less than or equal to 10.
count = 0
number = 180
while number > 10:
# divide number by 3
number = number / 3
# increase count
count = count + 1
print('Total iteration required', count)
Total iteration required 3
# Example 6: Program to add natural numbers up to sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter, i.e., the value of i will change from 1 to 2 in next iteration...
# print the sum
print("The sum is", sum)
The sum is 55
Explanation:
In the above program, the test expression will be True
as long as our counter variable i
is less than or equal to n
(10 in our program).
We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).
Finally, the result is displayed.
# Example 7: simple fibonacci series
# the sum of two elements defines the next set
a, b = 0, 1
while b < 1000:
print(b, end = ' ', flush = True)
a, b = b, a + b
print() # line ending
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
while
loop with if-else
#
A while
loop can have an optional if-else block. We use if-else
statement in the loop when conditional iteration is needed. i.e., If the condition is True
, then the statements inside the if block will execute othwerwise, the else block will execute.
# Example 1: Print even and odd numbers between 1 to the entered number.
n = int(input('Please Enter Number '))
while n > 0:
# check even and odd
if n % 2 == 0:
print(n, 'is a even number')
else:
print(n, 'is a odd number')
# decrease number by 1 in each iteration
n = n - 1
Please Enter Number 9
9 is a odd number
8 is a even number
7 is a odd number
6 is a even number
5 is a odd number
4 is a even number
3 is a odd number
2 is a even number
1 is a odd number
# Example 2: printing the square of odd numbers less than n.
n =10
i = 1
while i < n:
#if (i % 2 == 0): (for even numbers)
if (i % 2 != 0):
print(i ** 2)
i = i + 1
else:
print(i)
i = i + 1
1
2
9
4
25
6
49
8
81
# Example 3: Add all even numbers from 1 to 10 using while loop
# 2+4+6+8+10
# n = int(input("Please enter the maximum value: "))
n = 10
sum = 0
i = 1
while i <= n:
if(i%2==0):
sum = sum + i
# sum += i
i = i+1
# print the sum
print("The sum is", sum)
The sum is 30
# Example 4: Write a code to add all the prime numbers between 17 to 53 using while loop
# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53
'''Method 1'''
sum=0
for i in range(17,54):
k=2
if i>=2:
while i % k!=0:
k+=1
if i==k:
sum += i
print(i)
print("The total sum is",sum)
17
19
23
29
31
37
41
43
47
53
The total sum is 340
while
loop with else
#
A while
loop can have an optional else
block as well. The else
part is executed if the condition in the while
loop evaluates to False
.
The else
will be skipped/ignored when:
while
loop terminates abruptlyThe break statement is used to break the
while
loop
count = 0
while count < 5:
print(count)
count = count + 1
else:
print(count)
0
1
2
3
4
5
Explanation:
The above loop condition will be false when count is 5 and the loop stops, and execution starts the else statement. As a result 5 will be printed.
# Example 1: Use while loop to print numbers from 1 to 6
i = 1
while i <= 6:
print(i)
i = i + 1
else:
print("Done. 'while loop' executed normally")
1
2
3
4
5
6
Done. 'while loop' executed normally
# Example 2: Else block with break statement in a while loop.
i = 1
while i <= 6:
print(i)
if i == 3:
break
i = i + 1
else:
print("Done. `while loop` executed normally")
1
2
3
# Example 3:
'''Example to illustrate the use of else statement with the while loop'''
counter = 0 # counter is my variable
while counter < 3:
print("Inside while loop")
counter = counter + 1 # increment the counter
else:
print("Inside else")
Inside while loop
Inside while loop
Inside while loop
Inside else
Explanation:
Here, we use a counter
variable to print the string Inside loop
three times.
On the fourth iteration, the condition in while
becomes False
. Hence, the else
part is executed.
# Example 4: we want a user to enter any number between 100 and 600
number = int(input('Enter any number between 100 and 600 '))
# number greater than 100 and less than 600
while number < 100 or number > 600:
print('Incorrect number, Please enter correct number:')
number = int(input('Enter a Number between 100 and 600 '))
else:
print("Given Number is correct", number)
Enter any number between 100 and 600 555
Given Number is correct 555
Using Control Statement in while
loops in Python#
Control statements in Python like break
, continue
, etc can be used to control the execution flow of while
loop in Python. Let us now understand how this can be done.
It is used when you want to exit a loop or skip a part of the loop based on the given condition. It also knows as transfer statements.
a) break
in while
loop#
Using the break
statement, we can exit from the while
loop even if the condition is True
.
If the break
statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop. For example,
# Example 1:
count = 0
while count < 5:
print(count)
count = count + 1
if count == 3:
break
0
1
2
Explanation:
Here, the while
loop runs until the value of the variable i
is less than 5. But because of the break
statement, the loop gets terminated when the value of the variable i
is 3 and it prints 0, 1, 2
# Example 2:
list = [60, "HelloWorld", 90.45, 50, 67.23, "Python"] # total 6 elements
i = 0
while(i < 6):
print(list[i])
i = i + 1
if(i == 3):
break
60
HelloWorld
90.45
Explanation:
Here, the while
loop runs until the value of the variable i
is less than 6. But because of the break
statement, the loop gets terminated when the value of the variable i
is 3.
# Example 3: Display each character from a string and if `a` character is number then stop the loop.
name = 'Alan99White'
size = len(name)
i = 0
# iterate loop till the last character
while i < size:
# break loop if current character is number
if name[i].isdecimal():
break;
# print current character
print(name[i], end=' ')
i = i + 1
A l a n
b) continue
in while loop#
The continue
statement is used to stop/skip the block of code in the loop for the current iteration only and continue with the next iteration.
For example, let’s say you want to print all the odd numbers less than a particular value. Here is how you can do it using continue
keyword in Python.
# Example 1:
count = 0
while count < 5:
if count == 3:
continue
else:
print(count)
count = count + 1
0
1
2
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-20-7359b7dba965> in <module>
4 while count < 5:
5 if count == 3:
----> 6 continue
7 else:
8 print(count)
KeyboardInterrupt:
Explanation:
The above while
loop only prints 0, 1, 2 and 4 (skips 3).
# Example 2: printing odd numbers less than `n`
n=10
i = 1
while (i < n):
if (i % 2 == 0):
i = i + 1
continue # continue means skip the current loop
else:
print (i)
i = i + 1
1
3
5
7
9
Explanation:
Here, the continue
statement gets executed when the value of the variable is an even number. This simply means, whenever it is an even number, we simply skip all other statements and execute the next iteration.
# Example 3: Write a while loop to display only alphabets from a string.
name = 'Alan99White'
size = len(name)
i = -1
# iterate loop till the last character
while i < size - 1:
i = i + 1
# skip while loop body if current character is not alphabet
if not name[i].isalpha():
continue
# print current character
print(name[i], end=' ')
A l a n W h i t e
c) pass
in while
loop#
The pass
statement is a null statement, i.e., nothing happens when the statement is executed. Primarily it is used in empty functions or classes. When the interpreter finds a pass statement in the program, it returns no operation.
# Example 1:
n = 4
while n > 0:
n = n - 1
pass
Reverse while
loop#
A reverse loop means an iterating loop in the backward direction. A simple example includes:
Display numbers from 10 to 1.
Reverse a string or list
# Example 1: Reverse a while loop to display numbers from 10 to 1
# reverse while loop
i = 10
while i >= 0:
print(i, end=' ')
i = i - 1
10 9 8 7 6 5 4 3 2 1 0
Nested while
loops#
Nested while loop is a while
loop inside another while
a loop.
In the nested while
loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the iterations in the inner loop. In each iteration of the outer loop inner loop execute all its iteration.
Syntax:
while expression:
while expression:
statement(s)
statement(s)
while
loop inside while
loop#
Example: Nested while
loop#
# Example: print the first 10 numbers on each line 5 times
i = 1
while i <= 3:
j = 1
while j <= 10:
print(j, end='')
j = j + 1
i = i + 1
print()
12345678910
12345678910
12345678910
Example: Nested while
loop to print the pattern#
*
* *
* * *
* * * *
* * * * *
# Example 1: Method 1
i = 1
# outer while loop
# 5 rows in pattern
while i < 6:
j = 0
# nested while loop
while j < i:
print('*', end=' ')
j = j + 1
# end of nested while loop
# new line after each row
print('')
i = i + 1
*
* *
* * *
* * * *
* * * * *
for
loop inside while
loop#
We can also use for loop inside a while
loop as a nested loop. For example,
# Example 1: Method 2
i = 1
# outer while loop
while i < 6:
# nested for loop
for j in range(1, i + 1):
print("*", end=" ")
print('')
i = i + 1
*
* *
* * *
* * * *
* * * * *
# Example 2: Write a code to add all the prime numbers between 17 to 53 using while loop
# 17, 19, 23, 29, 31, 37, 41, 43, 47, 53
'''Method 1'''
n=17
sum=0
while n<=53:
for i in range(2,n):
if(n % i)== 0:
break
else:
i=i+1
else:
sum=sum+n
print(n)
n=n+1
print("The total sum is",sum)
17
19
23
29
31
37
41
43
47
53
The total sum is 340
# Example 3:
print('Show Perfect number fom 1 to 100')
n = 2
while n <= 100: # outer while loop
x_sum = 0
for i in range(1, n): # inner for loop
if n % i == 0:
x_sum += i
if x_sum == n:
print('Perfect number:', n)
n += 1
Show Perfect number fom 1 to 100
Perfect number: 6
Perfect number: 28
Iterate String using while
loop#
By looping through the string using while
loop, we can do lots of string operations. For example,
# Example 1: while loop to iterate string letter by letter
name = "Alan"
i = 0
res = len(name) - 1
while i <= res:
print(name[i])
i = i + 1
A
l
a
n
Iterate List using while
loop#
Python list is an ordered collection of items of different data types. It means Lists are ordered by index numbers starting from 0 to the total items-1. List items are enclosed in square []
brackets.
Below are the few examples of Python list.
>>> numers = [1,2,4,6,7]
>>> players = ["Messi", "Ronaldo", "Neymar"]
Using a loop, we can perform various operations on the list. There are ways to iterate through elements in it. Here are some examples to help you understand better.
# Example 1: Use while loop to iterate over a list.
numbers = [1, 2, 3, 6, 9]
size = len(numbers)
i = 0
while i < size:
print(numbers[i])
i = i + 1
1
2
3
6
9
# Example 2: printing the first two elements of a list
list = [60, "HelloWorld", 90.96] # list with three elements
i = 0
while(i < 2):
print (list[i]) #printing the element in the index i
i = i + 1
60
HelloWorld
Note: When working with the
while
loop, it is important to declare the indexing variablei
beforehand and to increment the indexing variable accordingly. Else it will result in an infinite loop.
Iterate Numbers using while
loop#
Now, consider a program where you want to print out the squares of all the numbers less a particular number. Let’s see how this works with a while statement.
# Example 1: printing the square of numbers less than `n`
i = 1
while (i <= 10):
print (i ** 2) #printing the element in the index i
i = i + 1
1
4
9
16
25
36
49
64
81
100
# Example 2: Find the cube of number from 1 to 9.
i = 1
while(i<10):
print(i*i*i)
# print(i**3)
i=i+1
1
8
27
64
125
216
343
512
729
# Example 3:
i = 1
while i < 3:
print(i ** 2)
i = i+1
print('Loop over')
1
4
Loop over
While loop in Python FAQs#
A while loop in python is used for what type of iteration?
A while loop is ideal for iteration when the number of iterations is not known. Also, it is ideal to use a while loop when you have a condition that needs to be satisfied.
Why does infinite while loop occur in Python?
A loop becomes an infinite loop if the while condition never becomes FALSE. Such a loop that never terminates is called an infinite loop.
Is there a do…while loop in Python?
No. There is no do while loop in Python.
How do you break a while loop in Python?
Usually, the control shifts out of the while loop when the while condition is no False. Or you can use various control statements like break, continue, etc to break out of the while loop or break of the particular iteration of the while loop.
How to write an empty while function in Python?
You can write an empty while function in Python using the pass statements. Here is how you can write it.
#empty while statement in python
>>> i = 0
>>> while (i < 10) :
>>> pass