首页 > 编程语言 > 详细

解析Python中while true的使用

时间:2016-02-01 00:21:44      阅读:180      评论:0      收藏:0      [点我收藏+]

无限循环
如果条件判断语句永远为 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效果一样,都会被解释器优化

解析Python中while true的使用

原文:http://www.jb51.net/article/73333.htm

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!