while loop:
The while loop is to be used in situations where the number of iterations is unknown at first. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop.
In Python, the while loop executes the statement or group of statements repeatedly while the given condition is True. And when the condition becomes false, the loop ends and moves to the next statement after the loop.
Syntax of Python While Loop
Now, here we discuss the syntax of the Python while loop. The syntax is given below
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.
Easy tips to write a while loop:
Initialize a variable with some value.
Create a condition based on the initialization.
Give a condition to stop the loop.
**Note: while writing a looping statement body must be properly indented. Otherwise, it gives an indentation error which becomes difficult to correct later.
Example
Now we give some examples of while Loop in Python. The examples are given in below -
Program code 1:
Now we give code examples of while loops in Python for printing numbers from 1 to 10. The code is given below -
Congrats🎉, On Learning the Python Nested While loops with example programs.
Happy Learning :)