How to create a grading system in Python? - python

I have an assignment for school and one of the tasks is to display the grades that the students will be receiving. The grades are:
A: 90% +
B: 80% - 89%
C: 70% - 79%
D: 60% - 69%
E: 50% - 59%
Here is some of the file, it's a comma-separated CSV file:
StudentName Score
Harrison 64
Jake 68
Jake 61
Hayley 86
I would like to know/get some guidance so I have a better understanding how to create the grade calculator.
I have spent ages trying to work it out but have had no hope.
My code:
def determine_grade(scores):
if scores >= 90 and <= 100:
return 'A'
elif scores >= 80 and <= 89:
return 'B'
elif scores >= 70 and <= 79:
return 'C'
elif scores >= 60 and <= 69:
return 'D'
elif scores >= 50 and <= 59:
return 'E'
else:
return 'F'

You can use bisect from Python's standard library for this purpose.
import bisect
def determine_grade(scores, breakpoints=[50, 60, 70, 80, 90], grades='FEDCBA'):
i = bisect.bisect(breakpoints, scores)
return grades[i]

You can use pandas and numpy to do it. Similar to this:
import pandas as pd
import numpy as np
#Create a DataFrame
d = { # Creating a dict for dataframe
'StudentName':['Harrison','Jake','Jake','Hayley'],
'Score':[64,68,61,86]}
df = pd.DataFrame(d) # converting dict to dataframe
# Keys get converted to column names and values to column values
#get grade by adding a column to the dataframe and apply np.where(), similar to a nested if
df['Grade'] = np.where((df.Score < 60 ),
'F', np.where((df.Score >= 60) & (df.Score <= 69),
'D', np.where((df.Score >= 70) & (df.Score <= 79),
'C', np.where((df.Score >= 80) & (df.Score <= 89),
'B', np.where((df.Score >= 90) & (df.Score <= 100),
'A', 'No Marks')))))
print(df)
result:
StudentName Score Grade
0 Harrison 64 D
1 Jake 68 D
2 Jake 61 D
3 Hayley 86 B

try this:
def determine_grade(scores):
if scores >= 90 and scores <= 100:
return 'A'
elif scores >= 80 and scores <= 89:
return 'B'
elif scores >= 70 and scores <= 79:
return 'C'
elif scores >= 60 and scores <= 69:
return 'D'
elif scores >= 50 and scores <= 59:
return 'E'
else:
return 'F'
in every if u have to compare scores with values this is why if scores >= 90 and <= 100: is incorrect, but after short editing it works

For scores >= 90 and <= 100 you can write 90 <= scores <= 100
i don't know, if the score is a float or integer number. If the score is a float, your comparison isn't enough.
if scores >= 90 and <= 100:
return 'A'
elif scores >= 80 and <= 89:
return 'B'
What happen if the score is 89.99?
This is my solution. There are a GRADES_PATTERN. So you must not change your function, if something is changed.
GRADES_PATTERN = {'A':[90, float('inf')], 'B':[80, 90], 'C':[70, 80], 'D':[60, 70], 'E':[50, 60], 'F':[0, 50]}
def check_grade(score, pattern):
for grade, score_range in pattern.iteritems():
if score_range[0] <= score < score_range[1]:
return grade
raise Exception("score is out of pattern range")
print check_grade(89.99, GRADES_PATTERN)
students = {'Harrison':64, 'Jake': 68, 'Hayley':86}
for name, score in students.iteritems():
print("Student {} hat score {} and grade {}".format(name, score, check_grade(score, GRADES_PATTERN)))

Another option...
If you didn't want an integer, you could change this for a float.
grade = int(input("What was your score?"))
if grade >=90 and grade <=100:
print("A*")
elif grade >=80 and grade <=89:
print("A")
elif grade >=70 and grade <=79:
print("B")
else:
print("Unknown grade")

You may just do this, noting the order of the if comparison.
def determine_grade(scores):
if scores >= 90:
return 'A'
elif scores >= 80:
return 'B'
elif scores >= 70:
return 'C'
elif scores >= 60:
return 'D'
elif scores >= 50:
return 'E'
else:
return 'F'

# Score Grade
# if > 1.0 error Bad score
# >= 0.9 A
# >= 0.8 B
# >= 0.7 C
# >= 0.6 D
# < 0.6 F
# ss (string score)
ss = input ("Enter your score: ")
# fs (float score)
try:
fs = float (ss)
except:
print("Error Bad score")
quit()
#print(fs)
if fs >= 1.0:
print("Error Bad Score")
if fs >= 0.9 :
print ("A")
elif fs >= 0.8 :
print ("B")
elif fs >= 0.7 :
print ("C")
elif fs >= 0.6 :
print ("D")
else:
print ("F")
I try to solve it referenced by this great site: https://www.py4e.com/html3/03-conditional

