循环语句包含:while和for语句
while循环
whil循环的表达式:
while 判断条件: (这里统一四个空格)语句
一定要注意缩进和判断条件后面的冒号!
例如用while计算1-100的和:
1 #!/usr/bin/env python3 2 3 a = 100 4 b = 0 5 counter = 1 6 7 while counter <= a: 8 b = b + counter 9 counter += 1 10 print(b)
运算结果:
1 /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/zk/PycharmProjects/old_boy/day02/循环/while.py 2 5050 3 4 Process finished with exit code 0
for语句
for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
for循环的格式:
1 for <变量> in <序列>: 2 <声明> 3 else: 4 <声明>
在循环中跳出break:
1 #!/usr/bin/env python3 2 3 a = ["C", "C++", "Perl", "Python"] 4 for i in a: 5 if i == ‘C‘: 6 print(‘列表中包含C‘) 7 break #跳出本次循环 8 print(‘干的漂亮~‘) 9 else: 10 print(‘列表中没有C‘) 11 print(‘呵呵‘)
运行结果:
1 /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/zk/PycharmProjects/old_boy/day02/循环/while.py 2 列表中包含C 3 呵呵 4 5 Process finished with exit code 0
range()函数
如果你需要遍历数字列表,可以使用内置函数range()。他会生成数列:
1 >>> for i in range(5): 2 ... print(i) 3 ... 4 0 5 1 6 2 7 3 8 4
也可以指定range区间的值:
1 >>> for i in range(5,9): 2 ... print(i) 3 ... 4 5 5 6 6 7 7 8
也可以用range指定数字开始并指定不同的增量(甚至可以是负数;有时这也叫做步长)
1 >>> for i in range(0,10,3): 2 ... print(i) 3 ... 4 0 5 3 6 6 7 9
也可以结合range()和len()函数遍历一个序列的索引:
1 >>> a = [‘Mary‘, ‘had‘, ‘a‘, ‘little‘, ‘lamb‘] 2 >>> for i in range(len(a)): 3 ... print(i,a[1]) 4 ... 5 0 had 6 1 had 7 2 had 8 3 had 9 4 had 10 >>> for i in range(len(a)): 11 ... print(i,a[i]) 12 ... 13 0 Mary 14 1 had 15 2 a 16 3 little 17 4 lamb
用range()函数创建一个列表:
1 >>> list(range(5)) 2 [0, 1, 2, 3, 4]
brea和continue语句及循环中的else子语句
break语句可以跳出for和while的循环体。如果你从for或while循环中终止,任何对应的循环else块将不执行。
continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
循环语句可以有else子句;它在穷尽列表(以for循环)或条件变为假(以while循环)循环终止时被执行,但循环被break终止时不执行.如下查寻质数的循环例子:
1 for i in range(2,10): 2 for x in range(2,i): 3 if i % x == 0: 4 print(i,‘equals‘,x,‘*‘,i//x) 5 break 6 else: 7 print(i,‘is a prime number‘)
运行结果:
1 /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/zk/PycharmProjects/old_boy/day02/循环/while.py 2 4 equals 2 * 2 3 6 equals 2 * 3 4 8 equals 2 * 4 5 9 equals 3 * 3 6 9 is a prime number 7 8 Process finished with exit code 0
pass语句
pass语句什么都不做。它只在语法上需要一条语句但程序不需要任何操作时使用.例如:
1 >>> while True: 2 ... pass #如果回车还会一直在等待状态 3 ...
enumrate
为可迭代的对象添加序号:
1 li = [‘haha‘,‘hehe‘,‘asd‘,124] 2 for k,v in enumerate(li,1): #1表示从一开始添加序号 3 print(k,v)
运行结果:
1 /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/zk/PycharmProjects/old_boy/day02/循环/while.py 2 1 haha 3 2 hehe 4 3 asd 5 4 124 6 7 Process finished with exit code 0
*在Python3.x中xrange已经没了,range相当于python2.x中的xrange
时间: 2024-10-12 23:12:41