Python成绩等级判定:if语句和字典模拟switch语句实现

本文将详细介绍如何使用Python编写程序,根据键盘输入的百分制成绩,输出对应的成绩等级。我们将使用两种方法实现:

  1. if语句
  2. 字典模拟switch语句

1. 使用if语句编写程序

score = int(input('请输入成绩:'))

if score >= 90 and score <= 100:
    print('成绩等级为A')
elif score >= 80 and score <= 89:
    print('成绩等级为B')
elif score >= 70 and score <= 79:
    print('成绩等级为C')
elif score >= 60 and score <= 69:
    print('成绩等级为D')
elif score >= 0 and score <= 59:
    print('成绩等级为E')
else:
    print('输入的成绩不在0到100之间')

2. 使用字典模拟switch语句编写程序

(注意:Python中没有内置的switch语句,可以使用字典来实现相似的功能。)

score = int(input('请输入成绩:'))

grade_dict = {
    9: 'A',
    8: 'B',
    7: 'C',
    6: 'D'
}

if score >= 90 and score <= 100:
    print('成绩等级为A')
elif score >= 80 and score <= 89:
    print('成绩等级为B')
elif score >= 70 and score <= 79:
    print('成绩等级为C')
elif score >= 60 and score <= 69:
    print('成绩等级为D')
elif score >= 0 and score <= 59:
    print('成绩等级为E')
else:
    print('输入的成绩不在0到100之间')

希望以上代码可以满足您的需求,如果有任何疑问,请随时提出。

Python成绩等级判定:if语句和字典模拟switch语句实现

原文地址: https://www.cveoy.top/t/topic/by4H 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录