1、分支结构
单分支 if…:
二分支 if… : else… : 【还有更加简洁的表达方式: 表达式1 if 条件 else 表达式2】
【任何非零的数值、非空的数据类型都等价于True,0等价于False】
多分支
if … :
elif …:
…
else …:
a = eval(input("输入数字:"))
#单分支
if a%2==1 :
print("该数是一个奇数")
print("end1")
#二分支
if a%2==1 :
print("该数是一个奇数")
else :
print("该数是个偶数")
print("end2")
#多分支
if a>=6 and a<=10 :
print("优秀")
elif a<6 and a>=3 :
print("良好")
else:
print("合格")
print("end3")
输出结果为:
输入数字:5
该数是一个奇数
end1
该数是一个奇数
end2
良好
end3
2、循环结构
a、遍历循环:可以是字符串、文件、range()函数或者组合数据类型
for 循环变量 in 遍历结构 :
语句块
辅助:break 【跳出当前循环】和 continue 【结束当前档次循环】
for i in range(1,5):
print(i,end=' ')
print("end1")
string = "abcdef"
for a in string:
if a=="d" :
break
print(a,end=' ')
print("end2")
for a in string:
if a=="d" :
continue
print(a,end=' ')
print("end3")
输出结果为:
1 2 3 4 end1
a b c end2
a b c e f end3
【扩展模式】
for 循环变量 in 遍历结构:
语句块1
else:
语句块2
【for循环正常执行后,else才会执行】
break时,for循环属于非正常执行,else不执行
string = "abcdef"
for a in string:
if a=="d" :
break
print(a,end=' ')
else:print("end2")
输出结果为:
a b c
continue时,for循环只跳出了符合if条件的那一次循环,正常执行完了,所以else语句执行
for a in string:
if a=="d" :
continue
print(a,end=' ')
else:print("end3")
输出结果为:
a b c e f end3
b、无限循环
while 条件 :
语句块
n = 2
while n<10:
print(n)
n +=2
输出结果为:
2
4
6
8
【扩展模式】——同for中的扩展模式一样
while 条件:
语句块1
else:
语句块2
3、异常处理
try:
语句块1【正常执行的内容】
except:
语句块2【发生异常时执行的内容】
while True:
try:
a = eval(input("输入一个数字:"))
break
except:
print("是输入数字!")
print("该数字为:{}".format(a))
当输入的是一个数字时:
输入一个数字:5
该数字为:5
当输入的不是一个数字时:
输入一个数字:4sd
是输入数字!
输入一个数字: