Parse the use of while true in Python, pythonwhile

Source: Internet
Author: User

Parse the use of while true in Python, pythonwhile

Infinite Loop
If the condition determination statement is always true, the loop will be executed infinitely, as shown in the following example:

#! /Usr/bin/python #-*-coding: UTF-8-*-var = 1 while var = 1: # This condition is always true, the loop will be infinitely executed num = raw_input ("Enter a number:") print "You entered:", numprint "Good bye! "


Output result of the above instance:

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

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

Python while 1 vs while True
Before Python 3.0, their execution was different:
While 1, python will be optimized, and the 1 condition will not be checked for each loop, so the performance will be good
While True: True is not a reserved word before 3 K in python. You can set True to 0. Therefore, you must compare the value of True at a time.

After Python 3.0, True/False are reserved words,

>>> True = 10


An error is reported.
Therefore, after python 3, while 1 and while True have the same effect and will be optimized by the interpreter.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.