You could use this for the grading system but it doesn't put it into a nice array. Instead, it gives you a percentage and a grade letter.
def main():
a = input("Enter amount of questions... ")
b = input("Enter amount of questions correct... ")
def calc(a, b):
c = 100 / a
d = c * b
return d
r = calc(int(a), int(b))
print(f"Result: {int(r)}%")
if int(r) < 80:
print("Result is not passing, test will require Parent Signature.")
t = 0
if int(r) > 79:
print("The test has passed!")
if int(r) == 100 or int(r) > 92:
print('Grade Letter: A')
t += 1
if int(r) > 91:
if t != 0:
return
print('Grade Letter: A-')
t += 1
if int(r) > 90:
if t != 0:
return false
print('Grade Letter: B+')
t += 1
if int(r) > 87:
if t != 0:
return false
print('Grade Letter: B')
t += 1
if int(r) > 83:
if t != 0:
return false
print('Grade Letter: B-')
t += 1
if int(r) > 80:
if t != 0:
return false
print('Grade Letter: C+')
t += 1
if int(r) > 77:
if t != 0:
return false
print('Grade Letter: C')
t += 1
if int(r) > 73:
if t != 0:
return false
print('Grade Letter: C-')
t += 1
if int(r) > 70:
if t != 0:
return false
print('Grade Letter: D+')
t += 1
if int(r) > 67:
if t != 0:
return false
print('Grade Letter: D')
t += 1
if int(r) > 63:
if t != 0:
return false
print('Grade Letter: D-')
if int(r) > 60:
if t != 0:
return false
print('Grade Letter: F')
t += 1
else:
if t != 0:
return false
print('Grade Letter: F')
t += 1
main()

def determine_grade(scores):
if scores >= 0 and <= 39:
return 'U'
elif scores >= 40 and <= 49:
return 'D'
elif scores >= 50 and <= 59:
return 'C'
elif scores >= 60 and <= 69:
return 'B'
elif scores >= 70 and <= 79:
return 'A'
else:
return 'No Marks'

Related

Menu driven program

I'm trying to complete my menu driven program; however, I can't get this code to function properly. the goal is to get information from my previous code then get the evaluated output here. It keeps asking to execute my previous function before the menu pops up. get_list is the previous function that gets the list of numbers from the user.
previous code
def get_list(score_list=None):
if score_list is None:
score_list = []
n = int(input('How many scores do you want to enter? '))
for n in range(1, n + 1):
score = float(input('Enter score #{}: '.format(n)))
while True:
if 0 > score or score > 100:
print('Invalid score entered!!\n', 'Score should be a value between 0 and 100')
score = float(input('Enter score #{}: '.format(n)))
continue
else:
score_list.append(score)
break
return score_list
pass
problem code
def evaluate_list():
score_list = get_list()
lowest_score = min(score_list)
score_list.remove(lowest_score)
score_average = sum(score_list) / len(score_list)
if 90 < score_average <= 100:
grade = 'A'
elif 70 < score_average <= 80:
grade = 'B'
elif 40 < score_average <= 60:
grade = 'C'
elif score_average > 20 and score_average >= 40:
grade = 'D'
else:
grade = 'F'
print('----------Results--------------')
print('Lowest Score : ', lowest_score)
print('Modified List: ', score_list)
print('score Average: ', f'{score_average:.2f}')
print('Grade : ', grade)
evaluate_list()

I am trying to write a grade calculator with functions in Python

