Python入门(2)---if,else,elif语句

二、判断语句

1.if语句

格式:
if 要判断的条件:
条件成立时要做的操作
注意只有在缩进内的代码才算在if条件成立要做的操作里,如果没有缩进,则不算
顶格书写的代码,代表与if没有关系

2.if-else结构

格式:
if 条件:
条件
else:
条件

# 本例演示基本的if语句
# 用户键盘输入对应的年龄
age = input("请输入您的年龄:")
# 判断年龄是否大于18岁
if int(age)>18:
    print("我已经成年了")
else:
    print("我还没成年")
print("if-else语句结束")

3.if elif条件

格式
if 条件1:
执行代码
elif 条件2:
执行代码
……

# 本例演示if-elif语句
# 用户输入成绩
score = input("请输入您的考试成绩:")
# 将score转换为int类型
score = int(score)
# 利用if-elif语句进行判断
if score < 60:
    print("成绩等级为E")
elif (score >= 60) and (score < 70):
    print("成绩等级为D")
elif (score >= 70) and (score < 80):
    print("成绩等级为C")
elif (score >= 80) and (score < 90):
    print("成绩等级为B")
elif (score >= 90) and (score <= 100):
    print("成绩等级为A")
else:
    print("您输入的成绩不合法")
print("代码执行结束")

4.if语句嵌套

# 本例演示if语句的嵌套
age = input("请输入您的年龄:")
age = int(age)
if age > 50:
    if age > 80:
        print("您的年龄大于80")
    elif (age <= 80) and (age > 50):
        print("您的年龄介于50到80岁之间")
elif (age <= 50) and (age > 0):
    if age > 25:
        print("您的年龄介于25-50之间")
    elif (age <= 25) and (age >= 0):
        print("您的年龄介于0到25岁之间")
else:
    print("您输入的年龄不合法")

猜你喜欢

转载自blog.csdn.net/weixin_46841376/article/details/112849094
今日推荐