Site icon TestingDocs.com

Python while Loop

Overview

Let’s learn about Python while loop in this tutorial. We’ll explore its syntax, working, and usage. The while loop iterates a code block while a condition is true. It’s useful when the number of iterations isn’t known in advance.

Syntax

The general syntax of the while loop is as follows:
while loop_expression:
       loop statement(s)
Indentation determines the body of the while loop. The loop body starts with indentation, and the first unindented line marks the end of the loop.
The loop_expression is evaluated. If the loop_expression evaluates to true, then the loop’s body is executed. After one iteration, the test expression is evaluated and tested again for true or false. This process continues until the loop_expression is evaluated to be false.

Example

Python program to display numbers using a while loop.

# Python program to display numbers using while loop
# Python Tutorials - www.TestingDocs.com
count = 1
while count <= 10:      # while loop
    print(count)             # print the count value
    count = count + 1    # increment count variable

Output

1
2
3
4
5
6
7
8
9
10

Note that the loop body will not execute if the loop expression is false on the first iteration. The statement following the while loop will execute.

 

We can see that the count variable is initialized to 1, and the loop condition is set as count <= 10

When the while loop is executed, the condition 1<= 10 evaluates to true. The while loop body executes and prints the value of the count variable as 1. The count variable is incremented by one and becomes count=2. Then, control goes back to the loop expression that is 2 <= 10, which is true, and the while loop is executed again. The loop will continue to execute until the count value becomes 11 and loop expression 11<=10 evaluates to false. This will terminate the while loop, and the control is transferred to the next statement after the loop( if any).

Python Tutorials

Python Tutorial on this website can be found at:

https://www.testingdocs.com/python-tutorials/

More information on Python is available at the official website:

https://www.python.org

Exit mobile version