I need help finishing a grade calculator program in python - python

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)

Related

How do I get data from dictionary in python?

a= int(input("Enter number of students:"))
i=1
n = []
t = []
p = []
avg = []
while i<=a:
total=0
name = input("Enter name of student:")
n.append(name)
subjects = int(input("Enter count of subjects:"))
i=i+1
j=1
while j<=subjects:
s = int(input("Enter marks:"))
total = total + s
j=j+1
percentage = (total/(subjects*100))*100
average = total/subjects
t.append(total)
p.append(percentage)
avg.append(avg)
result = dict(zip(n,p))
print("Total marks of", name, "is", total)
print("The students:",n)
print("The total of students:",total)
print("The average of students:",avg)
print("The percentage of students:", percentage)
print("The result of students:", result)
i want to store the data which I get from this code and later on display specific data like if I search for student's name, I'll get his marks and average. how do I do this?
First get the name. Then find the index of that. Now search for the marks, average etc in the arrays. Keep in mind that this will only work when the indices are same for each student data. Imagine that the arrays are stacked on top of each other, the data for each student should be in a straight line(You have done that only here).Oh, and one more thing, they are called arrays, not dictionaries. Dictionaries are initialized with {}(curly brackets).
Here is a sample code:
n=["S1","S2"]
t=[100,70]
avg=[30,20]
#say you want to get the data of S2
i=n.index("S2")
print("Student name: "+str(n[i])+" Student total marks:"+str(t[i])+" Student average: "+str(avg[i]))

Loop occurs twice within one range

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)

Find average grade of 10 students, and increment students

I need to ask the final grade of 10 students (while) incrementing their values:
So something like:
Please enter final grade for student 1
Please enter final grade for student 2
and so on... till 10
Then I need to get the grades they entered, and find average.
This is what I have so far:
def main():
x = []
for i in range(10):
final_grades = x.append(int(input('Please enter final grade for student: ')))
##average_final_grade = final_grades / 10
##print(average_final_grade)
main()
# list of grades
x = []
# count of students
n = 10
# fill list with grades from console input
# using pythonic generator
x = [int(input('Please enter final grade for student {}: '.format(i+1))) for i in range(n)]
# count average,
# sum is builtin way to sum values in list
# float required for python 2.x to make avg float, not int
average_final_grade = sum(x) / float(n)
print('Avg grade is {}'.format(average_final_grade))
Online demo.
First, you need to get the values, as you have already done:
x = []
for i in range(10):
x.append(int(input('Please enter final grade for student: ')))
Now you need to sum the values of x:
total_sum = sum(x)
Then, you get the average:
average_final_grade = total_sum/len(sum)
total=sum(x)
average=total/10
print(average)
tack this at the bottom and it should work

Python- Function that returns a value

Im really struggling with this question, can anyone help me write a code for this program? or at least say where am I going wrong? Ive tried a lot but can't seem to get the desired output.
This is the program description: Python 3 program that contains a function that receives three quiz scores and returns the average of these three scores to the main part of the Python program, where the average score is printed.
The code I've been trying:
def quizscores():
quiz1 = int(input("Enter quiz 1 score: "))
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
average = (quiz1 + quiz2 + quiz3) / 3
print (average)
return "average"
quizscores(quiz1,quiz2,quiz3)
One, you are returning a string, not the variable. Use return average instead of return "average". You also don't need the print() statement in the function... actually print() the function.
If you call a function the way you are doing it, you need to accept parameters and ask for input outside the function to prevent confusion. Use a loop as needed to repeatedly use the function without having to rerun it every time. So the final code would be:
def quiz_average(quiz1, quiz2, quiz3):
average = (quiz1 + quiz2 + quiz3) / 3
return average
quiz1 = int(input("Enter Quiz 1 score: "))
quiz2 = int(input("Enter Quiz 2 score: "))
quiz3 = int(input("Enter Quiz 3 score: "))
print(quiz_average(quiz1, quiz2, quiz3)) #Yes, variables can match the parameters
You are returning a string instead of the value. Try return average instead of return "average".
There are a few problems with your code:
your function has to accept parameters
you have to return the actual variable, not the name of the variable
you should ask those parameters and print the result outside of the function
Try something like this:
def quizscores(score1, score2, score3): # added parameters
average = (score1 + score2 + score3) / 3
return average # removed "quotes"
quiz1 = int(input("Enter quiz 1 score: ")) # moved to outside of function
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
print(quizscores(quiz1,quiz2,quiz3)) # print the result
An alternative answer to the already posted solutions could be to have the user input all of their test scores (separated by a comma) and then gets added up and divided by three using the sum method and division sign to get the average.
def main():
quizScores()
'''Method creates a scores array with all three scores separated
by a comma and them uses the sum method to add all them up to get
the total and then divides by 3 to get the average.
The statement is printed (to see the average) and also returned
to prevent a NoneType from occurring'''
def quizScores():
scores = map(int, input("Enter your three quiz scores: ").split(","))
answer = sum(scores) / 3
print (answer)
return answer
if __name__ == "__main__":
main()

Calculting GPA using While Loop (Python)

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

Categories

Resources