python - while 和 for 循环有什么区别
问题描述
python中的while和for之间真的有区别吗?或者我可以使用我想要的任何人吗?我的第二个问题:-
persons['alic', 'sam', 'rain']
first_name = 'mike'
for first_name in persons :
#when the program runs for the first time
#what is the value of first_name?
#is it 'mike',or its value is Null??
print(first_name)
谢谢。
解决方案
通常,for in 循环对于在已知集合上进行迭代很有用,并且迭代次数是预先确定的。当退出条件是状态变化而不是预定长度时,通常使用 while 循环。
while 循环的常见用例包括:
运行程序的主循环直到键盘中断:
try:
while True:
break
except KeyboardInterrupt:
print("Press Ctrl-C to terminate while statement")
pass
查找引用列表中的最后一个节点:
while(node is not None):
node = node.next()
提取信息:
while 循环- 用于循环直到满足条件以及不确定代码应该循环多少次
for 循环- 用于循环直到满足条件,但在您知道代码需要循环多少次时使用
do while loop - 在检查 while 条件之前执行一次循环的内容。
推荐阅读
- javascript - 如何在不使用 navigation.navigate() 的情况下在 React Native 中的屏幕之间导航?
- python - Python re 我想拆分所有标点符号,除了 - 符号
- php - Laravel 语言文件分离逻辑
- python - 将不同聚合函数应用于熊猫数据框的不同列的 Pythonic 方式?并有效地命名列?
- python - 以单列为中心,但具有对角线历史客户访问视图
- python - 如何合并多个 CSV 文件?
- firebase - Flutter异步firebase请求未等待
- docker - 如何自动清理 Amazon EKS 工作线程节点中的 Docker 资源?(模仿 docker 系统 prune -a)
- macos - 在 macOS 上的 SwiftUI 列表视图中选择和删除核心数据实体
- sql - 在 Postgress 中分桶