Not understanding my python dilemma - python

I am trying to finish up an assignment for a class "grade determination"
Write a program that will input 3 test scores.The program should determine and display their average.The program should then display the appropriate letter grade based on the average.The letter grade should be determined using a standard 10-point scale: (A = 90-100; B = 80-89.999; C = 70-79.999, etc.)
So far what I've been able to put together, (and it works averaging)
def main():
score1 = input("What is the first test score? ")
score2 = input("What is the second test score? ")
score3 = input("What is the third test score? ")
scoreaverage = score1 + score2 + score3
score = (scoreaverage / 3)
if score < 60:
grade="F"
elif score < 70:
grade="C"
elif score < 80:
grade="B"
elif score < 90:
grade="A"
else:
print score, " is the student's grade average!"
main()
If I replace score with grade I get an error.
raceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 16, in main
UnboundLocalError: local variable 'grade' referenced before assignment
So my question is how do I get the letter grade to print correctly?

def main():
score1 = input("What is the first test score? ")
score2 = input("What is the second test score? ")
score3 = input("What is the third test score? ")
scoreaverage = score1 + score2 + score3
score = (scoreaverage / 3)
if score < 60:
grade="F"
elif score < 70:
grade="C"
elif score < 80:
grade="B"
elif score < 90:
grade="A"
else:
print score, " is the student's grade average!"
main()
This would be your indented code. Are you sure you get the error you are mentioning?
The following code would generate the error you are mentioning.
print grade, " is the student's grade average!"
You can fix it this way:
def main():
score1 = input("What is the first test score? ")
score2 = input("What is the second test score? ")
score3 = input("What is the third test score? ")
scoreaverage = score1 + score2 + score3
score = (scoreaverage / 3)
grade = 'Unknown'
if score < 60:
grade="F"
elif score < 70:
grade="C"
elif score < 80:
grade="B"
elif score < 90:
grade="A"
print "%s is the student's grade average!" % grade
main()

Welcome to SO. As explained by others, your problem was accessing grade before assigning a value to it. Here is another suggestion for doing what you want to do: (see the comments)
#disregard next line if you are using Python 3.3
from __future__ import division
#use a list to store the scores
scores = []
#if you are using 2.7 replace input with raw_input
#use float() to convert the input to float
scores.append(float(input("First score? ")))
scores.append(float(input("Second score? ")))
scores.append(float(input("Third score? ")))
#More general way of calculating the average
score = sum(scores) / len(scores)
#You could use a dictionary for score-grade mapping
grades = {100: 'A', 90: 'A', 80: 'B',
70: 'C', 60: 'D', 50: 'E',
40: 'F', 30: 'F', 20: 'F',
10: 'F', 0: 'F'}
#removes the remainder from the score
#to make use of the above dictionary
grade = grades[score - (score % 10)]
#Use string formatting when printing
print('grade: %s, score: %.2f' % (grade, score))

Your grade comparisons are off by 10 points. You won't assign anything to grade if score is between 90 and 100. And a piece of advice for a newbie programmer: Use a debugger. You'd have discovered the problem in just a few minutes had you stepped through it.
Try:
if score < 60:
grade="F"
elif score < 70:
grade="D"
elif score < 80:
grade="C"
elif score < 90:
grade="B"
else:
grade="A"

Related

Letter for Grade for multiple students

def getGradeInfo():
numStudent = int(input('Total number of students: '))
getGrades = input(f'Enter {numStudent} scores: ')
gradeListNum = getGrades.split(' ')
maxScore = int(max(gradeListNum[0:numStudent]))
gradeListLetter = []
for grade in gradeListLetter:
if int(grade) >= maxScore - 10:
gradeListLetter.append('A')
elif int(grade) >= maxScore - 20:
gradeListLetter.append('B')
elif int(grade) >= maxScore - 30:
gradeListLetter.append('C')
elif int(grade) >= maxScore - 40:
gradeListLetter.append('D')
else:
gradeListLetter.append('F')
a = 1
while a<= numStudent:
print(f'Student{a} score is {gradeListNum[a-1]} and grade is')
a+=1
getGradeInfo()
I can get the input for the number of students in the code but can't figure out how to assign the letter to each of the student's grades for the print statement
As Adam Oppenheimer said,
for grade in gradeListLetter:
should be
for grade in gradeListNum:
Also,
print(f'Student{a} score is {gradeListNum[a-1]} and grade is')
should be
print(f'Student {a}: score is {gradeListNum[a - 1]} and grade is {gradeListLetter[a - 1]}')
You are iterating over gradeListLetter which is empty, try iterating over gradeListNum instead.
You also aren't printing the letter grade in your print statement.

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()

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)

syntax error python 'if' and 'else' statements

