引入
1.什么是for循环
循环就是重复做某件事,for循环是python提供的第二种循环机制
2.为何要有循环
理论上for循环能做的事情,while循环都能实现
之所以有for循环,是因为for循环在循环取值时比while循环更简洁
3.如何用for循环
for 变量名 in 可迭代对象 # 可迭代对象可以是:字符串、列表、元组、字典、集合
代码块
...
一、for循环的基本使用
案例1:列表循环取值 for、while循环实现
list1 = ['czp', 'xs', 'wq']
for i in list1:
print(i)
n = 0
while n < 3:
print(list1[n])
n += 1
案例2:字典循环取值 while循环遍历字典较为麻烦
dic1 = {
'name': 'czp',
'age': 24,
'gender': 'man'
}
for x in dic1:
print(x) # 字典的key
print(dic1[x]) # 字典的value
案例3&#