Python中分支语句只有if语句,这个if语句使得程序具有了“判断能力”,能够像人类的大脑一样分析问题。if语句有if结构、if-else结构和elif结构三种。
if结构
例题:输入分数,计算优秀、中等、差。
if语句结构如下:
if 条件:
语句组
……
代码:
#coding = utf-8
#!/usr/bin/python3
import sys
score = int(sys.argv[1])
if score >= 85:
print("您真优秀")
if score < 60:
print("您需要加倍努力")
if score >= 60:
print("您的成绩还可以,仍要继续努力!")
if-else结构
几乎所有的计算机语言都有这个结构,先判断条件,如果返回值为True,那么执行语句,否则执行else内的语句。
if-else 结构如下:
if 条件:
语句组1
else:
语句组2
elif结构
elif结构就是c++语言中的else if结构,elif实际上是if-else的多重嵌套,不用多说
if-else结构实例
#coding = utf-8
#!/usr/bin/python3
import sys
score = int(sys.argc[1])
if score >= 60:
print("及格")
if score >= 90:
print("优秀")
else:
print("不及格")
elif结构实例
#coding = utf-8
#!/usr/bin/python3
import sys
score = int(sys.argv[1])
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print("Grade = " + grade)