• python篇第10天【For 循环语句】


     
    实例
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    for a in 'Henry':
    print "This is ", a
     
    fruits = ['banana','apple','mango']
    for fruit in fruits:
    print 'Fruit is ', fruit
     
    以上实例输出结果:
    当前字母 : 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 也是一样。
     
    #使用内置 enumerate 函数进行遍历
    #for index, item in enumerate(sequence):
    # process(index, item)
    sequence = [12, 34, 34, 23, 45, 76, 89]
     
    for i, j in enumerate(sequence):
    print i,j
     
  • 相关阅读:
    linux脚本mysql服务与keepalived服务高可用脚本
    linux脚本启动服务脚本
    linux脚本数据库备份脚本
    linux脚本清理日志文件脚本
    最大数字
    求阶乘
    素数
    水仙花数
    js基础1
    css常用属性2
  • 原文地址:https://www.cnblogs.com/TomBombadil/p/10979677.html
Copyright © 2020-2023  润新知