for 循环
1、for 循环—for 便利:列表、字典、元祖、字符串/
2、break :退出循环
3、continue :跳过本轮循环,不执行continue之后的代码。直接进入下一轮循环
new_list = ["玖yue", "柠檬", "人生", "leisen", "Bodhi", "饭团"]
# 1、遍历列表的值(成员) for item in new_list: print(f"哈罗,{item}") if item == "人生": continue # 2、遍历列表的下标,通过下标去取值 [0,1,2,3...] for index in range(len(new_list)): # print(index) # 索引 # print(new_list[index]) # 索引对应的值 print("索引为 {} 的值是: {}".format(index,new_list[index]))
4、有一个生成整数列表的方法:range
range([起始整数],结束整数,[步长]) 起始整数默认为0,步长默认为1 左闭右开(取头不取尾)
range(5) => [0,1,2,3,4]
range(1,5) => [1,2,3,4]
range(1,10,2) => [1,3,5,7,9]
5、字典的遍历:key --value
(1)遍历 key
for key in dict.keys()
(2)遍历 key --value
for item in person_info.items(): print(item)
for key,value in person_info.items(): print(key,value)
1 person_info = {"name": "xj", "age":18, "city": "长沙", "girl": ""} 2 for key in person_info.keys(): 3 print(key)
1 print(person_info.items()) #dict_items([('name', 'xj'), ('age', 18), ('city', '长沙'), ('girl', '')])
1 for item in person_info.items(): 2 print(item)
1 for key,value in person_info.items(): 2 print(f"{key}: {value}")