I am new to python and trying to make a grade calculator with functions. I want to check the users input so that when they put a number in it will check and see if it is between 1 and 100, but don't know how to do that. can anyone help? I also want to make it at the end so that it says for 'subject' and a score of 'number' you get a 'grade'.
here is what i have so far:
class_list = ['math', 'art', 'P.E.', 'science', 'english']
my_dict = {}
for idx,subject in enumerate(class_list):
print ("What is your score for ", class_list[idx])
my_dict[subject] = int(raw_input())
print my_dict
def assign_letter_grade(grade):
if 93 <= grade <= 100:
return 'A'
elif 90 <= grade < 93:
return 'A-'
elif 87 <= grade < 90:
return 'B+'
elif 83 <= grade < 87:
return 'B'
elif 80 <= grade < 83:
return 'B-'
elif 77 <= grade < 80:
return 'C+'
elif 73 <= grade < 77:
return 'C'
elif 70 <= grade < 73:
return 'C-'
elif 67 <= grade < 70:
return 'D+'
elif 63 <= grade < 67:
return 'D'
elif 60<= grade < 63:
return 'D-'
else:
return 'F'
Try it:
def raw_input():
while True:
score = input()
if score in [str(i) for i in range(101)]:
return score
class_list = ['math', 'art', 'P.E.', 'science', 'english']
my_dict = {}
for idx,subject in enumerate(class_list):
print ("What is your score for ", class_list[idx])
my_dict[subject] = assign_letter_grade(int(raw_input()))
print( my_dict)
def assign_letter_grade(grade):
if 93 <= grade <= 100:
return 'A'
elif 90 <= grade < 93:
return 'A-'
elif 87 <= grade < 90:
return 'B+'
elif 83 <= grade < 87:
return 'B'
elif 80 <= grade < 83:
return 'B-'
elif 77 <= grade < 80:
return 'C+'
elif 73 <= grade < 77:
return 'C'
elif 70 <= grade < 73:
return 'C-'
elif 67 <= grade < 70:
return 'D+'
elif 63 <= grade < 67:
return 'D'
elif 60<= grade < 63:
return 'D-'
else:
return 'F'
You can use the try and except functions.
For example:
data_valid = False
score = input("What is your score?")
while data_valid == False:
score = input("Enter your score: ")
try:
score = float(score)
except:
print("Invalid input. Please type an decimal or integer.")
continue
if score < 0 or score > 100:
print("Invalid input. Score should be between 0 and 100.")
continue
else:
data_valid = True

Make a grading Calculator with Functions?

I am doing a school assignment, and can not figure out despite how much I have tried, how to make the raw input change except to make each one individually,
Below is my assignment parameters:
Prompt the user to enter in a numerical score for a Math Class. The numerical score should be between 0 and 100.
Prompt the user to enter in a numerical score for a English Class. The numerical score should be between 0 and 100.
Prompt the user to enter in a numerical score for a PE Class. The numerical score should be between 0 and 100.
Prompt the user to enter in a numerical score for a Science Class. The numerical score should be between 0 and 100.
Prompt the user to enter in a numerical score for an Art Class. The numerical score should be between 0 and 100.
Call the letter grade function 5 times (once for each class).
Output the numerical score and the letter grade for each class.
And this is what I have done:
class_list=(['Math','Science','English','P.E.','Art'])
for i in class_list:
grades = int(input('What is your score for math: ',class_list[1])),
def score (grade):
if grade>=93:
return ("A")
elif grade >=90 and grade<=93:
return ("-A")
elif grade >= 87 and grade<=90:
return("B+")
elif grade>=83 and grade >=87:
return ("B")
elif grade >= 80 and grade >=83:
return ("B-")
elif grade >= 77 and grade >80:
return ("C+")
elif grade >= 73 and grade >= 77:
return ("C")
elif grade >= 70 and grade >=73:
return ("C-")
elif grade>= 67 and grade >= 70:
return ("D+")
elif grade >=63 and grade >=67:
return ("D")
elif grade >=60 and grade >=63:
return ("D-")
else:
return ("F")
print ("For an average score of"),grade, ("your grade is %s") % (score (grade))
Any advice?
For Python 3.2+ (iirc)
# convert the things to Py 2.x :); The below is one of the way;
class_list=['Math','Science','English','P.E.','Art']
my_dict = {}
for (idx,subject) in enumerate(class_list):
my_dict[subject] = int(input(f"What is your score for {class_list[idx]} :")) # my_dict.update({subject : int(input(f"What is your score for {class_list[idx]} : "))})
# Calculate letter grade of each student
def assign_letter_grade(grade):
if grade >= 93:
return ("A")
elif grade >= 90 and grade <= 93:
return ("A-")
elif grade >= 87 and grade <= 90:
return("B+")
elif grade>=83 and grade >= 87:
return ("B")
elif grade >= 80 and grade >= 83:
return ("B-")
elif grade >= 77 and grade > 80:
return ("C+")
elif grade >= 73 and grade >= 77:
return ("C")
elif grade >= 70 and grade >=73:
return ("C-")
elif grade>= 67 and grade >= 70:
return ("D+")
elif grade >= 63 and grade >= 67:
return ("D")
elif grade >= 60 and grade >= 63:
return ("D-")
else:
return ("F")
for subject in my_dict:
print(f"For {subject}, a score of {my_dict[subject]}, you are eligible to get grade as {assign_letter_grade(my_dict[subject])}")
For Python 2.x
class_list=['Math','Science','English','P.E.','Art']
my_dict = {}
for idx,subject in enumerate(class_list):
print("What is your score for :", class_list[idx])
my_dict[subject] = int(raw_input())
print(my_dict)

