The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don’t know beforehand, the number of times to iterate.

Syntax of while Loop

In while loop, test expression is checked first. The body of the loop is entered only if thetest_expression evaluates to True. After one iteration, the test expression is checked again. This process continues untill the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation. Body starts with indentation and the first unindented line marks the end. Python interprets any non-zero value as True. None and 0are interpreted as False.

Flowchart of while Loop

while Loop in Python programming

Example: Python while Loop

Output

In the above program, we asked the user to enter a number, n. while loop is used to sum from 1 to that number. The condition will be True as long as our counter variable i is less than or equal to n. We need to increase the value of counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never ending loop). Finally the result is displayed.

while loop with else

Same as that of for loop, we can have an optional else block with while loop as well. The elsepart is executed if the condition in the while loop evaluates to False. while loop can be terminated with a break statement. In such case, the else part is ignored. Hence, a while loop’s else part runs if no break occurs and the condition is false.

Here is an example to illustrate this.

Output

Here, we use a counter variable to print the string Inside loop three times. On the forth iteration, the condition in while becomes False. Hence, the else part is executed.

LEAVE A REPLY

Please enter your comment!
Please enter your name here