Python 分支结构复习
单分支结构
if 条件表达式:%冒号千万不能丢
print() %不用加“;”
注意:无,因为超简单。但还是要注意一个——判断语句if()不能用赋值运算符“=”,而应该使用连等“==”,表示的是a等于5,而不是将5赋值给了a!!!!
双分支结构
if 条件表达式:
print()
else: %要加“:”
print()
注意:可以用三元运算符来简化编程
三元运算符:
num = input("Please input a number:")
print("OK" if int(num<10) else "None")
注意:①num刚开始为str类型,在条件表达式里应该转换为int型
多分支结构
if 条件表达式1:
print()
elif 条件表达式2:
print()
elif 条件表达式3:
print()
...
elif 条件表达式n:
print()
or
if 条件表达式1:
print()
elif 条件表达式2:%elif 相当于else if
print()
elif 条件表达式3:
print()
...
else:
print()
注意:也没什么还注意的,可能是学的太基础
选择结构嵌套
if 条件表达式:
if 条件表达式:
语句块
else:
语句块
else:
if 条件表达式:
语句块
else:
语句块
注意:注意不同层次代码块的缩进就差不多了,以便明确代码之间的递进和从属关系
复习:字符创格式化
score=int(input('please input score of student:'))
grade=""
if score<0 or score>100:
print("False!Please input again!")
else:
if score>=90:
grade="A"
elif score>=80:
grade="B"
elif score>=70:
grade="C"
elif score>=60:
grade="D"
else:
grade="E"
print('score is {0},grade is {1}'.format(score,grade)) #字符串格式化
'''