主要内容:
小目标:掌握for语句 主要内容:for, break, continue,while与if使用1.for语句
基本语法:for item in iters: 代码1
for语句主要用于在迭代对象中取数据,直到取完。 基本理解:
1:每次从iters中取一个对象, 2:将取出对象赋值给item, 3:执行代码1 4:继续重复1,直到items中值取完。
来看一个例子:
for item in range(10): print(item, end=",")
输出结果:0,1,2,3,4,5,6,7,8,9,
问题:for遍历时候,怎么知道结束了?遍历结束,会触发异常, for语句处理异常,然后结束
2.while小练习
输出0,20之间偶数for num in range(20): if num%2: continue print(num, end=',')
结果:0,2,4,6,8,10,12,14,16,18,
3 for语句与break,continue
for 语句可以和break,continue,配合使用,具体可以产看while语句内容。
注意点:
break,continue必须与while,for配合使用,否则会有语法问题; for中的代码段,注意缩进4:enumerate函数
enumerate:处理可迭代对象,生成:(0,seq[0]),(1,seq[1])...迭代对象
获取索引与值
s = 'this is test' for item in enumerate(s): print(item,end=',')
输出结果:(0, 't'),(1, 'h'),...(11, 't'),
修改:分别使用变量获取索引与值
s = 'this is test' for index,value in enumerate(s): print(index,value,end='|')
结果:0 t|1 h|2 i|3 s|4 |5 i|6 s|7 |8 t|9 e|10 s|11 t|
分析:for遍历enumerate对象,获取一个元组(两个值组成的对象) 赋值方式:index,value = (v1,v2) 结果:index为索引,value为索引对应的值
查看更多关于21天学习python编程_for语句的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did170438