while loop
While loop statements
A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.
Syntax:
while expression:
statement(s) |
Working of while loop
The instructions inside the while loop can be executed until the condition becomes false.In other words, the body of the loop is executed only if the condition in the while is evaluated to true. If the condition becomes false, then the body will not be executed and the control moves immediately to the next instruction after the while suite.
Ex A sample program on while loop
Program 1: To display the count from number.
Output
Count: 0
Executed Count: 1 Executed Count: 2 Executed Count: 3 Executed Count: 4 Executed Count: 5 Executed Count: 6 Executed |
Explanation:
Here the print and increment statements, is get executed repeatedly until the count reaches less than 9. For each iteration, the current value of the index count is displayed and then increased by 1.
Program 2: To print the squares of all integers from 1 to 10
Output
1
4 9 16 25 |
Program 3: To print the sum of numbers from 1 to 75
Output
Sum of the numbers is: 2850 |
Program 4: To print the string “Sudhakar” in vertical manner.
Output
S
u d h a k a r |
The Infinite Loop
A loop is said to be an infinite loop if a condition never becomes FALSE. This results in a loop that never ends. Such kind of a loop is called an infinite loop.
Program 5: The following code produces infinite loop
Output
Enter a number: 5
The number is: 5 Enter a number:6 The number is: 6 Enter a number:9 The number is: 9 Enter a number:1 The number is: 1 Enter a number:2 The number is: 2 Enter a number:0 The number is: 0 Enter a number: Traceback (most recent call last): File “<pyshell#147>”, line 2, in <module> n=int(input(“Enter a number:”)) File “C:\Users\user\AppData\Local\Programs\Python\Python35\lib\idlelib\PyShell.py”, line 1386, in readline line = self._line_buffer or self.shell.readline() KeyboardInterrupt |
The above example goes in an infinite loop and to break this continuity press CTRL+C and you can exit the program.
While using else
If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
Ex: The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise the else statement gets executed.
Output:
0 < 5
1 < 5 2 < 5 3 < 5 4 < 5 5 = 5 |