我正在使用python 2中的GPA计算器。但是,我无法让代码按照我的意愿工作。我希望有人能帮我,并给我一些方向。当我投入成绩时,我希望它能够计算出GPA。现在,它只读取字母或符号,但不能同时读取。我会输入A +它会给我.3而不是4.3。如果我输入多个等级,它只会读一年级。 for部分获取所有输入的成绩,并给出我们的平均GPA。
以下是代码:
from sys import argv
def gp(grade):
points = 0
if grade == 'A' or grade == 'a':
points += 4.0
if grade == 'B' or grade == 'b':
points += 3.0
if grade == 'C' or grade == 'c':
points += 2.0
if grade =='D' or grade == 'd':
points += 1.0
if grade == 'F' or grade =='f':
points += 0.0
if grade.endswith ('+'):
points = points + 0.3
if grade.endswith ('-'):
points = points - 0.3
for x in grade
return points = sum(points)/len(grade)
if __name__ == '__main__':
grade = argv[1].replace(" ","")
print (("%.1f") % gp(grade))
答案 0 :(得分:1)
由于这看起来像家庭作业,我不打算给出解决方案。但我会提供一些关于错误的信息。希望如果你理解了什么是错的,你将能够弄清楚如何正确地做到这一点。
如果您的成绩是'A +',则它是一个包含2个字符的字符串,第一个字符为A
,第二个字符为+
。 grade=='A'
可以是真的吗?一旦你理解了这一点,就应该清楚为什么A+
没有获得4年级的成绩。
至于为什么它只给你一年级的结果,argv[1]
会变成什么?是你发送的所有成绩吗?
答案 1 :(得分:0)
from sys import argv
def gp(grade):
points = 0
if grade.lower() == 'a':
points += 4.0
if grade.lower() == 'b':
points += 3.0
if grade.lower() == 'c':
points += 2.0
if grade.lower() == 'd':
points += 1.0
if grade.lower() =='f':
points += 0.0
if grade[:0] == "+"
points = points + 0.3
if grade[:0] == "-"
points = points - 0.3
for x in grade
return points = sum(points)/len(grade)
if __name__ == '__main__':
grade = argv[1].replace(" ","")
print (("%.1f") % gp(grade))
我“修复”等级字母的if语句,但你在这里是为了那些符号。
答案 2 :(得分:-2)
'''This is a simple GPA calculator I was able to put together. Hope this help'''
class GpaCalculator():
'''Declare the variables'''
count = 0
hrs = 0
numberofclasses =0
totalhours = 0
totalPoints = 0.0
gpa = 0.0
'''Prompt the user for the number of classes taking'''
numberofclasses = int(input("Enter number of classes "))
'''use for to loop '''
for count in range(count, numberofclasses):
'''This is to keep track of the number of classes (Optional)'''
print("For class # ", count+1)
'''Prompt user for number of number of credit hours per class'''
hrs = int(input("Enter the credit hrs "))
'''Prompt user to enter the letter grade'''
grade = input("Enter the letter grade ")
'''Use if statement to check the grade and increment points and total hours'''
if grade == 'A' or grade == 'a':
totalPoints = totalPoints + (hrs * 4)
totalhours = totalhours + hrs
elif grade == 'B' or grade == 'b':
totalPoints += (hrs * 3.0)
totalhours += hrs
elif grade == 'C' or grade == 'c':
totalPoints += (hrs * 2.0)
totalhours += hrs
elif grade == 'D' or grade == 'd':
totalPoints += (hrs * 1.0)
totalhours += hrs
'''If not A,B, C, D then it must be F. You can write validation to check in other lettes'''
else:
totalPoints += (hrs * 0.0)
totalhours += hrs
'''Calculate GPA based on the total points and total hours'''
gpa = totalPoints / totalhours
print("Your GPA is :", gpa)
def main():
gpa = GpaCalculator()
if __name__ == '__main__':main()