while循环:在任何条件为真的情况下重复执行一个代码块
for循环:可用在为一个集合(序列或其他可迭代对象)的每个元素都执行一个代码块,它必while循环更简洁
words = ["a","b",123,"d"]
for word in words:
print(word)#将列表words中的元素打印出来
numbers = [1,2,3,4,5]
for number in numbers:
print(number)
Output:
a
b
123
d
1
2
3
4
5
Python将迭代某范围的数字打包成一个函数供使用
range()函数
for i in range(10):
print(i)#打印0-9共10个数字,即循环10次
Output:
0
1
2
3
4
5
6
7
8
9
它默认下限为0,需要我们提供上限;同时我们也可以改变下限,中间用逗号隔开
for i in range(10,20):
print(i)#打印10-19共10个数字,即循环10次
Output:
10
11
12
13
14
15
16
17
18
19
关于循环对象的数据类型:
取决于集合中对象本身
for i in range(3):
print(type(i))
Output:
<class 'int'>
<class 'int'>
<class 'int'>
words = ["a","b",1,"asd"]
for word in words:
print(type(word))
Output:
<class 'str'>
<class 'str'>
<class 'int'>
<class 'str'>
关于在for前面加上变量或函数