In coding, loops are designed to execute a specified code block repeatedly. We’ll learn how to construct a while loop in Python, the syntax of a while loop, loop controls like break and continue, and other exercises in this tutorial.
Introduction of Python While Loop
The Python while loop iteration of a code block is executed as long as the given condition, i.e., conditional_expression, is true.
If we don’t know how many times we’ll execute the iteration ahead of time, we can write an indefinite loop.
Syntax of Python While Loop
while conditional_expression:
Code block of while
The given condition, i.e., conditional_expression, is evaluated initially in the Python while loop. Then, if the conditional expression gives a boolean value True, the while loop statements are executed. The conditional expression is verified again when the complete code block is executed. This procedure repeatedly occurs until the conditional expression returns the boolean value False.
- The statements of the Python while loop are dictated by indentation.
- The code block begins when a statement is indented & ends with the very first unindented statement.
- Any non-zero number in Python is interpreted as boolean True. False is interpreted as None and 0.
Python While Loop Example
Here we will sum of squares of the first 15 natural numbers using a while loop.
Code
# Python program example to show the use of while loop
num = 15
# initializing summation and a counter for iteration
summation = 0
c = 1
while c <= num: # specifying the condition of the loop
# begining the code block
summation = c**2 + summation
c = c + 1 # incrementing the counter
# print the final sum
print("The sum of squares is", summation)
Output:
The sum of squares is 1240
Provided that our counter parameter i gives boolean true for the condition, i less than or equal to num, the loop repeatedly executes the code block i number of times.
Next is a crucial point (which is mostly forgotten). We have to increment the counter parameter’s value in the loop’s statements. If we don’t, our while loop will execute itself indefinitely (a never-ending loop).
Finally, we print the result using the print statement.
Exercises of Python While Loop
Prime Numbers and Python While Loop
Using a while loop, we will construct a Python program to verify if the given integer is a prime number or not.
Code
num = [34, 12, 54, 23, 75, 34, 11]
def prime_number(number):
condition = 0
iteration = 2
while iteration <= number / 2:
if number % iteration == 0:
condition = 1
break
iteration = iteration + 1
if condition == 0:
print(f"{number} is a PRIME number")
else:
print(f"{number} is not a PRIME number")
for i in num:
prime_number(i)
Output:
34 is not a PRIME number 12 is not a PRIME number 54 is not a PRIME number 23 is a PRIME number 75 is not a PRIME number 34 is not a PRIME number 11 is a PRIME number
Multiplication Table using While Loop
In this example, we will use the while loop for printing the multiplication table of a given number.
Code
num = 21
counter = 1
# we will use a while loop for iterating 10 times for the multiplication table
print("The Multiplication Table of: ", num)
while counter <= 10: # specifying the condition
ans = num * counter
print (num, 'x', counter, '=', ans)
counter += 1 # expression to increment the counter
Output:
The Multiplication Table of: 21 21 x 1 = 21 21 x 2 = 42 21 x 3 = 63 21 x 4 = 84 21 x 5 = 105 21 x 6 = 126 21 x 7 = 147 21 x 8 = 168 21 x 9 = 189 21 x 10 = 210
Python While Loop with List
We will use a Python while loop to square every number of a list
Code
# Python program to square every number of a list
# initializing a list
list_ = [3, 5, 1, 4, 6]
squares = []
# programing a while loop
while list_: # until list is not empty this expression will give boolean True after that False
squares.append( (list_.pop())**2)
# print the squares
print( squares )
[36, 16, 1, 25, 9]
In the preceding example, we execute a while loop over a given list of integers that will repeatedly run as long as an element in the list is found.
Python While Loop Multiple Conditions
We’ll need to recruit logical operators to combine two or more expressions specifying conditions into a single while loop. This instructs Python on collectively analyzing all of the given expressions of conditions.
We can construct a while loop with multiple conditions in this example. We have given two conditions and a and keyword, meaning until both conditions give boolean True, the loop will execute the statements.
Code
num1 = 17
num2 = -12
while num1 > 5 and num2 < -5 : # multiple conditions in a single while loop
num1 -= 2
num2 += 3
print( (num1, num2) )
Output:
(15, -9) (13, -6) (11, -3)
Let’s look at another example of multiple conditions with an OR operator.
Code
num1 = 17
num2 = -12
while num1 > 5 or num2 < -5 :
num1 -= 2
num2 += 3
print( (num1, num2) )
Output:
(15, -9) (13, -6) (11, -3) (9, 0) (7, 3) (5, 6)
We can also group multiple logical expressions in the while loop, as shown in this example.
Code
num1 = 9
num = 14
maximum_value = 4
counter = 0
while (counter < num1 or counter < num2) and not counter >= maximum_value: # grouping multiple conditions
print(f"Number of iterations: {counter}")
counter += 1
Output:
Number of iterations: 0 Number of iterations: 1 Number of iterations: 2 Number of iterations: 3
Single Statement While Loop
Similar to the if statement syntax, if our while clause consists of one statement, it may be written on the same line as the while keyword.
Here is the syntax and example of a one-line while clause –
# Python program to show how to create a single statement while loop
counter = 1
while counter: print('Python While Loops')
Loop Control Statements
Now we will discuss the loop control statements in detail. We will see an example of each control statement.
Continue Statement
It returns the control of the Python interpreter to the beginning of the loop.
Code
# Python program to show how to use continue loop control
# Initiating the loop
for string in "While Loops":
if string == "o" or string == "i" or string == "e":
continue
print('Current Letter:', string)
Output:
Current Letter: W Current Letter: h Current Letter: l Current Letter: Current Letter: L Current Letter: p Current Letter: s
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
# Python program to show how to use the break statement
# Initiating the loop
for string in "Python Loops":
if string == 'n':
break
print('Current Letter: ', string)
Output:
Current Letter: P Current Letter: y Current Letter: t Current Letter: h Current Letter: o
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and empty control statements.
Code
# Python program to show how to use the pass statement
for a string in "Python Loops":
pass
print( 'Last Letter:', string)
Output:
Last Letter: s