2

这是我拥有的代码,我想知道如何获取整数列表(分数)并调用函数并打印诸如“成绩为 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()
4

1 回答 1

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))
于 2013-03-14T22:14:06.990 回答