Home python How to create an infinite loop in an infinite loop in Python

# How to create an infinite loop in an infinite loop in Python

Author

Date

Category

I can’t create an infinite loop in the same loop. There are no errors, but the program just skips some of the code starting from the second while.

``````while True:
user_input = input(": ")
while True:
numb1 = float(input("Enter : "))
numb2 = float(input("Enter : "))
print(str(numb1), str(numb2))
``````

``````>>> while True:
...     user_input = input(": ")
...         while True:
...             numb1 = float(input("Enter : "))
...             numb2 = float(input("Enter : "))
...             print(str(numb1), str(numb2))
...
Enter : 10
Enter : 5
10.0 5.0
Enter : 15
Enter : 3
15.0 3.0
Enter : 123
Enter : 10
123.0 10.0
Enter :
``````

The program exactly follows the logic that you put into it, if you correct the incorrectly composed condition.
What comes after the cycle is not skipped – the queue simply does not reach it. If you need any other code to be executed after the loop, it makes sense to exit the loop:

``````>>> while True:
...     user_input = input(": ")
...         while True:
...             numb1 = float(input("Enter : "))
...             numb2 = float(input("Enter : "))
...             print(str(numb1), str(numb2))
...             if numb1 == numb2: # the condition under which the loop ends. I used the condition of equality of two numbers, you may have it different
...                 break
...         print('***** The endless loop is over, the code is executed further')
...
Enter : 3
Enter : 2
3.0 2.0
Enter : 3
Enter : 5
3.0 5.0
Enter : 5
Enter : 5
5.0 5.0
***** The endless loop is over, the code is executed further
:
``````

Regarding the error in your code:

``````user_input = input()
print('This condition is always met!')
``````

You can check it yourself. The fact is that, taking into account the priorities of operations, the condition looks like this:

``````if (user_input == "Add") or ("Add"):
pass # do something
``````

Boolean expression `user_input == "Add"`can take either a true value or a false one, but the boolean value of the line `"Add"`is always true, because any non-empty string has a true boolean representation. If you want to use exactly this approach to the solution, and not by converting to lower case, the condition should be of the form:

``````if user_input in ("Add", "Add"):
pass # do something
``````

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.