I'm working on a GPA calculator in python 2. However, I cannot get the code to work as I want. I was hoping if someone could me out and provide me some direction. When I put in grades I want it to calculate a GPA. Now, it only reads a letter or a symbol, but not both together. I'll put in A+ it'll give me .3 not 4.3. If I put in multiple grades, it'll only read the first grade.
The for part takes all the grades entered, and gives us the average GPA.
Here is the code:
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))
Since this looks like homework, I'm not going to give a solution. But I will give a little bit more info about what is wrong. Hopefully if you understand what is wrong, you will be able to figure out how to do it right.
If your grade is 'A+', then it is a string of 2 characters, the first of which is A and the second is +. Can grade=='A' be true? Once you understand that, it should be clear to you why A+ isn't getting the 4 part of the grade.
As for why it's only giving you the result for the first grade, what does argv[1] become? Is it all of the grades you send it?
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))
I "fixed" the if statements for the grade letters but you're here for the symbols so there.
'''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()
Related
So I'm able to divide the variable I asked earlier (thank you). But I guess I didn't put enough code so here's the whole thing, I'm getting errors all over the place but whatever I change to try to fix it I get the same response. And yes I am new to python and this is due in an hour.
# grade: The student's grade level Ex. 12
# first: 1st six-weeks grade Ex. 98
# second: 2nd six-weeks grade Ex. 78
# third: 3rd six-weeks grade Ex. 89
# num_exemptions: The number of exemptions that the student has already applied for this semester. Ex. 3
# absences: The number of absences that the student has accrued for the semester. Ex. 4
# tardies: The number of tardies that the student has accrued for the semester. Ex. 5
# previously_taken_exemptions: Has the student taken an exemption for the same course in the fall. Ex. True
print('Enter your 1st 6 weeks grade. Ex. 98')
first = input()
print('Enter your 2nd 6 weeks grade. Ex. 78')
second = input()
print('Enter your 3rd 6 weeks grade. Ex. 89')
third = input()
print('Enter the number of exemptions that you have already applied for this semester. Ex. 3')
num_exemptions = input()
print('Enter your grade. Ex. 12')
grade = input()
print('Enter how many absences you have had this semester. Ex. 4')
absences = input()
print('Enter how many times you have been tardy this semester. Ex. 5')
tardies = input()
print('Have you taken and exemption for this course in the fall. Ex. no')
previously_taken_exemptions = input()
real_absences = float(tardies) // 3 + float(absences)
first = int(first)
sum = float(first) + float(second) + float(third)
average = sum/3
if(average >= 81 and average <= 100):
print("Your Grade is an A")
elif(average >= 61 and average <= 80):
print("Your Grade is an B")
elif(average >= 41 and average <= 60):
print("Your Grade is an C")
elif(average >= 0 and average <= 40):
print("Your Grade is an F")
else:
print("You did something wrong, try again")
if float(grade == '11') and float(num_exemptions) <= 2 and float(real_absences) <= 3 and float(previously_taken_exemptions) == 'no' and float(average) >= 84:
print('You are eligable!')
elif float(grade == '12') and float(num_exemptions) <= 4 and float(real_absences) <= 3 and float(previously_taken_exemptions) == 'no' and float(average) >= 84:
print('You are eligable!')
elif float(grade == '9' or '10') and float(num_exemptions) <= 1 and float(real_absences) <= 3 and float(previously_taken_exemptions) == 'no' and float(average) >= 84:
print('You are eligable!')
else:
print('You are not eligable')
**
It's because it's a string, use:
real_absences = float(tardies) // 3 + float(absences)
You can turn your strings into integers using int.
you have to just declare integer.
here is an example
Tardies = int(“15”)
Absences = int(“5”)
real_absences = Tardies // 3 + Absences
Create a program that will calculate a student’s grade in a class that uses a weighted gradebook.
A weighted system uses percentages to determine how much each assignment category is worth. For this project, use the following percentages:
Project Grades = 30% (weight = .30)
Participation Grades = 20% (weight = .20)
Quizzes = 10% (weight = .10)
Exams = 40% (weight = .40)
Grading scale:
A - 90-100
B - 80-89
C - 70-79
D - 60-69
F - Below 60
Note: You will multiply the average for each of the categories by its weight. The final grade is the sum of the calculated weights.
Can't get the code to the allow the user to enter grades in all 4 categories, because it gets stuck on the first category chosen and the loop just goes on and on without stopping asking for a list of scores. I attempted a loop inside a loop, but it only continued on the first one chosen as well. Need multiple grades entered into all 4 categories which is why I need the program to allow the user to enter grades to the other categories not just the one that is chosen first.
print ("Weighted Grade Calculator ")
name = input("Enter the Student's Name ")
number = input("Enter the Student's Number ")
x = input("Enter Assignment type: ")
c = 'y'
#Loop is in case user wants to calculate another students grade
while c=='y' or c=='Y':
if x >= "quiz" or x >= "Quiz":
input_string = input("Enter a list of scores separated by space ")
#Read ints separated by spaces
lst = input_string.split()
print("Calculating sum of element of input list")
#convert strings to ints and convert map to list
lst = list(map(int, lst))
#Find total and avg
total = sum(lst)
avg_1 = total/len(lst)
elif x >= "project" or x >= "Project":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
print("Calculating sum of element of input list")
lst = list(map(int, lst))
total = sum(lst)
avg_2 = total/len(lst)
elif x >= "participation" or x >= "Participation":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
lst = list(map(int, lst))
total = sum(lst)
avg_3 = total/len(lst)
elif x >= "exam" or x >= "Exam":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
print("Calculating sum of element of input list")
lst = list(map(int, lst))
total = sum(lst)
avg_4 = total/len(lst)
else:
print("error, please try again")
#Finds percentage earned from each category
w_quiz = avg_1 * 0.1
w_project = avg_2 * 0.3
w_participation = avg_3 * 0.2
w_exams = avg_4 * 0.4
total = w_project + w_quiz + w_participation + w_exams
if(total >= 90 and total <=100):
grade = 'A'
elif(total >= 80 and total < 90):
grade = 'B'
elif(total >= 70 and total < 80):
grade = 'C'
elif(total >= 60 and total < 70):
grade = 'D'
elif(total >= 0 and total < 60):
grade = 'F'
print ("Student Name: " + str(name))
print ("Student ID: " + str(number))
print ("Total Weighted Score: " + str(total) + "%")
print ("Letter Grade: " + grade)
c = input("Would you like to calculate another grade? (Y or N): ")
Not sure exactly what you are looking for, but this code will take as much input as you give it and at the end will calculate the average of all totals and its respective letter grade:
def calculate_letter(total):
#function calculates letter grade
if(total >= 90 and total <=100):
grade = 'A'
elif(total >= 80 and total < 90):
grade = 'B'
elif(total >= 70 and total < 80):
grade = 'C'
elif(total >= 60 and total < 70):
grade = 'D'
elif(total >= 0 and total < 60):
grade = 'F'
return grade
print ("Weighted Grade Calculator ")
name = input("Enter the Student's Name ")
number = input("Enter the Student's Number ")
totals = [] #initialize list to append scores to
while True:
project = float(input("Enter the percentage for Projects (numbers only): "))
participation = float(input("Enter the percentage for the Participation (numbers only): "))
quizzes = float(input("Enter the percentage for Quizzes (numbers only): "))
exams = float(input("Enter the percentage for the Final Exam (numbers only): "))
w_project = project * 0.3
w_participation = participation * 0.2
w_quiz = quizzes * 0.1
w_exams = exams * 0.4
total = w_project + w_quiz + w_participation + w_exams
grade = calculate_letter(total) #running the function defined above to evaluate letter grade from total
print ("Total Weighted Score: " + str(total) + "%")
print ("Letter Grade: " + grade)
c = input("Would you like to calculate another grade? (Y or N): ").lower()
totals.append(total)
if c == 'y':
#restarts the loop
continue
else:
#exits the loop
break
print(totals)
final_averaged_score = sum(totals) / len(totals) #finding the average of the list
final_grade = calculate_letter(final_averaged_score)
print ("Student Name: " + str(name))
print ("Student ID: " + str(number))
print ("Final Averaged score: " + str(final_averaged_score))
print ("Final letter grade: " + str(final_grade))
I am in need of assistance on a coding question in Python.
I have to calculate a student’s GPA. The program must ask them how many classes they are taking, then ask them to enter the grades for each class and if it is weighted.
The program should then output the averaged GPA including the decimal place, and my main program must call the function.
The question gives a chart for the non-weighted and weighted number scores that correlates with the given letter grade:
gpa chart
Here's what I have so far:
def average (c):
div = c
avg =(1.0*(sum(scores))/div)
#****************MAIN********************
c = input("How many classes are you taking?")
print ("You are taking " + str(c) + " classes.")
x = input("Enter your letter grade.")
w = int(input("Is it weighted? (1 = yes)")
while (c <= 7): #Here it is saying that there is a syntax error because I input a while loop. I don't know why it is saying this.
if (x == A):
if (w == 1):
print ("Your GPA score is 5")
else:
print ("Your GPA score is 4")
elif (x == B):
if (w == 1):
print ("Your GPA score is 4")
else:
print ("Your GPA score is 3")
elif (x == C):
if (w == 1):
print ("Your GPA score is 3")
else:
print ("Your GPA score is 2")
elif (x == D):
if (w == 1):
print ("Your GPA score is 2")
else:
print ("Your GPA score is 1")
elif (x == F):
if ( w == 1):
print ("Your GPA score is 1")
else:
print ("Your GPA score is 0")
scores = []
list.append(x)
average(c)
Any help would be much appreciated! :)
Not sure about what you are asking for, but fixing just after the function definitions might be a good start
Don't
def classes(c):
print ("You are taking " + c + " classes.")
Do
def classes(c):
print ("You are taking " + c + " classes.")
Something like that maybe? I didn't divide anything in classes but I want you to understand the logic:
number_class=None
while number_class==None:# I set-it up number_class=None so it will keep asking the number of classes until you introduce an integer value
try:
number_class=input("How many classes are you taking?")
except:
print "Error, the input should be a number!\n"
total_result=0#your score start from 0
i=0
while i<number_class:# i create a loop to insert the score for each class
grade=raw_input("Enter your letter grade for the %s class." %(str(i+1)))
grade=grade.upper()#convert the grate to upper so you are able to introduce a or A without make too many check
if grade== 'A' or grade== 'B' or grade== 'C' or grade== 'D' or grade== 'F':#if you introduce a correct score we add it to the total sum and we go ahead with next class
i+=1#next iteration
if grade== 'A':
total_result+=4
elif grade== 'B':
total_result+=3
elif grade== 'C':
total_result+=2
elif grade== 'D':
total_result+=1
#elif: grade== 'F':#we can omitt F seeing that it's =0
# total_result+=0
print total_result
else:# if you introduce a wrong input for the grade we ask you again without pass to next iteration
print "Error, the grade should be: A, B, C, D or F!\n"
average="%.2f" % (float(total_result)/float(number_class))#we divided the total score for the number of classes using float to get decimal and converting on 2 decimal places
print "Your GPA is: %s" %(str(average))
Example:
How many classes are you taking?5
Enter your letter grade for the 1 class.A
4
Enter your letter grade for the 2 class.B
7
Enter your letter grade for the 3 class.C
9
Enter your letter grade for the 4 class.A
13
Enter your letter grade for the 5 class.B
16
Your GPA is: 3.20
I'm writing a python program that drops the lowest of four test scores. The program first prompts the user to enter their first four test scores, then the program should drop the lowest test score and take the average of the remaining three test scores. The program should then print the final letter grade. This is what I have so far and I keep receiving an error when dropping the lowest score.
#Enter four test scores as percentages (%)
test1 = int(input("Enter grade 1: 90"))
test2 = int(input("Enter grade 2: 80"))
test3 = int(input("Enter grade 2: 70)")
test4 = int(input("Enter grade 2: 80)")
#Drop lowest test score
print("The average, with the lowest score dropped" )
total =(test1 + test2 + test3)
#Calculate average
def calc_average(total):
return total /3
#Grade scale
def determine_score(grade):
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >=70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
#Calculate final letter grade
print("The final grade is")
main()
I tried to write a program with the things that I understood from you.
Here is the explanation:
Taking four grades from user.
Dropping the lowest one.
Taking average.
Giving a letter grade according to the average.
Here is the code:
test1 = int(input("Enter grade 1: "))
test2 = int(input("Enter grade 2: "))
test3 = int(input("Enter grade 3: "))
test4 = int(input("Enter grade 4: "))
x = min(test1,test2,test3,test4)
total = float(test1 + test2 + test3 + test4 - x)
avg = total / 3
print("Your average is " + str(avg))
def determine_letter(grade):
letter =""
if grade >= 90:
letter = "A"
elif grade >= 80:
letter = "B"
elif grade >= 70:
letter = "C"
elif grade >= 60:
letter = "D"
else:
letter = "F"
print("The final letter grade is " + letter)
determine_letter(avg)
I have been at this for a while, and I am stuck. I have to write a program that asks the user for each score and the average test score. I need the functions calcAverage which accepts five test scores and returns the average of the scores. determineGrade which accepts a score and returns the grade as a string based off the standard grading scale (90-100 is an A, 80-89 is a B, 70-79 is a C, etc). But I also need a function for getValidScore which prompts and reads a single valid test score and once the score is has been input it returns to the calling module. And finally isInValidScore is a function that checks whether a passed test score is in range from 0-100 and returns a Boolean letting me know if it's valid.
Here's what I have:
def main():
test1 = int(input('Enter test grade 1: '))
test2 = int(input('Enter test grade 2: '))
test3 = int(input('Enter test grade 3: '))
test4 = int(input('Enter test grade 4: '))
test5 = int(input('Enter test grade 5: '))
grade = (test1 + test2 + test3 + test4 + test5)
input('press enter to continue')
print(calc_average)
print(determine_grade)
print(getValidScore)
print(isInvalidScore)
return;
def calcAverage():
grade / 5
return averageScore
def determinGrade(score):
if grade >= 90 and grade <= 100:
return 'A'
elif grade >= 80 and grade <= 89:
return 'B'
elif grade >= 70 and grade <= 79:
return 'C'
elif grade >= 60 and grade <= 69:
return 'D'
else:
return 'F'
def getValidScore():
grade = int(input('input score'))isInvalidScore(score)
while isInvalidScore == false:
print('ERROR')
grade = int(input('input correct score'))
return score
def isInvalidScore(score):
status = True
if score < 0 or score > 100:
status = True
else: status = False
return status
main()
So I added returns and when I run the program, I get this:
Enter test grade 1: 99
Enter test grade 2: 88
Enter test grade 3: 77
Enter test grade 4: 66
Enter test grade 5: 55
press enter to continue
function calc_average at 0x02BAD228>
function determine_grade at 0x02BAD270>
function getValidScore at 0x02BAD2B8>
function isInvalidScore at 0x02BAD300>
There are a few things wrong here:
You're printing out the function itself which is represented by the location in memory, not the result of execution. Add parentheses to the ends of your calls to print out the result.
You should be calling getValidScore and return an integer result instead of reading in input without validation (see main).
Some of your functions take parameters, but you aren't passing any (hint: determinGrade, isInvalidScore).
Some of your functions should take parameters (hint: calcAverage).
calcAverage should return a real number with the actual average. (hint: return grade/5)
Your while loop should start with while isInvalidScore(grade), making the call on the previous line unnecessary.
In main, you're calling an undefined function (determine_grade, is it a typo?)
That's all I can see on a quick look of it. Good luck!
The answer from #tdlive aw'sum is actualy really good (I just upvoted it). Read his comments and work with the stuff. I will supply you with a correction implementation.. I hope you study the aspects you dont understand but take away some good parts from it. Best of luck.
isValidScore = lambda n: 0 <= n <= 100
calcAverage = lambda *args: sum(args)/len(args)
determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, (min(60, 99)/10)-5)]
def getValidScore():
while True:
try:
if isValidScore(int(raw_input('Input score: '))):
return score
except ValueError:
pass
print('Score has to be an integer in the range 0 to 100')
if __name__ == "__main__":
scores = []
for _ in range(5):
scores.append(getValidScore())
print('\nThe scores are: ' + str(scores))
print('The average is: ' + str(calcAverage(*scores)))
print('The grade is: ' + determinGrade(calcAverage(*scores)))