Python program to calculate average quiz grade for students - python

Ok, it I don't understand where I am going wrong because I had help with this coding and for the person who originally wrote it, it works just fine. However, mine seems to be malfunctioning. It keeps displaying the 'highest grade' multiple times instead of just once like it's supposed to. Having some real newbie problems here.
This is the code:
#this program will compute average quiz grade for a group of 5 students
#prompt user for quiz grade using a for loop for each of the 5 students
#assign names to student list
students = ["John", "Jake", "Jane", "Sally", "Susie"]
#grades: 90-100=A, 80-90=B, 70-80=C, 60-70=D, <60=F
#prompt user for student grades
grades = []
for student in students:
grade = eval(input(f"Enter the grade for {student}: "))
grades.append(grade)
sum = 0
for i in range(0,5):
for i in grades:
sum+=i
avg_grade=sum/5
#print average grade of students
if(avg_grade >=90):
print("Average Grade: A")
elif(avg_grade>=80 and avg_grade<90):
print("Average Grade: B")
elif(avg_grade>=70 and avg_grade<80):
print("Average Grade: C")
elif(avg_grade>=60 and avg_grade<70):
print("Average Grade: D")
else:
print("Average Grade: F")
#print highest grade
max_grade=max(grades)
for i in grades:
if(max_grade>=90):
print("Highest Grade: A")
elif(max_grade>=80 & max_grade<90):
print("Highest Grade: B")
elif(max_grade>=70 & max_grade<80):
print("Highest Grade: C")
elif(max_grade>=60 & max_grade<70):
print("Highest Grade: D")
else:
print("Highest Grade: F")

You are using a for loop at the end, which means for every single grade, the highest grade will be printed out.
You can delete the for, and unindent the if, elif, and else statements. Then the program should work as intended.

First of all, instead of using a variable such as sum, because sum is a python special function, you should use something like total.
Second, you shouldn't be using eval(input()) because the eval does nothing.
Third, when doing the for loop, you don't already know the number of students so it should be for i in range(len(students)-1) and the -1 part because list indexing starts at 0. Also, the second for loop should use a different variable then i because i is already used, so use something like j.

Use just sum to get the total grade and average value. Don't need to run an additional loop for 5 times.
total = sum(grades)
avg_grade = total/len(grades)
Then you don't need to run a loop to get the highest grade and also else should be indented with like other if elif. Follow the code
students = ["John", "Jake", "Jane", "Sally", "Susie"]
grades = []
for student in students:
grade = eval(input(f"Enter the grade for {student}: "))
grades.append(grade)
total = sum(grades)
avg_grade = total/len(grades)
if(avg_grade >= 90):
print("Average Grade: A")
elif(avg_grade >= 80 and avg_grade < 90):
print("Average Grade: B")
elif(avg_grade >= 70 and avg_grade < 80):
print("Average Grade: C")
elif(avg_grade >= 60 and avg_grade < 70):
print("Average Grade: D")
else:
print("Average Grade: F")
max_grade = max(grades)
if(max_grade >= 90):
print("Highest Grade: A")
elif(max_grade >= 80 & max_grade < 90):
print("Highest Grade: B")
elif(max_grade >= 70 & max_grade < 80):
print("Highest Grade: C")
elif(max_grade >= 60 & max_grade < 70):
print("Highest Grade: D")
else:
print("Highest Grade: F")

sum = 0
for i in range(0,5):
for i in grades:
sum+=i
avg_grade=sum/5
what that does is essentially go through every grade and increment sum every time and do that 5 times. It's unnecessarily O(n^2) and will run significantly slower when you add a lot of data.
Other than that a couple of useful things were pointed out by the other answers, I think one of them directly put the code there too so there isn't much I can say.
Basically you had logical flaws in your code that caused it to not function as intended.
debugging:
as you can see above the values for sum and avg_grade are totally not what they're intended to be, this was uncovered using print statements in the right places.
Your logic in implementation was flawed for the next part too, but this post is already too wordy for it's purpose.

Related

Stuck on this Python program

