1、for循環
for循環是一種遍歷循環
for i in XXX:
循環體
案例1:10位同學的成績放在一個列表中,區分成績等級
小於60分:不及格
60-79分:及格
80-100分:優秀
li=[78,32,55,77,88,90,54,24,67,39]
for item in li:
if item<60:
print(“成績{}分,不及格”.format(item))
elif 60<=item<80:
print(“成績{}分,及格”.format(item))
else:
print(“成績{}分,優秀”.format(item))
案例2:分別用while和for循環實現1+2+…+100
用while:
n=1
s=0
while n<=100:
s+=n
n+=1
print(s)
用for:
s=0
for i in range(1,101):
s+=i
print(s)
2、for循環的應用場景——遍歷字符串、列表、字典
遍歷字符串
遍歷列表
遍歷字典 遍歷所有的鍵、遍歷所有的值、遍歷所有的鍵值對
(1)遍歷字符串
s=“fghjklfvghjfghjasdf”
for i in s:
print(i)
(2)遍歷列表
前面已經運用過
(3)遍歷字典
dic={“a”:11,“b”:22,“c”:33}
遍歷字典的鍵
for i in dic:
print(i) 得到結果為:a
b
c
遍歷字典的值
for i in dic.values():
print(i) 得到結果為:11
22
33
遍歷字典的鍵值對
for i in dic.items():
print(i) 得到結果為:(‘a’,11)
(‘b’,22)
(‘c’,33)
3、for循環中的break、continue
例:打印100遍hello python,但在第50遍時跳出循環
for i in range(1,101):
print(“這是第{}遍打印:hello python”.format(i))
if i==50:
break
例:打印100遍hello python,但在第30~50遍時不打印
for i in range(1,101):
if 30<=i<=50:
continue
print(“這是第{}遍打印:hello python”.format(i))
4、for循環中的嵌套使用
需求:
通過for循環打印如下圖案:
*
* *
* * *
* * * *
* * * * *
for i in range(5):
for j in range(i+1):
print(“* ”,end=“”)
print()