1)if-else
num1 = 45
num2 = 36
if num1==num2:
print('两个数值是相等的。')
else:
print('两个数值不相等。')
两个数值不相等。
2)if-elif-else
num3 = int(input('请输入你的年龄:
'))
if num3 >=30:
print('{}岁属于中年人'.format(num3))
elif num3>=18:
print('{}岁属于成年人'.format(num3))
else:
print('{}岁属于未成年人'.format(num3))
请输入你的年龄:
16
16岁属于未成年人
2.循环语句
1)while循环 while是条件控制循环,当他的表达式为True时,就进行循环,知道表达式判断为False时停止
aa = 0
y = 1
while y<=10:
aa = aa + y
y = y + 1
print(aa)
55
2)for循环
for x in range(1,8):
print(x*x)
1
4
9
16
25
36
49
for i in range(1,8,3): print(i+i)
2 8 14
liebiao = ['zz',3,2,5,4,1,11] for i in range(len(liebiao)): print(liebiao[i])
zz 3 2 5 4 1 11
3)列表生成式 列表生成式可以用来创建list,而且代码写法相对简洁很多
[x*x for x in range(1,8)]
[1, 4, 9, 16, 25, 36, 49]
[x*x for x in range(1,8) if x%2==0]
[4, 16, 36]
带if-else判断的列表生成式 语句1 if 条件 else 语句2 for x in range()
[x+2 if x%2==0 else x*x for x in range(1,8)]
[1, 4, 9, 6, 25, 8, 49]
ss = [11,32,21,24,65,32] [x+1 if x%2==0 else x+100 for x in ss]
[111, 33, 121, 25, 165, 33]
4)循环控制
break:代码执行到break时,循环结束
continnue:代码执行到continue时,跳过本次循环,不影响下次循环
break
for x in range(4): if x==2: break print(x)
0 1 2 3
y = 0 while y<=5: if y==3: break print(y) y = y + 1
0 1 2
continue
for x in range(4): if x==2: continue print(x)
0 1 3
y = 0 while y<=5: if y==3: continue print(y) y = y + 1
0 1 2
dd = ['a','sd','11','cad','ppt','excel','word','sdt'] for i in range(len(dd)): if i==3: break print(dd[i])
a sd 11
rr = [0,13,11,6,23,9,4] for i in range(len(rr)): if i==5: break print(rr[i])
0 13 11 6 23
uu = ['gg','zz','航天','数量级','jahd','2333','666'] vv = input('输入:') for x in range(len(uu)): if vv in uu: print('AMD yes') break else: print(uu[x:5])
输入:gg AMD yes