Python while Loop
Python while Loop
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
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
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: