"""语法: for item in 某个数据类型: 字符串、列表、元组、字典、集合等 代码块 循环次数由元素个数决定""" # s = "hello" # list_1 = [1, 2, 3] # dic_1 = {"age": "18", "name": "star"} # for item in s: # 遍历s里面的元素,然后赋值给item # print(item) # print("&&44") # for i in list_1: # print(i) # for i in dic_1: # 字典返回key # print(i) # for i in dic_1: # 字典返回value # print(dic_1[i]) # for i in dic_1.items(): # .items()返回键值队 # print(i) # # for i in dic_1.keys(): # .keys()返回键 # print(i) # # for i in dic_1.keys(): # .keys()返回键 # print(i) # for k, v in dic_1.items(): # 可以单独取出键值对的值 # print(k, v) # # """例题:利用for循环,完成列表里所有数字相加""" # list_2 = [1, 4, 5, 8, 3] # s = 0 # for i in list_2: # s += i # print("所有值的和是{}".format(s)) """range函数 range(m,n,k),m头,n尾,k步长,步长默认1,取头不取尾 用来生成整数序列,不是随机数 生成的结果不是列表,可以转成列表""" # print(list(range(1, 6, 2))) # print(list(range(4))) # 头默认为0 """例题,打印列表的每个元素值""" # list_3 = [1, 4, 6, 5, 7] # for i in range(5): # print(list_3[i]) """利用for循环和range函数 完成1-100 的整数求和,包含1、100""" # s = 0 # for i in range(1, 101): # s += i # print(s) """嵌套循环 单独打印列表的某个元素""" # L = [["star", "moon", "son"], ["yes", "no", "equal"]] # for i in L: # 每次循环拿到一个子列表 # for s in i: # 每次循环拿到子列表的元素 # print(s) """ 输出直角三角形 * ** *** **** ***** """ for i in range(1, 6): print("*" * i)
来源:https://www.cnblogs.com/come202011/p/12232308.html