Python for 循环语句
来源:互联网 发布:儿童编程软件 编辑:程序博客网 时间:2024/04/19 18:09
原文地址:http://www.w3cschool.cc/python/python-for-loop.html
Python for 循环语句
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
语法:
for循环的语法格式如下:
for iterating_var in sequence: statements(s)
流程图:
实例:
#!/usr/bin/pythonfor letter in 'Python': # First Example print 'Current Letter :', letterfruits = ['banana', 'apple', 'mango']for fruit in fruits: # Second Example print 'Current fruit :', fruitprint "Good bye!"
以上实例输出结果:
Current Letter : PCurrent Letter : yCurrent Letter : tCurrent Letter : hCurrent Letter : oCurrent Letter : nCurrent fruit : bananaCurrent fruit : appleCurrent fruit : mangoGood bye!
通过序列索引迭代
另外一种执行循环的遍历方式是通过索引,如下实例:
#!/usr/bin/pythonfruits = ['banana', 'apple', 'mango']for index in range(len(fruits)): print 'Current fruit :', fruits[index]print "Good bye!"
以上实例输出结果:
Current fruit : bananaCurrent fruit : appleCurrent fruit : mangoGood bye!
以上实例我们使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。
循环使用 else 语句
在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。
如下实例:
#!/usr/bin/pythonfor 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 * 511 is a prime number12 equals 2 * 613 is a prime number14 equals 2 * 715 equals 3 * 516 equals 2 * 817 is a prime number18 equals 2 * 919 is a prime number
0 0
- Python for 循环语句
- Python--for 循环语句
- Python for 循环语句
- Python for 循环语句
- Python for 循环语句
- Python for 循环语句使用
- Python菜鸟--for 循环语句
- 关于Python中的for循环控制语句
- 关于Python中的for循环控制语句
- python循环控制语句(for)
- 关于Python中的for循环控制语句
- python for循环语句怎么写
- Python循环语句for和while
- 关于Python中的for循环控制语句
- 关于Python中的for循环控制语句
- python 学习(六) for 循环语句
- Python学习 for循环语句的使用
- python for和while循环语句实例教程
- wijmo制作复合图表
- VC使用驱动打印的一个例子
- Android Camera 实时滤镜(八)
- 欢迎使用CSDN-markdown编辑器
- gitlab安装-设置1-修改仓库(repositories)的位置
- Python for 循环语句
- VC查看某IP是否可以ping通
- 8个不可不知的Mac OS X专用命令行工具
- grep,egrep和fgrep的区别
- SIP代理服务器(一)
- httpclient 文件下载
- Photoshop 画空心圆
- NSString属性什么时候用copy,什么时候用strong?
- 关于不同版本JDK启动eclipse失败的解决方法