I'm getting this syntax error in my code and I can't figure out if it's an indentation error or something else (https://i.stack.imgur.com/Alazd.png).
# Creating a program that gives us the name,score and grade with variation in score and grade! A
name = input("Enter namez")
# print("name:", name)
print()
score = input("Enter scorez")
# print("score:", score)
score = int(score)
if score >= 75:
grade = 'Excellent'
elif score >= 60:
grade = 'Very good'
elif score >= 50
grade = 'Quite good'
elif score >= 40
grade = 'Not Bad'
elif score >= 30
grade = 'Pretty Bad'
elif score >= 20
grade = 'Horibble'
else: grade = 'Appauling'
print()
print('name:', name, 'score:', score, ' and grade:', grade)
print()
print('So,', name, 'you got a score of', score, 'and hence culminates that your grade becomes', grade, '.')
You have missed number of ":" in elif conditions and in last four conditions, set the indention by 4 spaces.
You are missing semi-colons (:) in elif condition. And then indentation too is not correct in last 3 assignment to grade.
Use proper indentation to mark blocks of your code.
Your elif statements are missing colons.
http://www.python.org/dev/peps/pep-0008/#other-recommendations
Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
The exception to that is when = is used to set named parameters.
That said, you could turn your code into a reusable function.
def grade(score):
""" Return a grade based on score."""
rank = ''
if score >= 75:
rank = 'Excellent'
elif score >= 60:
rank = 'Very good'
elif score >= 50:
rank = 'Quite good'
elif score >= 40:
rank = 'Not bad'
elif score >= 30:
rank = 'Pretty bad'
elif score >= 20:
rank = 'Horrible'
else:
rank = 'Appalling'
return rank
name = input('Enter name: ')
score = int(input('Enter score: '))
report_card = {'Name': name, 'Score': score, 'Grade': grade(score)}
print(report_card)
Test run:
Enter name: X
Enter score: 90
{'Name': 'X', 'Score': 90, 'Grade': 'Excellent'}

grade input program python if else elif

I am trying to solve this grade input program. I need to input the grades between 0.6 to 1.0 and assign them a letter value. I can only use the if else method as we haven't gotten to the other methods yet in class...
score = raw_input("Enter Score Grade:")
sco = int(float(score))
if score < 0.60:
print "Your grade is an F"
elif score >= 0.6:
print "grade d"
elif score >= 0.7:
print "grade c"
elif score >= 0.8:
print "grade b"
elif score >= 0.9:
print "grade a"
else:
print "wrong score"`
You don't have to go highest to lowest score, you can also do this:
score = float(raw_input("Enter Score Grade:"))
if score < 0.60:
print "Your grade is an F"
elif score < 0.7:
print "grade d"
elif score < 0.8:
print "grade c"
elif score < 0.9:
print "grade b"
elif score <= 1.0:
print "grade a"
else:
print "wrong score"
If you do decide to check from highest to lowest, being consistent is a good practice. You can check your failing grade last:
score = float(raw_input("Enter Score Grade:"))
if score > 1:
print "wrong score"
elif score >= 0.9:
print "grade a"
elif score >= 0.8:
print "grade b"
elif score >= 0.7:
print "grade c"
elif score >= 0.6:
print "grade d"
else:
print "Your grade is an F"
As a reusable function :
def grade(score):
if score > 1:
return "wrong score"
if score >= 0.9:
return "grade a"
if score >= 0.8:
return "grade b"
if score >= 0.7:
return "grade c"
if score >= 0.6:
return "grade d"
return "Your grade is an F"
score = float(raw_input("Enter Score Grade:"))
print grade(score)
You should start from the largest grade first:
as you see 0.92 > 0.6 and also 0.92 > 0.9
But according to yout logic, it will satisfy the first if and will never reach last if.
Do something like this:
score = raw_input("Enter Score Grade:")
sco = int(float(score))
if score < 0.60:
print ("Your grade is an F")
elif score >= 0.9:
print ("grade a")
elif score >= 0.8:
print ("grade b")
elif score >= 0.7:
print ("grade c")
elif score >= 0.6:
print ("grade d")
else:
print ("wrong score")
You need to go from high grade to low grade. You need to change sco = int(float(score)) to score = float(score). It is not required to change it to int as you are comparing float
score = raw_input('Enter the Score')
score = float(score)
if score >= 0.9:
grade = 'A'
elif score >= 0.8:
grade = 'B'
elif score >= 0.7:
grade = 'C'
elif score >= 0.6:
grade = 'D'
else:
grade = 'F'
print 'Your Grade : ' + grade
You have to take not of the first condition. If the first condition is equal to 0.9, it will equate to false and give the grade of 'B'. Also, it will be wise to convert the input to int first
score = int(raw_input('Enter the Score'))
score = float(score)
if score > 0.9:
grade = 'A'
elif score >= 0.8:
grade = 'B'
elif score >= 0.7:
grade = 'C'
elif score >= 0.6:
grade = 'D'
else:
grade = 'F'
print 'Your Grade : ' + grade
It is therefore advisable to use the greater than or equal to so as to handle the situation when it is equal to the upper value(ie 0.9).
score = int(raw_input('Enter the Score'))
score = float(score)
if score >= 0.9:
grade = 'A'
elif score >= 0.8:
grade = 'B'
elif score >= 0.7:
grade = 'C'
elif score >= 0.6:
grade = 'D'
else:
grade = 'F'
print 'Your Grade : ' + grade

Categories