在Python中同样有两种循环:for-in
循环和while
循环
for-in 循环
1
2
3
4
5
6
7
8
"""
用for循环实现1~100求和
"""
sum = 0
for x in range(101):
sum += x
print(sum)
其中,range()
函数可以更灵活:
range(101)
可以产生一个0到100的整数序列。range(1, 100)
可以产生一个1到99的整数序列。range(1, 100, 2)
可以产生一个1到99的奇数序列,其中2是步长,即数值序列的增量。
注意: range(n)
产生的是0
至n-1
的序列!
while 循环
1
2
3
4
5
6
7
8
9
10
"""
用while循环实现1~100求和
"""
i = 1
sum = 0
while i <= 100 :
i = i + 1
sum =sum + i
print(sum)
在while
循环中,可以使用break
强制结束循环,以及使用continue
函数直接跳到下一次循环的开始。
循环的嵌套
举个栗子,九九乘法表
1
2
3
4
5
6
7
8
"""
九九乘法表
"""
for i in range(1, 9 + 1):
for j in range(1, i + 1):
print('%d*%d=%d' % (i, j, i * j), end='\t')
print()
关于逗号
,
的作用,可以参考这篇文章,应该是对的
References
Author: Mike Lyou
Link: https://blog.mikelyou.com/2020/01/02/python-learning-04-loop-structure/
Liscense: Copyright Statement: This python learning series are posted only for personal studies and communication. The whole series are not allowed to be reproduced unles otherwise indicated. I do not own copyright of some of the content. If any post accidentally infringes your copyright, it will be removed shortly after being informed. View python-learning-readme for more information.