如何获取整数列表,使用letter_grade函数并打印“等级为A”。

时间:2013-03-14 22:07:25

标签: python

这是我的代码,我想知道如何获取整数列表(分数)并调用函数并打印一些像'等级是A'等等。

def letter_grade():
score = input('Enter your test score: ')
if score < 60:
    print 'The grade is E'
elif score < 70:
    print 'The grade is D'
elif score < 80:
    print 'The grade is C'
elif score < 90:
    print 'The grade is B'
else:
    print 'The grade is A' 
return score


letter_grade()

1 个答案:

答案 0 :(得分:4)

首先让你的函数取一个参数

def letter_grade(score):    
    if score < 60:
        print 'The grade is E'
    elif score < 70:
        print 'The grade is D'
    elif score < 80:
        print 'The grade is C'
    elif score < 90:
        print 'The grade is B'
    else:
        print 'The grade is A' 
    return score


score = int(raw_input('Enter your test score: '))
letter_grade(score)

由于您使用的是Python2,因此应使用raw_input代替input

将逻辑和打印混合在同一个函数中并不好,所以让我们返回只是等级

def letter_grade(score):    
    if score < 60:
        return 'E'
    elif score < 70:
        return 'D'
    ... and so on



score = int(raw_input('Enter your test score: '))
print "The grade is {}".format(letter_grade(score))

请注意,我们现在使用format将等级插入字符串中。现在获得list分数

list_of_scores = range(50, 100, 5)  # a list of scores [50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
for score in list_of_scores:
    print "The grade is {}".format(letter_grade(score))