不使用循环
>>> 1 + 2 + 3
6
使用循环
1、for ... in循环:
编辑1.py
# -*- coding: utf-8 -*-
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
D:\Pythoncode>python 1.py
Michael
Bob
Tracy
计算1到10之和:
# -*- coding: utf-8 -*-
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
D:\Pythoncode>python 1.py
55
使用range()和list():
range()函数可以生成一个整数序列,list()函数可以将整数序列转换为list
range(5)表示从0开始小于5的整数
>>> list(range(5))
[0, 1, 2, 3, 4]
range(101)可以生成0-100的整数序列,计算0到100整数的和:
# -*- coding: utf-8 -*-
sum = 0
for x in range(101):
sum = sum + x
print(sum)
D:\Pythoncode>python 1.py
5050
2、使用while循环
# -*- coding: utf-8 -*-
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
在循环内部变量n不断自减,直到变为-1时,不再满足while条件,循环退出
D:\Pythoncode>python 1.py
2500
3、死循环
# -*- coding: utf-8 -*-
sum = 0
n = 1
while n > 0:
sum = sum + n
n = n + 2
print(sum)
如果在使用循环过程中程序陷入了“死循环”,可以利用Ctrl+C退出程序,或者强制结束Python进程
4、练习
# -*- coding: utf-8 -*-
L = ['Bart', 'Lisa', 'Adam']
for name in L:
print('Hello, %s!' % name)
D:\Pythoncode>python 1.py
Hello, Bart!
Hello, Lisa!
Hello, Adam!