Image to problem
The for loop works, though I can't figure out how to put the grade on a single line as shown in the photo. It asks for grades individualy when ran instead.
Here is my code:
num_students = int(input("Enter the number of students: "))
scores = []
for i in range(num_students):
scores.append(int(input("Enter a score: ")))
best_score = max(scores)
for i in range(num_students):
if scores[i] >= best_score - 10:
grade = "A"
elif scores[i] >= best_score - 20:
grade = "B"
elif scores[i] >= best_score - 30:
grade = "C"
elif scores[i] >= best_score - 40:
grade = "D"
else:
grade = "F"
print("Student", i, "score is", scores[i], "and grade is", grade)
Use a single input() call instead of a loop, and use .split() to get each individual score.
num_students = int(input("Enter the number of students: "))
scores = input(f"Enter {num_students} scores: ")
scores = [int(score) for score in scores.split()]
As John Gordon answered, your main issue is calling input inside a loop. That dictates that each user response will be on its own line. To fix this, call input once, then break the resulting string up using .split(). Split when called with no arguments will break a string into a list at each space.
Here is an example of how to do this (without the f strings and list comprehensions from John's answer):
num_students = int(input("Enter the number of students: "))
score_string = input("Enter " + str(num_students) + " scores: ")
scores = []
for score in score_string.split():
scores.append(int(score))

How to make my program add the two averages together and calculate one average for the "class"?

I am trying to get my program to add all averages together to generate one big "class" average. The code is only taking the last individual average and dividing that by the number of students in calc_average. Any ideas? Here's my code:
def calc_average(total):
return total / student_num
def determine_score(grade):
if 90 <= grade <=100:
return 'A'
elif 80 <= grade <= 89:
return 'B'
elif 70 <= grade <= 79:
return 'C'
elif 60 <= grade <= 69:
return 'D'
else:
return 'F'
student_num=int(input('How many students?'))
for j in range(student_num):
scores = []
sum=0
total=0
for i in range(0,5):
score = int(input('Enter Test Scores'))
print ('Your letter grade is: ', determine_score(score))
scores.append(score)
sum=sum+score
iavg=sum/5
print('Your average is:', iavg)
total=total+iavg
cavg=calc_average(total)
abc_grade=determine_score(cavg)
print('Class average is: ' + str(cavg))
print("The class letter grade would be: " + str(abc_grade))
OUTPUT:
How many students?2
Enter Test Scores80
Your letter grade is: B
Enter Test Scores80
Your letter grade is: B
Enter Test Scores80
Your letter grade is: B
Enter Test Scores80
Your letter grade is: B
Enter Test Scores80
Your letter grade is: B
Your average is: 80.0
Enter Test Scores90
Your letter grade is: A
Enter Test Scores90
Your letter grade is: A
Enter Test Scores90
Your letter grade is: A
Enter Test Scores90
Your letter grade is: A
Enter Test Scores90
Your letter grade is: A
Your average is: 90.0
Class average is: 45.0
The class letter grade would be: F
There are a couple things you can fix.
Total is being set to 0 every time you loop for a new student. Put it above the loop.
You are adding to total after both loops have already gone. Put the addition to total in the loop itself.
These will get your program to run as intended. However, there are still things you can do to make this closer to best practices.
Include a space in your inputs, something like "Input Test Score: "
You're passing total to an average function, but treating num_students as a global value. While this doesn't break anything, it doesn't look right.
Your code for calculating total has two mistakes:
total = 0 happens inside the loop, so on each iteration it gets reset
total += iavg happens outside the loop, so it only happens once
I'd suggest just calculating the average the same way in both cases -- build a list, and then sum/divide. Using two different methods of doing the exact same thing makes it easier to confuse yourself.
def determine_grade(score):
if 90 <= score:
return 'A'
if 80 <= score:
return 'B'
if 70 <= score:
return 'C'
if 60 <= score:
return 'D'
return 'F'
student_num=int(input('How many students?'))
averages = [] # average score for each student
for j in range(student_num):
scores = [] # individual scores for this student
print(f'Student #{j}:')
for _ in range(5):
score = int(input('Enter Test Score: '))
print('Your letter grade is: ', determine_grade(score))
scores.append(score)
avg = sum(scores) / len(scores)
print('Your average is:', avg)
averages.append(avg)
class_avg = sum(averages) / len(averages)
print('Class average is:', class_avg)
print("The class letter grade would be:", determine_grade(class_avg))
Output:
How many students?2
Student #0:
Enter Test Score: 80
Your letter grade is: B
Enter Test Score: 80
Your letter grade is: B
Enter Test Score: 80
Your letter grade is: B
Enter Test Score: 80
Your letter grade is: B
Enter Test Score: 80
Your letter grade is: B
Your average is: 80.0
Student #1:
Enter Test Score: 90
Your letter grade is: A
Enter Test Score: 90
Your letter grade is: A
Enter Test Score: 90
Your letter grade is: A
Enter Test Score: 90
Your letter grade is: A
Enter Test Score: 90
Your letter grade is: A
Your average is: 90.0
Class average is: 85.0
The class letter grade would be: B

How do I make a program ask the user for the number of inputs, and add the result of their inputs togther?

I'm currently trying to make a program that calculates your final semester grade based on the grades you received previously and how big of an impact they have on your semester grade. The problem is I'm struggling to figure out how you can make the program ask the user for the number of grades they received and then ask for the same amount of grades.
In a nutshell, the program is supposed to do the following:
Ask for the number of received grades
Ask what grade the user got and the percentage of that grade x amounts of times, where x is the number the user gave on the first question.
Calculate the final semester grade based on the inputs.
I hope someone can help, I've made this code so far in case it helps you to understand what I'm trying to do.
grade1 = int(input("What was the first grade you received? " ))
percentage1 = float(input("What's the percentage of the first grade? "))
grade_value1 = grade1 * percentage1
grade2 = int(input("\nWhat was the second grade you received? "))
percentage2 = float(input("What's the percentage of the second grade? "))
grade_value2 = grade2 * percentage2
grade3 = int(input("\nWhat was the third grade you received? " ))
percentage3 = float(input("What's the percentage of the third grade? "))
grade_value3 = grade3 * percentage3
finale_grade = grade_value1 + grade_value2 + grade_value3
if finale_grade < 2.9:
print("\nYour finale grade is 2")
elif finale_grade < 5.4:
print("\nYour finale grade is 4")
elif finale_grade < 8.4:
print("\nYour finale grade is 7")
elif finale_grade < 10.9:
print("\nYour finale grade is 10")
else:
print("\nYour finale grade is 12")
#I hope this works , I'm a beginner tho
num_of_recieved_grades = int(input("number of recieved
grades ?"))
final_grade = 0
# for loop in range of the number entered
for x in range (num_of_recieved_grades ):
grade = int(input("what is the grade"))
percentage = float(input("what is the percentage"))
final_grade += grade * percentage

Python; calculate the average of three grades for each of a number of students

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

How to display max and min averages in a set of class averages

I'm writing a program in python to allow the user to enter the number of students in class, and then 3 test grades for each student. It also needs to show the student's test average, the class average, and the max and min average in the class. Right now, I'm having trouble making it not print the class average after each student's grades and average is printed. I also really can't make the max and mins work because it is changing with each student to that student's average.
students=int(input('Please enter the number of students in the class: '))
for number in range(students):
class_average == 0
first_grade=int(input("Enter student's first grade: "))
second_grade=int(input("Enter student's second grade: "))
third_grade=int(input("Enter student's third grade: "))
StudentAverage=(first_grade + second_grade + third_grade)/3
print("The student's average is", round(StudentAverage,2))
class_average= class_average + StudentAverage
print("The class average is", round(class_average/students,2))
maximum_num = 0
if StudentAverage > maximum_num:
maximum= StudentAverage
print("The maxiumum average is", round(maximum,2))
minimum_num = 100
if StudentAverage < minimum_num:
minimum= StudentAverage
print("The minimum average is", round(minimum,2))
I moved your initializers outside the loop so the value would not reset during each iteration. I moved the maximum and minimum comparisons into the loop and and replaced the maximum and minimum variable. Each new value was less than and greater than those values, respectively, so maximum_num and minimum_num needed to be used instead. The running class average was too low because it used the total number of students instead of the current number calculated. I replaced the use of student with number+1. I think this is the code you want.
students=int(input('Please enter the number of students in the class: '))
class_average = 0
maximum_num = 0
minimum_num = 100
for number in range(students):
first_grade=int(input("Enter student's first grade: "))
second_grade=int(input("Enter student's second grade: "))
third_grade=int(input("Enter student's third grade: "))
StudentAverage=(first_grade + second_grade + third_grade)/3
print("The student's average is", round(StudentAverage,2))
class_average= class_average + StudentAverage
print("The class average is", round(class_average/(number+1),2))
if StudentAverage > maximum_num:
maximum_num = StudentAverage
if StudentAverage < minimum_num:
minimum_num = StudentAverage
print("The minimum average is", round(minimum_num,2))
print("The maxiumum average is", round(maximum_num,2))

Categories

Resources