zoukankan      html  css  js  c++  java
  • 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
     
  • 相关阅读:
    电脑开机慢是查看与解决方案
    做男人真难
    强大的数据恢复软件--EasyRecovery专业版
    30招让你从头到脚都健康
    教您如何使用SQL中的SELECT LIKE like语句
    SQL server经典电子书、工具和视频教程汇总
    数据开发-经典
    C# 数据操作工具类
    关于web请求中 获取真实IP
    生成二维码
  • 原文地址:https://www.cnblogs.com/TomBombadil/p/10979677.html
Copyright © 2011-2022 走看看