if语句
单一结构
age=32 if age<=6: print("童年") else: print("非童年")
复合结构
if age<=6: print("童年") elif age<=18: print("少年") elif age<=41: print("青年") elif age<=66: print("中年") else: print("老年")
元素是否在集合中
v=10 a=[1,2,3,4,5,6,7] if v in a: print("在") else: print("不在")
循环语句
for循环
alist = (1,2,3,4,5) for item in alist: print(item)
blist = [1,2,3,4,5,6] for item in blist: print(item)
while循环
print("=========================") clist = [6,7,8,9,10] i=0 while i<len(clist): print(clist[i]) i=i+1
嵌套循环
print("=========================") dlist = [[1,2,3],[4,5,6],[7,8,9]] n=0 for lst in dlist: for item in lst: n=n+item print("累加结果:",n)
break语句
结束循环
continue语句
跳出本次循环
列表推导式
通过列表推导式生成一个集合
[i for i in range(1,51) if i%2==0] [表达式 for表达式 for表达式或if表达式] 输出结果: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]