Home  >  Article  >  Backend Development  >  解析Python中while true的使用

解析Python中while true的使用

WBOY
WBOYOriginal
2016-06-06 11:14:183386browse

无限循环
如果条件判断语句永远为 true,循环将会无限的执行下去,如下实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

var = 1
while var == 1 : # 该条件永远为true,循环将无限执行下去
  num = raw_input("Enter a number :")
  print "You entered: ", num

print "Good bye!"


以上实例输出结果:

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

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

python while 1 vs while True
Python 3.0之前,他们的执行是不同的:
while 1,python会进行优化,每次循环是不会去检查1的条件,因此性能会好
而while True,在python 3k前,True不是保留字,用户可以True=0,所以,每次还要比较True的值

Python 3.0之后,True/False都变成了保留字,

>>> True = 10


会报错
因此,python 3后,while 1和while True效果一样,都会被解释器优化

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn