A Comprehensive Guide to Python While Loops: Syntax, Examples, and Best Practices

Rumman Ansari   Software Engineer   2024-07-26 06:59:28   294  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

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. When the program control reaches the while loop, the condition is checked. If the condition is true, the block of code under it is executed. After that, the condition is checked again. This continues until the condition becomes false. Then the first statement, if any after the loop is executed. Remember to indent all statements under the loop equally.

If we don't know how many times we'll execute the iteration ahead of time, we can write an indefinite loop.

Python While Loop Syntax


 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 Flow chart

A while loop in Python iterates till its condition becomes False. In other words, it executes the block of statements until the condition it takes is true.

Python While Loop Flow chart

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.

The else statement for while loop

A while loop may have an else statement after it. When the condition becomes false, the block under the else statement is executed. However, it doesn’t execute if you break out of the loop or if an exception is raised.

a=3
while(a > 0):
    print(a)
    a-=1
else:
        print("Reached 0")
3
2
1
Reached 0

In the following code, we put a break statement in the body of the while loop for a==1. So, when that happens, the statement in the else block is not executed.

a=3
while(a > 0):
    print(a)
    a-=1
    if(a == 1):
     break
else:
    print("Reached 0")

Output

3
2

Single Statement while

Like an if statement, if we have only one statement in while loop’s body, we can write it all in one line.

a=3
while a>0: print(a); a-=1;

Output

3
2
1

You can see that there were two statements in while loop’s body, but we used semicolons to separate them. Without the second statement, it would form an infinite loop.

MCQ Available

There are 17 MCQs available for this topic.

17 MCQTake Quiz