for循环
除了while循环以外,for可以完成循环的功能。 在Python中 for循环可以遍历任何序列的项目,如一个列表或者一个字符串等。
for循环的格式
for 临时变量 in 列表或者字符串等可迭代对象:
循环满足条件时执行的代码
for循环的使用
遍历字符串:
for s in "hello":
print(s)
输出结果:
h
e
l
l
o
Copy
打印数字
for i in range(5):
print(i)
Copy
输出结果:
0
1
2
3
4
Copy
练习
使用for循环,计算1~100的和
range
range 可以生成数字供 for 循环遍历,它可以传递三个参数,分别表示 起始、结束和步长。
>>> range(2, 10, 3)
[2, 5, 8]
>>> for x in range(2, 10, 3):
... print(x)
...
2
5
3