循环语句:
1、python 里没有 do…while循环
2、while循环: 条件为true时会一直循环体,否则跳出循环
① 简单while循环
a = 1
while a < 10:
a += 1
print a
② 无限while循环
a = 1
while a != 1:
print 'a等于1'
③ while 中使用else循环
a = 1
while a > 1:
print 'a大于1'
else:
print 'a不大于1'
3、for循环: 重复循环体
① 简单for语句
list = [1, 2, 'a', 'aa']
for value in list:
print value
② 通过序列索引迭代
list = [1, 2, 'a', 'aa']
for index in range(len(list)):
print index
print list[index]
③ for循环中使用else
list = [
[1, 3, 5, 7],
[2, 4, 6, 8]
]
for item in list:
for value in item:
if(value % 2 == 0):
print '偶数'
else:
print '奇数'
4、嵌套循环: while循环和for循环可以互相嵌套
① for循环嵌套 while
a = 1
for a in range(1, 20):
a += 1
while a > 10:
print 'a 大于 10'
else:
print 'a 小于 10'
② for循环中嵌套 for循环
list = [
[1, 3, 5, 7],
[2, 4, 6, 8]
]
for item in list:
for value in item:
if(value % 2 == 0):
print '偶数'
else:
print '奇数'
③ while循环中嵌套 for循环
while True:
for value in [1, 2,3]:
print value
④ while循环中嵌套 while循环
while True:
while True:
print 'True'
5、循环的控制语句
① break: 中止循环,跳出整个循环体
for value in 'addsdad':
if value == 's':
break
print value # a d d
② continue:跳过本次循环,进行下一循环
for value in 'addsdad':
if value == 's':
continue
print value # a d d d a d
③ pass: 空语句,不做任何事,为了保持程序结构的完整性
for value in 'addsdad':
if value == 's':
pass
print value # a d d s d a d
6、思维导图式总结(可以直接看这里)