单分支选择结构
if语句:
x=input("input 2 numbers") #x是str类型
a,b = map(int,x.split()) #将str类型转化为int类型
if a> b:
a,b=b,a
print(a,b)
双分支选择结构
value1 if conditions else value2:当条件表达式condition的值与vlaue1等价时,表达式的值为value1,否则表达式的值为value2。
>>> a=5
>>> print(6) if a>3 else print(5)
6
>>> b=6 if a>13 else 9
>>> b
9
>>> import math
>>> x=math.sqrt(9) if a>3 else random.randint(1,100)
>>> x
3.0
>>> x=math.sqrt(9) if a>9 else random.randint(1,100)
>>> x
多分支结构
def func(score):
if score > 100:
return 'wrong score .must <= 100'
elif score >=90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
else:
return 'E'
print(func(120))
print(func(88))
print(func(43))
选择结构的嵌套
def func(score):
degree='DCBAAE'
if score> 100 or score < 0:
return "wrong socre"
else:
index=(score - 60)//10 //取整数
if index >= 0:
return degree[index]
else:
return degree[-1]
print(func(97))
print(func(100))
print(func(45))