A GPA, or Grade point Average, is calculated by summing the grade points earned in a student’s courses and then dividing by the total units. The grade points for an individual course are calculated by multiplying the units for that course by the appropriate factor depending upon the grade received:
A receives 4 grade points
B receives 3 grade points
C receives 2 grade points
D receives 1 grade point
F receives 0 grade point
Your program will have a while loop to calculate multiple GPAs and a while loop to collect individual grades (i.e. a nested while loop).
For your demo, calculate the GPA to 2 decimal places for these two course combinations:
First Case: 5 units of A 4 units of B 3 units of C
Second Case: 6 units of A 6 units of B 4 units of C
This is what I have so far....
todo = int(input("How many GPA's would you like to calculate? "))
while True: x in range (1, todo+1)
n = int(input("How many courses will you input? "))
totpoints = 0
totunits = 0
while True: range(1, n+1)
grade = input("Enter grade for course: " )
if grade == 'A':
grade = int(4)
if grade == 'B':
grade = int(3)
if grade == 'C':
grade = int(2)
if grade == 'D':
grade = int(1)
if grade == 'F':
grade = int(0)
units = int(input("How many units was the course? "))
totunits += units
points = grade*units
totpoints += points
GPA = totpoints / totunits
print("GPA is ", ("%.2f" % GPA))
print("total points = ", totpoints)
print("total units = ", totunits)
My question is how do I exactly incorporate the while function correctly? My code is not running correctly.
Thanks in advance.
First thing you must know about Python is that is all about indentation. So make sure you indent your while blocks correctly. The syntax of the while statements is like:
while <condition>:
do_something
The code inside the while block is executed if the condition is true. After executing the code the condition is checked again. If the condition is still true it will execute the block again, and so on and so forth until the condition is false. Once the condition is false it exits the while block and keeps executing the code after.
One last thing, Python does not have case statements like other programming languages do. But you can use a dictionary, so for example I've defined a dictionary to map the grades to points and remove the if statements from your code:
gradeFactor = {'A':4, 'B': 3, 'C':2, 'D':1, 'F':0}
todo = int(raw_input("How many GPA's would you like to calculate? "))
while todo:
n = int(raw_input("How many courses will you input? "))
totpoints = 0
totunits = 0
while n:
grade = raw_input("Enter grade for course: " )
units = int(raw_input("How many units was the course? "))
totunits += units
points = gradeFactor[grade]*units
totpoints += points
n -= 1
GPA = float(totpoints) / totunits
print("GPA is ", ("%.2f" % GPA))
print("total points = ", totpoints)
print("total units = ", totunits)
todo -= 1
Related
I've been struggling with this problem for a while now since loops are a bit confusing to me. Essentially, I think I got some of the more difficult stuff (for me at least) out of the way. The issue is that I need the average of 3 students per exam not 6 students per exam, which is what my current code gives.
If what I am asking isn't clear let me know and I will clear it up.
My inputs are n = 3 and m = 2.
def readGrade():
grade = int(input("Enter the grade: "))
while grade > 100 or grade < 0:
print("Invalid Grade")
grade = int(input("Enter the grade: "))
return grade
def examAverage(m):
average = 0
for i in range(n):
readGrade()
average = average + readGrade()
return (average / n)
n = int(input("Enter the number of students: "))
m = int(input("Enter the number of exams: "))
for i in range(m):
print("The average of exam", i + 1, "is:", examAverage(m))
You are calling readGrade() two times within examAverage()
I think this is what examAverage() should be:
def examAverage(m):
average = 0
for i in range(n):
this_grade = readGrade()
average = average + this_grade
return (average / n)
For a classroom assignment I have been asked to create a program that averages a number of user input exam grades using a while loop. I have come up with a functioning program, however it does not meet the specific criteria required by my instructor.
I need to Use a while-loop to allow the user to enter any number of exam scores, one number per line, until a sentinel value is entered.
How might I alter this program to get the same result using a while loop and a sentinel value of 9999?
here is what I have so far.
scores=int(input("how many test scores will you enter: "))
total_sum=0
for n in range(scores):
numbers=float(input("Enter exam score : "))
total_sum+=numbers
avg=total_sum/scores
print("average of ", scores, " test scores is :", avg)
The output should look something like this
Enter exam score. 9999 to quit: 100
Enter exam score. 9999 to quit: 95.5
Enter exam score. 9999 to quit: 90
Enter exam score. 9999 to quit: 9999
These 3 scores average to : 95.16666667
Think the best way to do it would be store the scores in a list and then compute the average of them after the user enters the sentinel value:
SENTINEL = float(9999)
scores = []
while True:
number = float(input("Enter exam score (9999 to quit): "))
if number == SENTINEL:
break
scores.append(number)
if not scores:
print("You didn't enter any scores.")
else:
avg = sum(scores)/len(scores)
print("average of ", len(scores), " test scores is :", avg)
There are a couple ways to go about this. The general approach would be to keep a running total of the scores, as well as how many scores you've read, and then check whether the next score to read is == 9999 to see whether or not to exit the while loop.
A quick version might be the following:
num_scores = 0
total_sum = 0
shouldExit = False
while shouldExit is False:
nextScore = float(input("Enter exam score : "))
if nextScore == 9999: #find a way to do this that does not involve a == comparison on a floating-point number, if you can
shouldExit = True
if shouldExit is False:
num_scores += 1
total_sum += nextScore
avg = total_sum / num_scores
See how that sort of approach works for you
You can just break out of your for loop after getting input.
for n in range(scores):
c = int(Input('Enter test score, enter 9999 to break'))
if c == 9999:
break;
scores += c
Something like that at least.
I am the given the following problem and asked to write a solution algorithm for it using python.
problem:
Write a Python program to determine the student with the highest average. Each student takes a midterm and a final. The grades should be validated to be between 0 and 100 inclusive. Input each student’s name and grades and calculate the student’s average. Output the name of the student with the best average and their average.
Here is my code:
def midTerm():
midtermScore = int(input("What is the midterm Score: "))
while (midtermScore <= 0 or midtermScore >= 100):
midtermScore = int(input("Please enter a number between 0 and 100: "))
return midtermScore
def final():
finalScore = int(input("What is the final Score: "))
while (finalScore < 0 or finalScore > 100):
finalScore = int(input("Please enter a number between 0 and 100: "))
return finalScore
total = 0
highest = 0
numStudents = int (input("How Many Students are there? "))
while numStudents < 0 or numStudents > 100:
numStudents = int (input("Please enter a number between 0 and 100? "))
for i in range (1, numStudents+1):
students = (input("Enter Student's Name Please: "))
score = (midTerm()+ final())
total += score
avg = total/numStudents
if (highest < avg):
highest = avg
winner = students
print ("The Student with the higgest average is: ", winner, "With the highest average of: ", avg)
The issue I am running into is the last part. The program does not print the name of the person with the highest average, but the name of the person that was entered at the very last. I am very confused on how to go forward from here. Can you please help? Thanks in advance for any help.
You're not far off. Take a look here:
for i in range (1, numStudents+1):
students = (input("Enter Student's Name Please: "))
score = (midTerm()+ final())
total += score
avg = total/numStudents
if (highest < avg):
highest = avg
winner = students
Besides the indentation error (hopefully just clumsy copy-pasting) You're not actually calculating each student's average score anywhere. Try something like this:
for i in range (numStudents):
student_name = (input("Enter Student's Name Please: "))
student_avg = (midTerm() + final()) / 2 # 2 scores, summed and divided by 2 is their average score
if (highest < student_avg):
highest = student_avg
winner = student_name # save student name for later
print ("The Student with the higgest average is: ", winner, "With the highest average of: ", highest)
It looks like you were originally trying to calculate the total class average, which is not what's described by the problem statement. Hope this helps!
For my computer science class I have to make a program that will calculate grades.
This is my first computer science class (no prior experience) so I am struggling through it.
These are the directions:
Ask the user for the number of tests, assignments, quizzes, and labs in their course.
Ask the user if there is a final with a separate weight from the tests above, e.g. a course has 2 tests, each weighing 12.5%, and 1 final weighing 15%.
For each category having a number > 0
a. Prompt the user for the weighted percent, out of 100%, which should total
100% for all categories!!!
b. Get the score(s) for the category.
c. If the category is labs, then sum all the scores.
d. Else, average the scores.
e. Calculate the weighted average for the category.
Using the weighted average of each category, calculate the grade in the course.
Ask the user if he/she wants to calculate a grade for another class.
If the user responds yes, then go back to step 1.
Else, end the program.
My code so far:
def main():
lists = get_user_input()
get_scores(lists);
get_weighted_average(lists)
def get_user_input():
# How many?
t = int(input("How many tests?: "))
a = int(input("How many assignments?: "))
q = int(input("How many quizzes?: "))
l = int(input("How many labs?: "))
# How much weight on grade?
tw = float(input("Enter weight of tests: "))
aw = float(input("Enter weight of assignments: "))
qw = float(input("Enter weight of quizzes: "))
lw = float(input("Enter weight of labs: "))
lists = [t, a, q, l, tw, aw, qw, lw]
return lists
def get_scores(lists):
# What are the scores?
scores = [0] * 5
for(x in range(lists[0]):
test_scores = float(input("enter your test scores: "))
scores[x] = test_scores
for(x in range(lists[1]):
test_scores = float(input("enter your assignment scores: "))
scores[x] = assignment_scores
for(x in range(lists[2]):
test_scores = float(input("enter your quiz scores: "))
scores[x] = quiz_scores
for(x in range(lists[3]):
test_scores = float(input("enter your lab scores: "))
scores[x] = lab_scores
sumlabs = 0
for(x in range(lists[3]):
sumlabs = sumlabs + scores[x]
print(sumlabs)
def get_weighted_average(lists):
main()
I am not sure how to proceed so any help is much appreciated.
Averaging a score means adding them up and dividing by the number of them. You can use the fact that a list has a way to tell you how many elements it has. For example if x is a list then len(x) is the number of things in the list. You should be careful about not trying to calculate the score of an empty list, because that would mean dividing by zero. In the following function the 'if score_list:' will be true if there is something in the list. Otherwise it returns None (since the average is not defined).
def average_score(score_list):
if score_list: # makes sure list is not empty
total = 0 # our total starts off as zero
for score in score_list: # starts a loop over each score
total += score # increases the total by the score
return total / len(score_list) # returns aveage
To form a list of scores from user input, presuming the user will put them all on the same line when you prompt them, you can get a string from the user (presumably like: "13.4 12.9 13.2" And then use the string's split method to convert this to a list of strings like ["13.4", "12.9", "13.2"], and then convert this list of strings to a list of floats. Finally using the average function above you can get an average:
test_score_entry = raw_input("Enter your test scores separated by spaces: ")
test_sore_strings = test_score_entry.split()
test_scores = [float(_) for _ in test_score_strings]
average_score = average(test_scores)
I have to write code that will calculate the average of three grades for each of a number of students, and display a message depending on the resulting average grades.
The program needs to be able process any number of students; but each student will have only 3 grades. I have to use a method to calculate the average score for each student, and also to determine the appropriate message depending on the average.
This is the code I have so far and I am stuck:
def main():
more = 'y'
while more == 'y' and more == 'Y':
numScore = int(input('How many test score per student: '))
for numtest in range(numScore):
print ("The score for test")
score = int(input(': '))
total += score
total = 0
print ("Student number", students + 1)
print ('-----------------------------------------')
avg = getAvg(numScore)
if avg > 90:
print ("You're doing excellent work")
elif avg > 85 and avg <= 90:
print("You are doing pretty good work")
elif avg > 70 and avg <= 85:
print ("You better get busy")
else:
print ("You need to get some help")
def getAvg (numScore):
avg = total / numScore
print ("The average for student number", student + 1, \ "is:", avg)
more = input('Do you want to enter another student test score and get the average score of the student (Enter y for yes and n for no): ')
main()
You had most of the elements correct in your script, but you need to think more about the order of everything.
Make sure you pass any arguments that are needed to a function. Your getAvg function needed three arguments for it to calculate the average and display it with the student number. Also you forgot to return average.
When calculating the avg ranges, if you first test for >90, then by definition the next elif avg > 85 will be less than or equal to 90 so it is only necessary to then test for >85.
The following has been rearranged a bit to work:
def getAvg(student, total, numScore):
average = total / numScore
print ("The average for student number", student, "is:", average)
return average
def main():
student = 0
more = 'y'
while more == 'y':
student += 1
total = 0
numScore = int(input('How many test scores per student: '))
for test_number in range(numScore):
print ("The score for test", test_number+1)
score = int(input(': '))
total += score
print ("Student number", student)
print ('-----------------------------------------')
avg = getAvg(student, total, numScore)
if avg > 90:
print ("You're doing excellent work")
elif avg > 85:
print("You are doing pretty good work")
elif avg > 70:
print ("You better get busy")
else:
print ("You need to get some help")
print()
print('Do you want to enter another student test score and get the average score of the student?')
more = input('Enter y for yes, and n for no: ').lower()
main()
Giving you the following kind of output:
How many test scores per student: 3
The score for test 1
: 93
The score for test 2
: 89
The score for test 3
: 73
Student number 1
-----------------------------------------
The average for student number 1 is: 85.0
You better get busy
Do you want to enter another student test score and get the average score of the student?
Enter y for yes, and n for no: n