Python While loop
The Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as a pre-tested loop.
It can be viewed as a repeating if statement. When we don't know the number of iterations then the while loop is most effective to use.
The syntax is given below.
Here, the statements can be a single statement or a group of statements. The expression should be any valid Python expression resulting in true or false. The true is any non-zero value and false is 0.
While loop Flowchart
Example-1: Program to print 1 to 10 using while loop
1 2 3 4 5 6 7 8 9 10
Example -2: Program to print table of given numbers.
Enter the number:10 10 X 1 = 10 10 X 2 = 20 10 X 3 = 30 10 X 4 = 40 10 X 5 = 50 10 X 6 = 60 10 X 7 = 70 10 X 8 = 80 10 X 9 = 90 10 X 10 = 100
Infinite while loop
If the condition is given in the while loop never becomes false, then the while loop will never terminate, and it turns into the infinite while loop.
Any non-zero value in the while loop indicates an always-true condition, whereas zero indicates the always-false condition. This type of approach is useful if we want our program to run continuously in the loop without any disturbance.
Hi! we are inside the infinite while loop Hi! we are inside the infinite while loop
Enter the number:10 Entered value is 10 Enter the number:10 Entered value is 10 Enter the number:10 Entered value is 10 Infinite time
Using else with while loop
Python allows us to use the else statement with the while loop also. The else block is executed when the condition given in the while statement becomes false. Like for loop, if the while loop is broken using break statement, then the else block will not be executed, and the statement present after else block will be executed. The else statement is optional to use with the while loop. Consider the following example.
In the above code, when the break statement encountered, then while loop stopped its execution and skipped the else statement.
Example-3 Program to print Fibonacci numbers to given limit
Enter the terms 10 Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34