Test average and grade - python

def calc_average(a,b,c,d,f):#function used to calculate average
return (a+b+c+d+f)//5
def determine_grade(test_score):#function used to determine letter grade
if gradeAverage > 89:
return "A"
elif gradeAverage > 79:
return "B"
elif gradeAverage > 69:
return "C"
elif gradeAverage > 59:
return "D"
else:
return "F"
test1 = float(input("Please enter test score for test1: "))#prompt user to enter grade
test2 = float(input("Please enter test score for test2: "))#prompt user to enter grade
test3 = float(input("Please enter test score for test3: "))#prompt user to enter grade
test4 = float(input("Please enter test score for test4: "))#prompt user to enter grade
test5 = float(input("Please enter test score for test5: "))#prompt user to enter grade
gradeAverage = calc_average(test1, test2, test3, test4, test5)#variable
finalgrade = determine_grade(gradeAverage)#variable
print(finalgrade)#display grade
print(gradeAverage)display grade letter
This is a problem in the "starting out with Python" book, I am supposed to calculate the average grade of 5 test scores and give a letter grade. My problem is, I wonder if I need the variables or not. If there is a better way I would like to know.

You can use for loops and lists to eliminate some variables and also generalize a bit:
def calc_average(grades): #function used to calculate average, now takes a list
return sum(grades)//len(grades)
grades = []
number_of_tests = int(input("input the total number of test results >>"))
for i in range(1, number_of_tests+1):
g = int(input("input grade " + str(i) +" >>"))
grades.append(g)
avg = calc_average(grades)
print(avg)
I would explain everything in detail, but I am sure your text book will soon enough tell you about "for loops", "lists", and so on. They usually start slow, and let you do unnecessary work so you can get used to the basics. Keep on reading m8 :)
(Or watch this video, in my opinion this is one of the best beginners guides out there: https://youtu.be/rfscVS0vtbw)

Please allow me to share a few comments:
The function determine_grade(test_score) takes in a parameter test_score, and should be using this parameter to determine the grade, instead of the global parameter gradeAverage. So your code should be:
def determine_grade(test_score):#function used to determine letter grade
if test_score > 89:
return "A"
elif test_score > 79:
return "B"
elif test_score > 69:
return "C"
elif test_score > 59:
return "D"
else:
return "F"
The calculation for average should not be a floor division (a+b+c+d+f)//5. This floor division formula outputs only the integer value and ignores the decimals behind. So the formula should be (a+b+c+d+f)/5.
A for loop would be elegant, and avoiding repeated codes. Then a list test_list could be used to store the test scores and be passed to the function calc_average to calculate the average.
The final code should look like this:
def calc_average(test_list): #function used to calculate average
return sum(test_list)/len(test_list)
def determine_grade(test_score): #function used to determine letter grade
if test_score > 89:
return "A"
elif test_score > 79:
return "B"
elif test_score > 69:
return "C"
elif test_score > 59:
return "D"
else:
return "F"
n = 5
test_list = []
for i in range(n):
score = float(input("Please enter test score for test{}: ".format(i+1))) #prompt user to enter grade
test_list.append(score)
gradeAverage = calc_average(test_list) #variable
finalgrade = determine_grade(gradeAverage) #variable
print(finalgrade) #display grade
print(gradeAverage) #display grade letter
Output
Please enter test score for test1: 66
Please enter test score for test2: 77
Please enter test score for test3: 88
Please enter test score for test4: 86
Please enter test score for test5: 69
C
77.2

Related

Limiting user from 0-100 in input function

How to create a program that limiting user in input function from 0-100 only. We need to ask user to for their grade in 4 tests after that if the user does not have taken any of those test it shows INC.
while True:
score = float(input('Enter your score: '))
if not 0 <= score <= 100:
continue
else:
break
while True:
score = input('Enter your score: ')
if not (0 <= score <= 100):
continue
else:
break

How To Determine Grades in Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This is using Python 3, through a website known as Repl.it
I am currently working on solving a question that states:
"Write a program that will take a grade between 100 and 0 zero and print the letter grade according to the scale:
90 or above is equivalent to an A grade
80-89 is equivalent to a B grade
70-79 is equivalent to a C grade
65-69 is equivalent to a D grade
64 or below is equivalent to an F grade
if user gives something other then integer or something that is not between 0 and 100 give an error and ask again.
Example run:
Enter the number grade: asd
Program only accepts integers between 0 and 100
Enter the number grade: 65
Your grade is D"
My current code is as follows:
def printgrade(score):
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 65:
print("D")
elif score <= 64:
print("F")
else:
print("ERROR")
def main():
score = int(input("Enter a score: "))
print("Your grade is:", printgrade(score))
main()
The only error message that I am receiving is that print is invalid syntax, but I cannot figure out as to why, am I just missing something? Any comments will be greatly appreciated.
Besides the error with the ( going through the code some modifications could make this a little more optimal. We can use a try, except block to eliminate the ERROR else statement and handle that directly when we receive the input if is not a valid int and we force a valid int between 0 and 100 using a while statement. Next our function should return 'A' or B, C etc. Then when we can use the print('Your grade is: ', printgrade(score)) as desired
def printgrade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 65:
return "D"
else:
return "F"
def main():
score = ''
while score not in range(0,101):
try:
score = int(input("Enter a score: "))
except ValueError:
print('Invalid Entry')
print("Your grade is:", printgrade(score))
main()
def printgrade(score):
if score >= 90: return "A"
elif score >= 80: return "B"
elif score >= 70: return "C"
elif score >= 65: return "D"
elif score <= 64: return "F"
else: return "ERROR"
def main():
score = int(input("Enter a score: "))
print("Your grade is:", printgrade(score))
main()
Hope it helps. You have to return value and not print them inside the sub function as your print function is expecting a value from your sub function.

Using functions for multiple inputs [Python]

I'm new to python, taking my first class in it right now, only about 4 weeks in.
The assignment is to calculate test average and display the grade for each test inputted.
Part of the assignment is to use a function to calculate the average as well as deciding what letter grade to be assigned to each score.
As I understand it, functions are supposed to help cut down global variables.
My question is this: how do I condense this code?
I don't know how to use a function for deciding letter grade and then displaying that without creating a global variable for each grade that has been inputted.
If you notice any redundancy in my code, I would appreciate a heads up and a little lesson on how to cut that out. I can already smell the mark downs I will get if I turn this in as is...
def main():
grade1=float(input( "Enter score (0-100):"))
while (grade1 <0 or grade1 >100 ):
if grade1 <0 or grade1 >100:
print("Please enter a valid grade")
grade1=float(input( "Enter score (0-100):"))
grade2=float(input( "Enter score (0-100):"))
while (grade2 <0 or grade2 >100 ):
if grade2 <0 or grade2 >100:
print("Please enter a valid grade")
grade2=float(input( "Enter score (0-100):"))
grade3=float(input( "Enter score (0-100):"))
while (grade3 <0 or grade3 >100 ):
if grade3 <0 or grade3 >100:
print("Please enter a valid grade")
grade3=float(input( "Enter score (0-100):"))
grade4=float(input( "Enter score (0-100):"))
while (grade4 <0 or grade4 >100 ):
if grade4 <0 or grade4 >100:
print("Please enter a valid grade")
grade4=float(input( "Enter score (0-100):"))
grade5=float(input( "Enter score (0-100):"))
while (grade5 <0 or grade5 >100 ):
if grade5 <0 or grade5 >100:
print("Please enter a valid grade")
grade5=float(input( "Enter score (0-100):"))
total=grade1+grade2+grade3+grade4+grade5
testAverage=calcAverage(total)
eachGrade1=determineGrade(grade1)
eachGrade2=determineGrade(grade2)
eachGrade3=determineGrade(grade3)
eachGrade4=determineGrade(grade4)
eachGrade5=determineGrade(grade5)
print("\nTest #1 grade:", (eachGrade1))
print("Test #2 grade:", (eachGrade2))
print("Test #3 grade:", (eachGrade3))
print("Test #4 grade:", (eachGrade4))
print("Test #5 grade:", (eachGrade5))
print("\nTest average:", (testAverage),("%"))
def calcAverage(total):
average=total/5
return average
def determineGrade(grade):
if grade >=90:
return "A"
elif grade >=80:
return "B"
elif grade >=70:
return "C"
elif grade >=60:
return "D"
else:
return "F"
I won't refactor your whole code, but here's a few pointers:
First of all, you need a function to get the user input, let's call it get_score. I won't go into the details here because there's an excellent resource on how to write a function for that here: Asking the user for input until they give a valid response. That function should return a float or integer, so don't forget that input (assuming you are using Python 3) returns a string which you have to cast to int or float manually.
To get a list of n scores, I propose the function:
def get_n_scores(n):
return [get_score() for _ in range(n)]
The stuff in the square brackets is a list comprehension and equivalent to:
scores = []
for _ in range(n):
scores.append(get_score())
Use this code instead if you are not comfortable with the comprehension (don't forget to return result).
The variable name _ is commonly used to indicate a temporary value that is not used (other than for iteration).
You can avoid declaring grade1 ... grade5 by calling all_scores = get_n_scores(5), which will return a list with the user input. Remember that indexing is zero-based, so you'll be able to access all_scores[0] ... all_scores[4].
Instead of hardcoding total, you can just apply the built in sum function: total = sum(all_scores), assuming all_scores holds integers or floats.
Finally, you can determine the grade for each score by applying your function determineGrade to every score in all_scores. Again, you can use a comprehension:
all_grades = [determineGrade(score) for score in all_scores]
or the traditional:
all_grades = []
for score in all_scores:
all_grades.append(determineGrade(score))
The other stuff looks okay, except that in order to print the grade you can just loop over all_grades and print the items. It's up to you if you want to write further functions that wrap a couple of the individual function calls we're making.
In general, always avoid repeating yourself, write a function instead.
I'll write is as below:
def get_grade():
while(True):
grade = float(input("Enter score (0-100):"))
if grade >= 0 and grade <= 100:
return grade
print("Please enter a valid grade!")
def get_average(sum_val, counter):
return sum_val/counter
def determine_grade(grade):
if grade >=90:
return "A"
elif grade >=80:
return "B"
elif grade >=70:
return "C"
elif grade >=60:
return "D"
else:
return "F"
test_num = 5
sum_val = 0
result = {}
for i in range(test_num):
grade = get_grade()
result[i] = determine_grade(grade)
sum_val += grade
for key in result:
print ("Test %d Grade is %s" % (key+1, result[key]))
avg = get_average(sum_val, test_num)
print ("Average is %d" % avg)
Works like this:
>>> ================================ RESTART ================================
>>>
Enter score (0-100):89
Enter score (0-100):34
Enter score (0-100):348
Please enter a valid grade!
Enter score (0-100):34
Enter score (0-100):90
Enter score (0-100):85
Test 1 Grade is B
Test 2 Grade is F
Test 3 Grade is F
Test 4 Grade is A
Test 5 Grade is B
Average is 66
>>>

I am trying to create a function in Python language. Can anyone show me how to get an output from it?

Write a function called evaluate_letter_grade which accepts a single float argument (representing the student's grade) and returns a string which represents the corresponding letter grade. Letter grades are assigned as follows:
Grade Letter
90-100 A
80-89.99 B
70-79.99 C
60-69.99 D
0-59.99 F
Greater than 100 or less than 0 Z
I think I have created my function correctly (maybe), but I can not figure out how to get it to output the correct letter grade. Any suggestions?
This is what I have:
def evaluate_letter_grade(grade, lettergrade):
if grade >= 90 or grade <= 100:
lettergrade = "A"
elif grade >= 80 or grade <= 89.99:
lettergrade = "B"
elif grade >= 70 or grade <= 79.99:
lettergrade = "C"
elif grade >= 60 or grade <= 69.99:
lettergrade = "D"
elif grade >= 0 or grade <= 59.99:
lettergrade = "F"
else:
lettergrade = "Z"
return lettergrade
grade = float(input("Enter the student's grade: "))
evaluate = evaluate_letter_grade(grade, lettergrade)
finalgrade = evaluate
print finalgrade
Your function is correct as you have written it, except you only want one input parameter, grade, the float value of the grade.
Also, why not simply condense:
evaluate = evaluate_letter_grade(grade, lettergrade)
finalgrade = evaluate
print finalgrade
to:
print evaluate_letter_grade(grade)
I think I have created my function correctly (maybe), but I can not figure out how to get it to output the correct letter grade.
Whatever is in your return statement is the "output". In this case you are passing in float values and returning a String. Your function will "resolve" to that return value from which you can assign it to other variables or pass it as a parameter (as you did with the print function).

Cant get str to work in if-loop Python 3

I wrote a grade calculator where you put a float in and get a grade based on what you scored. The problem I have is that I belive I need a float(input... But that becomes an error if you write letters in the box...
def scoreGrade():
"""
Determine the grade from a score
"""
gradeA = "A"
gradeB = "B"
gradeC = "C"
gradeD = "D"
gradeF = "F"
score = float(input("Please write the score you got on the test, 0-10: "))
if score >= 9:
print("You did really good, your grade is:", gradeA, ". Congratulations")
elif score >= 7:
print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
elif score >= 5:
print("Not too bad. You got a:", gradeC)
elif score >= 4:
print("That was close...:", gradeD)
elif score < 4:
print("You need to step up and take the test again:", gradeF)
else:
print("Grow up and write your score between 0 and 10")
Is there a way to get rid of the float and print the last statement if you write something else that the score from 0-10?
Something like this:
score = None
while score is None:
try:
score = float(input("Please write the score you got on the test, 0-10: "))
except ValueError:
continue
Keep on asking until the float cast works without raising the ValueError exception.
You could do
try:
score = float(input("Please write the score you got on the test, 0-10: "))
except ValueError:
print("Grow up and write your score between 0 and 10")
scoreGrade()
I would suggest to use EAFP approach and separate handling good and bad inputs.
score_as_string = input("Please write the score you got on the test, 0-10: ")
try:
score_as_number = float(score_as_string)
except ValueError:
# handle error
else:
print_grade(score_as_number)
def print_grade(score):
"""
Determine the grade from a score
"""
gradeA = "A"
gradeB = "B"
gradeC = "C"
gradeD = "D"
gradeF = "F"
if score >= 9:
print("You did really good, your grade is:", gradeA, ". Congratulations")
elif score >= 7:
print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
elif score >= 5:
print("Not too bad. You got a:", gradeC)
elif score >= 4:
print("That was close...:", gradeD)
elif score < 4:
print("You need to step up and take the test again:", gradeF)
else:
print("Grow up and write your score between 0 and 10")
Note that typically you want to return from functions, not print inside them. Using function output as part of print statement is detail, and function does not have to know that.

Categories