What conditions are needed for infinite loop in Python

Infinite loop

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

The following example

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

The output of the above example:

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 "test.py", line 5,in<module 
 num =raw_input("Enter a number :")
KeyboardInterrupt
< /module 

Note: You can use CTRL+C to interrupt the infinite loop above.

python while 1 vs while True

Before Python 3.0, their implementation was different:

While 1, python will optimize, and each loop will not check the condition of 1, so the performance will be better

While True, before python 3k, True is not a reserved word, users can True=0, so each time you have to compare the value of True

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

 True =10

Will report an error

Therefore, after python 3, while 1 and while True have the same effect, they will all be optimized by the interpreter

Content supplement

Python infinite loop: In the while loop statement, you can achieve an infinite loop by making the judgment condition never reach False.

Conditional expression:

# var=1
# whilevar==1: #Expression is always True
# print("var = 1")
# # var=1
#  ...
# # var=1

Boolean value:

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

So far, this article on the conditions for infinite loops in Python is introduced. For more information about the conditions of infinite loops in Python, please search ZaLou.Cn

Recommended Posts

What conditions are needed for infinite loop in Python
​What are the numbers in Python?
What are web development frameworks in python
What are the methods for python to connect to mysql
What are the ways to open files in python
What are python class attributes
What is introspection in python
What is object-oriented in python
What is list comprehension in python
What does rc1 mean in python
What does def in python do
There are several keywords in Python
What does np do in python
What are the required parameters of python
What is an anonymous function in Python
What are the advantages of python language
What system is good for self-study python
What is a sequence table in Python
What is the function of adb in python
What does the tab key in python mean