In programming there will be some statements or group of statements which we want to execute continuously for more than one time, this is where loops comes in the picture. Looping allow us to continuously execute particular statement or block of statement to more than one time. Looping will check for the condition, and will continuously execute particular statement or block of statement until the condition get false or invalid. Repeated execution of a set of statements is called as iteration. This statements are executed in order except when a jump statements are encountered.
Similar to other programming languages, python also supports infinite loop.
When the condition of any loop never becomes false, then the loop becomes the infinite loop.
The infinite loop means the result in the loop never ends.
We can use this type of loop in client server programming. In client server programming the server needs to run continuously so that client programs can communicate with the server whenever it is required.
In simple words infinite loop is the loop which will never terminates and it will run throughout the program, and execute the code.
In while loop there is a possibility that the condition never turns False .Such type of situations leads to the formation of infinite while loop.In infinite while loop statements are executed continuously as condition is always True.
Example of infinite while loop in python
""" Author : ITVoyagers (itvoyagers.in)
Date :17th August 2020
Description : Program for infinite while loop in python """
z=1
while z==1:
x=input("Enter your name")
print("hello",x)
print("I am infinite loop")
Output
<strong>Output of infinite while loop in python</strong>
Keyboard Interrupt
When we get stuck in to an infinite loop we can use keyboard interrupt to stop that loop.Infinite loop will affect memory, to stop it we have to generate interrupt
Keyboard interrupt is nothing but keyboard shortcut i.e. Ctrl+C.
Whenever we use shurtcut key an exception is raised which interrupts the normal execution of code.
This exception is nothing but KeyboardInterrupt
We can demonstrate the use of keyboard interrupt using above code.
Output of infinite while loop after using keyboard interrupt
<strong>Output of infinite while loop after using Keyboard Interrupt in python</strong>
Single Suite Statements for infinite loop
Just as we write if statement , we can also write while statement with its executable statement in while header if its executable block consist of single line.
Example of one line infinite while loop in python
""" Author : ITVoyagers (itvoyagers.in)
Date :25th August 2020
Description : Program to show use of one line infinite while loop in python """
indicator = 1
while (indicator): print ('Condition is True')
Output
<strong>Output of one line infinite while loop in python</strong>
Note: It is difficult to implement infinite for loop