0基础教程习题5—输出学生分数的考评等级

输出学生分数考评等级


1、题目要求

 

允许用户从终端输入一个分数,程序输出这个分数所属的考评等级,90到100分是A,60到89是B,60分以下是C


2、程序分析

 

  • 接受用户的输入需要使用raw_input函数
  • raw_input函数得到的结果是字符串,因此要转成int
  • 为了方便调试程序,要写一个while循环,这样可以启动一次程序然后将各个分数段的分数都输入一遍而不用启动多次

3、示例代码

 

示例1

#coding=utf-8
while True:
    score = raw_input('input score:\n')
    if score == 'stop':
        break

    score = int(score)
    if score >= 90:
        grade = 'A'
    elif score >= 60:
        grade = 'B'
    else:
        grade = 'C'

    print '{score} belongs to {grade}'.format(score=score,grade=grade)

 

除了上面的这种写法,还有另外的一种写法,你可以仔细对比这两者的不同

示例2

#coding=utf-8
while True:
    score = raw_input('input score:\n')
    if score == 'stop':
        break

    score = int(score)
    if score >= 90:
        grade = 'A'

    if score >= 60 and score<90:
        grade = 'B'

    if score < 60:
        grade = 'C'

    print '{score} belongs to {grade}'.format(score=score,grade=grade)

4、本篇小结

 

  • 对于逻辑的控制,同样一个题目,每个人会有不同的写法
  • 上面的两个示例,在逻辑上完全等价