Python for 循环语句的使用

作者:jbzj 时间:2023-10-29 14:51:12 

 Python for 循环语句

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

语法:

for循环的语法格式如下:


for iterating_var in sequence:
  statements(s)

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

for letter in 'Python':     # 第一个实例
  print '当前字母 :', letter

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
  print '当前水果 :', fruit

print "Good bye!"

以上实例输出结果:

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!

通过序列索引迭代

另外一种执行循环的遍历方式是通过索引,如下实例:

实例


#!/usr/bin/python
# -*- coding: UTF-8 -*-
fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
  print '当前水果 :', fruits[index]
print "Good bye!"

以上实例输出结果:

当前水果 : banana

当前水果 : apple

当前水果 : mango

Good bye!

以上实例我们使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。

循环使用 else 语句

在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

实例


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

for num in range(10,20):  # 迭代 10 到 20 之间的数字
  for i in range(2,num): # 根据因子迭代
     if num%i == 0:      # 确定第一个因子
        j=num/i          # 计算第二个因子
        print '%d 等于 %d * %d' % (num,i,j)
        break            # 跳出当前循环
  else:                  # 循环的 else 部分
     print num, '是一个质数'

以上实例输出结果:

10 等于 2 * 5

11 是一个质数

12 等于 2 * 6

13 是一个质数

14 等于 2 * 7

15 等于 3 * 5

16 等于 2 * 8

17 是一个质数

18 等于 2 * 9

19 是一个质数

来源:https://www.runoob.com/python/python-for-loop.html

标签:Python,for,循环语句
0
投稿

猜你喜欢

  • python使用rpc框架gRPC的方法

    2021-02-28 06:28:37
  • 巧妙使用python opencv库玩转视频帧率

    2023-02-01 13:54:30
  • Python超细致探究面向对象

    2023-05-28 17:02:56
  • Python程序员开发中常犯的10个错误

    2023-12-14 04:56:32
  • python轻松实现代码编码格式转换

    2023-11-27 05:47:36
  • Python实现将绝对URL替换成相对URL的方法

    2023-08-28 13:40:08
  • 在Win2003 64位下ASP无法连接Access数据库

    2011-03-30 11:22:00
  • TensorFlow 显存使用机制详解

    2022-02-07 11:46:53
  • Pandas 同元素多列去重的实例

    2023-02-09 21:03:32
  • python 使用plt画图,去除图片四周的白边方法

    2022-02-07 19:34:41
  • JavaScript在XHTML中的用法详解

    2024-04-17 10:11:04
  • 详解Python中的测试工具

    2022-07-02 09:10:13
  • 最新整理Python中的type和object的示例详解

    2023-08-10 05:21:44
  • Python运算符之Inplace运算符的使用教程

    2021-09-24 11:32:10
  • MySQL如何通过Navicat实现远程连接

    2024-01-13 23:07:07
  • Python机器学习工具scikit-learn的使用笔记

    2021-08-30 10:28:50
  • Python实现生成随机数据插入mysql数据库的方法

    2024-01-19 09:28:42
  • golang coroutine 的等待与死锁用法

    2024-04-30 10:03:34
  • python编写猜数字小游戏

    2021-01-14 11:18:40
  • python SVD压缩图像的实现代码

    2023-04-18 18:23:30
  • asp之家 网络编程 m.aspxhome.com