Python中无限循环需要什么条件
作者:Python 时间:2023-03-28 09:05:14
无限循环
如果条件判断语句永远为 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
</module>
注意:以上的无限循环你可以使用 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 循环语句中,可以通过让判断条件一直达不到 False ,实现无限循环。
条件表达式:
# var = 1
# while var == 1: # 表达式永远为 True
# print("var = 1")
# # var = 1
# ...
# # var = 1
布尔值:
# while True:
# print("条件为真")
# # 条件为真
# ...
# # 条件为真
来源:https://www.py.cn/jishu/jichu/10386.html
标签:Python,无限循环
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
vue3的watch用法以及和vue2中watch的区别
2024-04-30 08:42:37
![](https://img.aspxhome.com/file/2023/6/132996_0s.png)
numpy数组做图片拼接的实现(concatenate、vstack、hstack)
2022-10-23 15:21:21
go语言实现聊天服务器的示例代码
2024-04-26 17:17:39
Python SELENIUM上传文件或图片实现过程
2021-12-22 09:11:53
![](https://img.aspxhome.com/file/2023/6/127636_0s.jpg)
在 Jupyter 中重新导入特定的 Python 文件(场景分析)
2021-01-30 01:16:57
![](https://img.aspxhome.com/file/2023/1/120311_0s.jpg)
使用SQL Server 2008中对象相关性
2008-12-12 06:36:00
卷积神经网络经典模型及其改进点学习汇总
2023-07-22 22:15:19
![](https://img.aspxhome.com/file/2023/0/86590_0s.png)
python io.BytesIO简介及示例代码
2021-04-25 04:52:31
vsCode安装使用教程和插件安装方法
2024-04-30 09:55:49
![](https://img.aspxhome.com/file/2023/7/132237_0s.jpg)
Python实现模拟分割大文件及多线程处理的方法
2021-08-26 10:55:12
XML简易教程之四
2008-09-05 17:19:00
python -v 报错问题的解决方法
2022-04-03 03:07:29
![](https://img.aspxhome.com/file/2023/1/110411_0s.jpg)
python实现高精度求自然常数e过程详解
2023-12-01 05:21:51
![](https://img.aspxhome.com/file/2023/8/109928_0s.png)
python中加背景音乐如何操作
2023-11-09 02:54:51
Django 解决由save方法引发的错误
2022-04-07 06:06:56
使用Protocol Buffers的C语言拓展提速Python程序的示例
2022-12-04 08:46:20
关于Keras模型可视化教程及关键问题的解决
2021-03-19 10:39:07
![](https://img.aspxhome.com/file/2023/1/78771_0s.jpg)
Elasticsearch属性单词常用解析说明
2023-06-12 14:47:36
asp如何制作一个弹出式的调查窗口?
2010-06-29 21:24:00
MySQL5.7.23解压版安装教程图文详解
2024-01-15 18:19:27
![](https://img.aspxhome.com/file/2023/0/110320_0s.jpg)