python中的流程控制语句,有一类是循环结构的语句,它们包括for语句、while语句。
下面我们分别进行介绍,学习下for与while语句的用法。
1. 概念
当条件满足时, 使某段代码重复执行多次
2. 语法
2.1 遍历序列
for iterating_var in sequence :
statement(s)
2.2 指定循环次数
- range([start,] end [,step]) 快速生成List
for iterating_var in range(0, max_time) :
statement(s)
2.3 注意
iterating_var 是局部变量, 只在for循环内有效
3. 举例
---------------2.1---------------------
for char in "abc" :
print char, "- I'm Mr String"
for num in [1,2,3] :
print num, "--- I'm Mr List"
for key in {1:"x", 2:"y"} :
print key, "------ I'm Mr Dict"
---------------2.2---------------------
sum = 0
for num in range(1, 101) :
sum += num
print "1+2+3+...+99+100 = ", sum
---------------------------------------
count = 1
sum = 0
for x in range(100) :
sum += count
count += 1
print "sum = ", sum
4. 遍历 sequence
4.1 value
for iterating_var in sequence :
print iterating_var
4.2 index
5. 遍历 dict
5.1 for
5.1.1 取key - dictName | dictName.keys()
myDict = {1:'a', 2:'b', 3:'c'}
for key in myDict :
print key, "=", myDict[key]
for key in myDict.keys() :
print key, "=", myDict[key]
5.1.2 取value - dictName.values()
5.1.3 取键值对- dictName.items()
6. 循环控制
6.1 for 的 else子句
6.1.1 语法
for ...
...
else:
...
6.1.2 说明
for循环正常执行完毕后, else子句才会执行
6.1.3 举例
for x in [1,2] :
print x
else:
print "for sentence is running over!!"
---output---
1
2
for sentence is running over!!
6.2 break - 终止循环
for x in [1,2] :
print x
if 2 == x :
print "break for sentence"
break;
else:
print "for sentence is running over!!"
---output---
1
2
break for sentence
6.3 continue - 终止当次循环
for x in [1,2,3] :
if 2 == x :
continue
print x
else :
print "for sentence running over!!"
---output---
1
3
for sentence running over!!
6.4 pass - 代码桩, 占位的作用
6.5 exit()
for x in range(5) :
print x
if 3 == x :
exit()
else :
print "for is over!!"
print "#" * 10
---output---
0
1
2
3
7. while
7.1 语法
while expression :
statement(s)
[else:
statement(s)
]
7.2 举例