What are these "none" at the bottom of my output? [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
Brand new to python. When using the map function in python, i get a series of the word "none" as an output when i run my function. ive added screenshot below.
Code
def rawGradeToLetter(grade):
if grade >= 90:
print ("A")
elif grade < 90 and grade >= 80:
print ("B")
elif grade < 80 and grade >= 70:
print ("C")
elif grade < 70 and grade >= 60:
print ("D")
elif grade < 60:
print ("F")
def convertRawsToLetters(myList):
return list(map(rawGradeToLetter, myList))
Example run:
>>> convertRawsToLetters([90,80,70])
A
B
C
[None, None, None]
I have a feeling it has something to do with the word list before the map function, but if I remove that all I get is the address of the map like "map object at 0x8g9b7ea51950".
You need to return the grades, not print them. Printing the grades displays them on screen instead of giving a value back to the caller.
def rawGradeToLetter(grade):
if grade >= 90:
return "A"
elif grade < 90 and grade >= 80:
return "B"
elif grade < 80 and grade >= 70:
return "C"
elif grade < 70 and grade >= 60:
return "D"
elif grade < 60:
return "F"
Without a return statement your function implicitly returns None, which explains why you're seeing [None, None, None] in your output.
I think it is because you aren't returning anything on your map function, so it doesn't work correctly. You can try this, so the instead of being mapped to None, it will be mapped to the results:
def rawGradeToLetter(grade):
if grade >= 90:
print ("A")
return "A"
elif grade < 90 and grade >= 80:
print ("B")
return "B"
elif grade < 80 and grade >= 70:
print ("C")
return "C"
elif grade < 70 and grade >= 60:
print ("D")
return "D"
elif grade < 60:
print ("F")
return "F"
def convertRawsToLetters(myList):
return list(map(rawGradeToLetter, myList))
It is, if you want to maintain the prints, if not, you can remove them.
def rawGradeToLetter(grade):
if grade >= 90:
print ("A")
elif grade < 90 and grade >= 80:
print ("B")
elif grade < 80 and grade >= 70:
print ("C")
elif grade < 70 and grade >= 60:
print ("D")
elif grade < 60:
print ("F")
def convertRawsToLetters(myList):
for grade in myList:
rawGradeToLetter(grade)
I think you are over complicating it by using map() if all you want to do is print the grades.

python: grading assignment, negative value

I am working on a python lettering assignment.
90 or above is an A and so on and so on for the rest of the letter grades; but when a value is inputted as a negative number, I need the code to do nothing other than display an error.
This is what i tried so far:
#Design a Python program to assign grade to 10 students
#For each student, the program first asks for the user to enter a positive number
#A if the score is greater than or equal to 90
#B if the score is greater than or equal to 80 but less than 90
#C if the score is greater than or equal to 70 but less than 80
#D if the score is greater than or equal to 60 but less than 70
#F is the score is less than 60
#Ihen the program dispalys the letter grade for this student.
#Use while loop to repeat the above grade process for 10 students.
keep_going = 'y'
while keep_going == "y":
num = float(input("Enter a number: "))
if num >= 90:
print("You have an A")
elif num >= 80:
print("You have an 3")
elif num >= 70:
print("You have an C")
elif num >= 60:
print("You have an D")
elif (num < 60 and <= 0:
print ("You have an F")
else:
print("lnvalid Test Score.")
Original screenshot
I see three problems, all in the same line:
elif (num < 60 and <= 0:
Syntax: num < 60 and <= 0 is not a valid expression; should be num < 60 and num <= 0
Logic: num <= 0 is not what you want, it should be num >= 0
Syntax: you missed a closing bracket ).
If you change those, it should work.
grade = int(input("Enter Score:"))
print "FFFFFDCBAA"[grade//10] if grade >= 0 else "ERROR!!!!"
you just have to change your elif for below 60.
keep_going = 'y'
while keep_going == "y":
num = float(input("Enter a number: "))
if num >= 90:
print("You have an A")
elif num >= 80:
print("You have an 3")
elif num >= 70:
print("You have an C")
elif num >= 60:
print("You have an D")
elif 60 > num >= 0:
print ("You have an F")
else:
print("lnvalid Test Score.")

Categories