Wednesday, July 27, 2022

What are infinite loops?

The infinite loops are loops without iteration variable. This variable is updated in each iteration and is responsible for controlling the loop execution. Without this variable loop does not know how many times it needs to execute. So it will execute indefinitely.
Example 1 Create a while loop that will in each iteration print the string "This is infinite while loop." until the user brakes the execution.
Solution:
while True:
print("This is infinite while loop.")
Executing the two lines of code will print out the string "This is infinite while loop." indefinitely or until the user brakes the execution.
This is infinite while loop.
This is infinite while loop.
This is infinite while loop.
This is infinite while loop.
This is infinite while loop.
This is infinite while loop.
This is infinite while loop.
This is infinite while loop.
This is infinite while loop.
This is infinite while loop.
Traceback (most recent call last):
File "< stdin >", line 2, in < module >
KeyboardInterrupt
The output is a previously mentioned string and the process would repeat indefinitely. However, we have terminated the execution in CommandPrompt by typing Ctrl+C which terminated execution i.e. "KeyboardInterrupt". In the following example, we will create a simple while loop that will terminate the execution after the condition of the while loop is not valid anymore.
Example 2 Create the while loop that will print every even number between 50 and 25 and after the loop is terminated it will print out "The program is complete."
Solution: The program will start by creating the varialbe x and assining the value 50 to this variable name.
x = 50
Then we are going to create a while loop with condition that the value of variable x must be greater than 25. In the body of the while loop the number will be printed out and then decreased by 2.
while x > 25:
print("x = {}".format(x))
x = x - 2
After the condition of the while loop is false, the string "Thi program is complete" will be printed out.
print("The program is complete.")
The entire code as well as the output is given below.
x = 50
while x > 25:
print("x = {}".format(x))
x = x - 2
print("The program is complete.")
The output is given below.
x = 50
x = 48
x = 46
x = 44
x = 42
x = 40
x = 38
x = 36
x = 34
x = 32
x = 30
x = 28
x = 26
The program is complete.
As you can see in this case in each iteration the value of variable x was decreased by 2 and the execution was terminated when the x value was equal to 24. In the next iteration, the condition of the while loop was False so the execution of the while loop was terminated.

No comments:

Post a Comment