Make a Program in Python that calculates the student's GPA? - python

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

Related

How to assign grade from a list in python

I am creating a program that takes users and stores them in list and takes their marks and afterwards it grades them. I've done the user input part and the marks as well along with the average of them but I am struggling to give them grade and print it along with their name so it will be like Name marks Grade. If anyone can help me with this I'll be thankful greatly here is my code
students=[]
for i in range (2):
x=(input("Enter Student Name. \n"))
students.insert(i,x)
i+=1
print(students)
grades = []
for student in students:
grade = eval(input(f"Enter the grade for {student}: "))
grades.append(grade)
result = list(zip(students, grades))
print(result)
average = sum(grades) / len(grades)
print ( "Average is: " + str(average))
total = sum(grades)
# print ("Total is: " + str(total))
print("Highest marks", max(list(zip(grades, students))))
print("Lowest marks", min(list(zip(grades, students))))
## To do assign grades to each according to their marks
I am struggling to give them grade and print it along with their name so it will be like Name marks Grade.
Look at the below - it uses zip and loop
names = ['Jack','Dan']
grades = [67,86]
def _get_grade(grade):
if grade < 50:
return 'C'
elif grade >= 50 and grade <= 75:
return 'B'
else:
return 'A'
for name,grade in zip(names,grades):
print(f'Name: {name} - Grade: {_get_grade(grade)}')

Python Grading Program

So I need to make a program that grades 10 students individually, then displays the average grade for all 10 students.
I think this is how the grading should look, but im not sure how to set up a count on the number of times its graded, or how to set up the average function. Help would be most welcome. I am a horrible coder.
score = int(input("Enter a score between 0 and 100: "))
if score >=89:
print("The grade is an A")
elif score>=79:
print("The grade is a B")
elif score>=69:
print("The grade is a C")
elif score>=59:
print("The grade is a D")
else:
print("The grade is a F")
You can try using a counter variable that goes from 0-9 and use a while loop to check and increment that counter value and after each loop calculates the average and keeps doing this till the last value has been entered
Counter = 0
average = 0
while (Counter <= 10):
score = int(input("Enter a score between 0 and 100: "))
if score >= 89:
print("The grade is an A")
elif score >= 79:
print("The grade is a B")
elif score >= 69:
print("The grade is a C")
elif score >= 59:
print("The grade is a D")
else:
print("The grade is a F")
Counter = Counter + 1
average = (score + average)
average = average/Counter
print("Average of all 10 students:",average)
So right now the code is configured specifically for just 10 loops but you can give the user the power to determine this by suggesting a value to end the loop and the while loop will check for this value and when the loop sees the value it exits the loop and gives a value
Also with each loop there is a counter value that keeps increasing and an average value that holds the sum of the values entered and when the loop exits and average is calculated by dividing the sum by the counters and this gives the results
This should do the trick.
total = 0
for i in range(10):
score = int(input("Enter a score between 0 and 100: "))
if score >= 89:
print("The grade is an A")
elif score >= 79:
print("The grade is a B")
elif score >= 69:
print("The grade is a C")
elif score >= 59:
print("The grade is a D")
else:
print("The grade is a F")
total += score
print("Average of all 10 students:", total/10)
In the for loop you get the score of each student and then add it to the total of all students. When the loop ends you divide it with the total number of students so 10.
total score / total number of students total / 10
You can define a function that finds the average score. Store all the scores in a list and then pass the list as an argument in the function
def avg(scores): #assuming scores is the name of the list
avg = sum(scores)/len(scores)
return "Average score is {}".format(avg)
Or
return f'Average score is {avg}' #for python3
Not sure I understand what you mean by number of times it is graded but I think you can include a while loop and a variable that increases by 1 every time it grades.

Not able fix variables python

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

Python GPA Calculator

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()

Test Average and Grade with two additional functions

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)))

Categories