Dark Mode
Image

Python While Loops

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 = [34125423753411]     

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)  

Comment / Reply From