range、break、continue应用
range()左闭右开
range(5):0,1,2,3,4
1、遍历字符串
s = "ahdi" for i in s: print(i) 结果:a h d i
2、遍历字典
①遍历字典的键
dic = {"a":111,"b":222,"c":333} for i in dic: print(i) 结果: a b c
②遍历字典的值
dic = {"a":111,"b":222,"c":333} for i in dic.values(): print(i) 结果: 111 222 333
③遍历字典的键值对
dic = {"a":111,"b":222,"c":333} for i in dic.items(): print(i) 结果: ('a', 111) ('b', 222) ('c', 333)
需求:遍历字典的键值对,使用两个变量分别保存键和值(利用元组的分包知识)
dic = {"a":111,"b":222,"c":333} for k,v in dic.items(): #dic.items()结果为元组形式 print(k) print(v) 结果: a 111 b 222 c 333
3、嵌套循环使用
1、通过for循环打印
for i in range(5): for j in range(i+1): print("*",end="") #end="" 不换行 print() #换行