SoFunction
Updated on 2024-10-29

What is required for infinite loops in Python

infinite loop

If the conditional statement is always true, the loop will continue indefinitely.

An example is as follows

#!/usr/bin/python
# -*- coding: UTF-8 -*-
var = 1
while var == 1 : # The condition will always be true and the loop will continue indefinitely
 num = raw_input("Enter a number :")
 print "You entered: ", num
print "Good bye!"

The above example outputs the results:

Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number between :Traceback (most recent call last):
 File "", line 5, in <module>
 num = raw_input("Enter a number :")
KeyboardInterrupt
</module>

Note: In the above infinite loop you can use CTRL+C to break the loop.

python while 1 vs while True

Prior to Python 3.0, they were executed differently:

While 1, python will be optimized so that each loop is not checking the 1 condition, so performance will be better

And while True, before python 3k, True was not a reserved word, the user could True=0, so you also had to compare the value of True each time

After Python 3.0, True/False have become reserved words.

>>> True = 10

will report an error

Thus, after python 3, while 1 has the same effect as while True and is optimized by the interpreter

Content additions

Python infinite loops: In a while loop statement, you can loop indefinitely by keeping the judgment condition from reaching False.

Conditional expressions:

# var = 1
# while var == 1: # expression is always True
#   print("var = 1")
# # var = 1
#  ...
# # var = 1

Boolean:

# while True:
# print("Condition is true")
# # The condition is true
#  ... 
# # the condition is true

To this article on the infinite loop in Python what conditions are required to this article, more related to the conditions of the infinite loop in Python please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!