所以我正在制作一个总计第一学期成绩的课程,第二学期也会这样做。这就是我所拥有的,它非常简单......
a = raw_input('1st Quarter: ')
b = raw_input('2nd Quarter: ')
c = raw_input('Midterm: ')
d = a * 0.4
e = b * 0.4
f = c * 0.2
g = a + b + c
print 'Your semester grade is', g
我想知道是否有一段代码我可以接受变量g
并将其从数字更改为变量,或者在这种情况下它将是一个等级,如A,B, C,D或F.我以为我能做到
if g in [90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
print 'your grade is A'
我会为B-F做更多事情但是这不起作用。我已经调查了一下,找不到它,我找到了什么没有帮助或者不对!
答案 0 :(得分:1)
使用bisect函数查看非常相似的示例here:
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect(breakpoints, score)
return grades[i]
因此,在Python3中,您可以执行以下操作:
import bisect
GRADES = 'FDCBA'
GRADE_THRESHOLDS = (60, 70, 80, 90)
def grade(score):
i = bisect.bisect(GRADE_THRESHOLDS, score)
return GRADES[i]
if __name__ == '__main__':
a = int(input('1st Quarter: '))
b = int(input('2nd Quarter: '))
c = int(input('Midterm: '))
weighted = a * 0.4 + b * 0.4 + c * 0.2
final_grade = grade(weighted)
print('Your semester grade is', final_grade)
当然,您需要使用对您的评分方案有意义的值替换阈值元组。
答案 1 :(得分:1)
以下程序演示了如何在Python中将整数值转换为字母等级:
import math
import sys
def main():
weights = (('1st Quarter', 2), ('2nd Quarter', 2), ('Midterm', 1),
('3rd Quarter', 3), ('4th Quarter', 3), ('Final', 4))
weighted_score = get_weighted_score(weights)
min_grade_scores = dict(A=90, B=80, C=70, D=60, F=0)
grade = pick_grade(weighted_score, min_grade_scores)
print('Your semester grade is', grade)
def get_weighted_score(weights):
total_score = total_weight = 0
for name, weight in weights:
score = get_integer(name + ': ', 0, 100)
total_score += score * weight
total_weight += weight
return round(total_score / total_weight)
def get_integer(prompt, min_value=-math.inf, max_value=math.inf):
while True:
try:
value = input(prompt)
except EOFError:
sys.exit()
else:
if not value:
print('Please provide a value')
continue
try:
number = int(value)
except ValueError:
print('Please provide a number')
else:
if number < min_value:
print('Number may not be lower than', min_value)
continue
if number > max_value:
print('Number may not be higher than', max_value)
continue
return number
def pick_grade(weighted_score, min_grade_scores):
pairs = map(lambda pair: pair[::-1], min_grade_scores.items())
for score, grade in sorted(pairs, reverse=True):
if weighted_score >= score:
return grade
raise ValueError('Valid grade could not be found')
if __name__ == '__main__':
main()
特别是,您需要查看pick_grade
函数以了解算法的工作原理。