详解Python中for循环的使用方法

yipeiwu_com6年前Python基础

 for循环在Python中有遍历所有序列的项目,如列表或一个字符串。
语法:

for循环语法如下:

for iterating_var in sequence:
  statements(s)

如果一个序列包含一个表达式列表,计算第一个。然后,在序列中的第一项被分配给迭代变量iterating_var。接着,语句块被执行。列表中的每个项目分配给iterating_var,并且statement块被执行,直到整个序列完成(到尾部)。
流程图:

2015514114025864.jpg (388×351)

 例子:

#!/usr/bin/python

for letter in 'Python':   # First Example
  print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']
for fruit in fruits:    # Second Example
  print 'Current fruit :', fruit

print "Good bye!"

当执行上面的代码,产生以下结果:

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

通过遍历序列索引:

通过每个项目进行迭代的一种替代方法是:通过索引偏移量序列本身。下面是一个简单的例子:

#!/usr/bin/python

fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
  print 'Current fruit :', fruits[index]

print "Good bye!"

当执行上面的代码,产生以下结果:

Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

在这里,我们采用内置函数len(),它计算元组元素的总数量以及range()内置函数给我们的实际遍历顺序。
循环使用else语句

Python支持与循环语句相关联的else语句。

  •     如果else语句与for循环使用,执行else语句时,循环已经迭代完成列表。
  •     如果在else语句使用while循环,当条件为假时,else语句被执行。

下面的例子演示了一个else语句,语句搜索素数从10到20的组合。

#!/usr/bin/python

for num in range(10,20): #to iterate between 10 to 20
  for i in range(2,num): #to iterate on the factors of the number
   if num%i == 0:   #to determine the first factor
     j=num/i     #to calculate the second factor
     print '%d equals %d * %d' % (num,i,j)
     break #to move to the next number, the #first FOR
  else:         # else part of the loop
   print num, 'is a prime number'

当执行上面的代码,产生以下结果:

10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number

相关文章

python实现读取excel写入mysql的小工具详解

Python是数据分析的强大利器 利用Python做数据分析,第一步就是学习如何读取日常工作中产生各种excel报表并存入数据中,方便后续数据处理。 这里向大家分享python如何读取...

python读取并定位excel数据坐标系详解

python读取并定位excel数据坐标系详解

测试数据:坐标数据:testExcelData.xlsx 使用python读取excel文件需要安装xlrd库: xlrd下载后的压缩文件:xlrd-1.2.0.tar.gz 解压后再...

Python 运行.py文件和交互式运行代码的区别详解

Python 运行.py文件和交互式运行代码的区别详解

代码版本:3.6.3 1. 交互式运行代码会直接给出表达式的结果,运行代码文件必须print才能在控制台看到结果。 直接给出结果:   没有print是看不到结果的: 有p...

python表格存取的方法

本文实例为大家分享了python表格存取的具体代码,供大家参考,具体内容如下 xlwt/xlrd库 存Excel文件:(如果存储数据中有字符,那么写法还有点小小的变化) impor...

Python cookbook(数据结构与算法)实现查找两个字典相同点的方法

Python cookbook(数据结构与算法)实现查找两个字典相同点的方法

本文实例讲述了Python实现查找两个字典相同点的方法。分享给大家供大家参考,具体如下: 问题:寻找两个字典中间相同的地方(相同的键、相同的值等) 解决方案:通过keys()或者item...