Python基础之条件语句
条件判断是根据不同的判断条件执行不同的代码,在业务逻辑判断时十分常用。python只有if else条件语句,不具备其他编程语言的switch条件语句。
用于流程控制执行,基本表达式如下:
if 判断条件:
执行语句……
elif:
执行语句……
else:
执行语句……
a = 10
b = 20
if a > b:
print("a大于b")
elif a==b:
print("a等于b")
else:
print("a小于b")
a小于b
示例1:根据车牌判断是否外地车
# 以广州为例,粤A以外的都为外地车
no_str = '粤B 12345'
if no_str[0:2] == "粤A":
print('{0}是本地车'.format(no_str))
else:
print('{0}是外地车'.format(no_str))
粤B 12345是外地车
示例2:根据分数判断学习能力水平
score = 87
if score == 100:
print('{0}分为优秀'.format(score))
elif score >= 90:
print('{0}分为优良'.format(score))
elif score >= 80:
print('{0}分为良好'.format(score))
elif score >= 60:
print('{0}分为及格'.format(score))
else:
print('{0}分为不及格'.format(score))
87分为良好