1 if-else语句
if 条件:
表达式1
else:
表达式2
说明:若逻辑判断值为TRUE,则执行"表达式1";否则不执行"表达式2"。需要注意的是,if和else单独一行,且行末需要加引号。表达式1和表达式2需要缩进。
采用if-else语句计算变量的绝对值:
x=-2
if x>=0:
print(x)
else:
print(-x)
运行结果:
2
x=5
if x>=0:
print(x)
else:
print(-x)
运行结果:
5
2 if-"elif"-else语句
if 条件1:
表达式1
elif 条件2:
表达式2
elif 条件3:
表达式3
...
elif 条件n:
表达式n
else:
表达式n+1
采用if-"elif"-else语句判断成绩:
score = 87
if score >= 90:
print("优秀")
elif score >= 80 & score < 90:
print("良好")
elif score >= 60 & score < 80:
print("合格")
else:
print("不合格")
运行结果:
良好