Need advice regarding function assignment - python

**Thank you for all of the help in calculating the average letter grade that corresponds to average of scores. I also need to list each grade and the corresponding letter grade. I am a little confused on how to do this. Do I make another function to print this?
def main():
student_name = input('Please enter your first and last name: ')
scores = askForScore()
avg_score = calc_average(scores)
letter_grade = determine_grade(avg_score)
print(student_name)
print('The average of 8 tests is', letter_grade)
print('letter_grade\tnumber_grade')
print('--------------------------')
def askForScore():
score1 = float(input('Please enter the first test score:'))
score2 = float(input('Please enter the second test score:'))
score3 = float(input('Please enter the third test score:'))
score4 = float(input('Please enter the fourth test score:'))
score5 = float(input('Please enter the fifth test score:'))
score6 = float(input('Please enter the sixth test score:'))
score7 = float(input('Please enter the seventh test score:'))
score8 = float(input('Please enter the eigth test score:'))
return (score1, score2, score3, score4, score5, score6, score7, score8)
def calc_average(scores):
avg_score = (scores[0] + scores[1] + scores[2] + scores[3] + scores[4] + scores[5] + scores[6] + scores[7]) / 8
return avg_score
def determine_grade(avg_score):
if avg_score >= 90 and avg_score <= 100:
return 'A'
elif avg_score >= 80 and avg_score <= 89:
return 'B'
elif avg_score >= 70 and avg_score <= 79:
return 'C'
elif avg_score >= 60 and avg_score <= 69:
return 'D'
else:
return 'F'
main()

Here you go. There were a few problems.
1) When you return a value from a function, you need to assign it to a variable so you can pass it into the next function.
2) String literals like the letter grade "F" need to be inside single or double quote marks.
def main():
student_name = input('Please enter your first and last name: ')
scores = askForScore()
avg_score = calc_average(scores)
letter_grade = determine_grade(avg_score)
print(letter_grade)
def askForScore():
score1 = float(input('Please enter the first test score:'))
score2 = float(input('Please enter the second test score:'))
score3 = float(input('Please enter the third test score:'))
score4 = float(input('Please enter the fourth test score:'))
score5 = float(input('Please enter the fifth test score:'))
return (score1, score2, score3, score4, score5)
def calc_average(scores):
avg_score = (scores[0] + scores[1] + scores[2] + scores[3] + scores[4]) / 5
return avg_score
def determine_grade(avg_score):
if avg_score >= 90 and avg_score <= 100:
return 'A'
elif avg_score >= 80 and avg_score <= 89:
return 'B'
elif avg_score >= 70 and avg_score <= 79:
return 'C'
elif avg_score >= 60 and avg_score <= 69:
return 'D'
else:
return 'F'
main()

Make sure you understand some Python concepts such as the scope of variables, return statements and function arguments. In your case, for instance, score1 ... score5 inside askForScore are not "readable" by calc_average. In fact, calc_average returns the values you need and those values need to be passed to the next function as arguments like this:
...
score1, score2, score3, score4, score5 = askForScore()
calc_average(score1, score2, score3, score4, score5)
...

Related

I don't know why my 'elif ' and 'else' code does not work

score = input("What is your score? ")
if score == str(100):
print('Perfect!')
elif score <= str(range(95, 99)):
print('Great!')
elif score <= str(range(90, 95)):
print('Good')
else:
print('Fail')
It works when I type 95 to 100, but it doesn't work when I type other numbers.
Use ints to compare numbers, not strings:
score = int(input("What is your score? "))
if score == 100:
print('Perfect!')
elif score in range(95, 100): # This 100 catches the 99 case
print('Great!')
elif score in range(90, 95):
print('Good')
else:
print('Fail')

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)

Python : How to print individual element of Tuple in print function

My code:
def askTestScores():
test1 = int(input("Enter test 1 score: "))
test2 = int(input("Enter test 2 score: "))
test3 = int(input("Enter test 3 score: "))
test4 = int(input("Enter test 4 score: "))
test5 = int(input("Enter test 5 score: "))
testScores = (test1,test2,test3,test4,test5)
return testScores
def determine_grade(testScores):
for i in range(testScores):
if i >= 90 and i <= 100:
return "A"
elif i >= 80 and i <= 89:
return "B"
elif i >= 70 and i <= 79:
return "C"
elif i >= 60 and i <= 69:
return "D"
else:
return "F"
def displayGrades(testScores):
print("Score\t\t Grade")
print("-----------------------")
print(f"{testScores[0]}\t\t {determine_grade(testScores[0])}")
print(f"{testScores[1]}\t\t {determine_grade(testScores[1])}")
print(f"{testScores[2]}\t\t {determine_grade(testScores[2])}")
print(f"{testScores[3]}\t\t {determine_grade(testScores[3])}")
print(f"{testScores[4]}\t\t {determine_grade(testScores[4])}")
x = askTestScore
displayGrades(x)
This is only printing "F" when I use the range function in the loop for determine_grade function. What I want is, to print each grade individually, but when I remove the range function I am getting type error: saying int object not iterable. How can I solve this?
instead of range() Use:
for i in testscores :
Why do you need for in determine_grades ?
I think you meant this
def determine_grades(testScore):
if testScore >= 90 and testScore <= 100:
return "A"
elif testScore >= 80 and testScore <= 89:
return "B"
elif testScore >= 70 and testScore <= 79:
return "C"
elif testScore >= 60 and testScore <= 69:
return "D"
else:
return "F"
def displayGrades(testScores):
print("Score\t\t Grade")
print("-----------------------")
for testScore in testScores:
print(f"{testScore}\t\t {determine_grades(testScore)}")
Here you loop testScores in displayGrades to pass one score at a time to determine_grade and print them.
Because if you used for loop in determine_grades then you need to return a list of grades and not String.
You can improve make your code by appending the inputs to a list instead of tuple
def askTestScores():
testScores = []
for i in range(5):
score = int(input(f"Enter test {i + 1} score: "))
testScores.append(score)
return testScores
EDIT:
If you need tuple you can convert the list to tuple
def askTestScores():
testScores = []
for i in range(5):
score = int(input(f"Enter test {i + 1} score: "))
testScores.append(score)
testScores = tuple(testScores)
return testScores
the easiest way to do it is to include each item of your tuple in a list and remove the range function:
def askTestScores():
test1 = int(input("Enter test 1 score: "))
test2 = int(input("Enter test 2 score: "))
test3 = int(input("Enter test 3 score: "))
test4 = int(input("Enter test 4 score: "))
test5 = int(input("Enter test 5 score: "))
testscores = ([test1],[test2],[test3],[test4],[test5])
return testscores
def determine_grade(testscores):
for i in testscores:
if i >= 90 and i <= 100:
return "A"
elif i >= 80 and i <= 89:
return "B"
elif i >= 70 and i <= 79:
return "C"
elif i >= 60 and i <= 69:
return "D"
else:
return "F"
def displayGrades(testscores):
print("Score\t\t Grade")
print("-----------------------")
print(f"{testscores[0]}\t\t {determine_grade(testscores[0])}")
print(f"{testscores[1]}\t\t {determine_grade(testscores[1])}")
print(f"{testscores[2]}\t\t {determine_grade(testscores[2])}")
print(f"{testscores[3]}\t\t {determine_grade(testscores[3])}")
print(f"{testscores[4]}\t\t {determine_grade(testscores[4])}")
x = askTestScores()
displayGrades(x)
displayGrades(x)

How To Create A Table in Python

I've posted this before, but I'm reposting it with more detailed information.
This is my assignment:
And, so far, this is my code:
# Define a function that caculates average test scores
def calculate_average(score1, score2, score3, score4, score5):
total = score1 + score2 + score3 + score4 + score5
average = total % 5
print(average)
# Define a function that determines a letter grade
# Based on the given score
def determine_grade(score):
if score < 60:
print 'F'
elif score => 60 or score <= 69:
print 'D'
elif score => 70 or score <= 79:
print 'C'
elif score => 80 or score <= 89:
print 'B'
elif score => 90 or score <= 100:
print 'A'
# Define a function that prompts the user to input names and test scores
def input_data():
score1 = input('Enter score 1:')
name1 = input('Enter name 1:')
score2 = input('Enter score 2:')
name2 = input('Enter name 2:')
score3 = input('Enter score 3:')
name3 = input('Enter name 3:')
score4 = input('Enter score 4:')
name4 = input('Enter name 4:')
score5 = input('Enter score 5:')
name5 = input('Enter name 5:')
# Define a function that displays a letter grade for each score
# followed by the student's name and the average test score
def display_menu():
As I said in the first post, I don't have a real problem with anything except setting up that table. I'm really confused!
I asked my instructor (this is an online course, BTW), and he said: "Its just using the print operator, like you have done in previous modules, your printing text , variables and the return value of a function."
Now I'm just wondering where to start.
EDIT: I've updated my code this:
# Define a function that prompts the user to input names and test scores
def input_data():
score1 = input('Enter score 1:')
name1 = input('Enter name 1:')
score2 = input('Enter score 2:')
name2 = input('Enter name 2:')
score3 = input('Enter score 3:')
name3 = input('Enter name 3:')
score4 = input('Enter score 4:')
name4 = input('Enter name 4:')
score5 = input('Enter score 5:')
name5 = input('Enter name 5:')
# Define a function that determines a letter grade
# Based on the given score
def determine_grade(score):
if score < 60:
print ('F')
elif 60 <= score <= 69:
print ('D')
elif 70 <= score <= 79:
print ('C')
elif 80 <= score <= 89:
print ('B')
elif 90 <= score <= 100:
print ('A')
# Define a function that caculates average test scores
def calculate_average(score1, score2, score3, score4, score5):
total = score1 + score2 + score3 + score4 + score5
average = total / 5
print(average)
# Define a function that displays a letter grade for each score
# followed by the student's name and the average test score
def display_menu():
for x in range(10):
print("{:<10}".format("{:0.1f}".format(x)), end='')
print ("Name\t\t\tnumeric grade\t\tletter grade")
print ("---------------------------------------------------------------")
print ("%s:\t\t\t%f\t\t%s") % ('name1', 'score1', determine_grade)
print ("%s:\t\t\t%f\t\t%s") % ('name2', 'score2', determine_grade)
print ("%s:\t\t\t%f\t\t%s") % ('name3', 'score3', determine_grade)
print ("%s:\t\t\t%f\t\t%s") % ('name4', 'score4', determine_grade)
print ("%s:\t\t\t%f\t\t%s") % ('name5', 'score5', determine_grade)
print ("---------------------------------------------------------------")
But when I run it:
EDIT #2: This is my code currently:
# Define a function that prompts the user to input names and test scores
def input_data():
score1 = input('Enter score 1:')
name1 = input('Enter name 1:')
score2 = input('Enter score 2:')
name2 = input('Enter name 2:')
score3 = input('Enter score 3:')
name3 = input('Enter name 3:')
score4 = input('Enter score 4:')
name4 = input('Enter name 4:')
score5 = input('Enter score 5:')
name5 = input('Enter name 5:')
# Define a function that caculates average test scores
def calculate_average(score1, score2, score3, score4, score5):
total = score1 + score2 + score3 + score4 + score5
average = total / 5
print(average)
# Define a function that determines a letter grade
# Based on the given score
def determine_grade(score):
if score < 60:
print ('F')
elif 60 <= score <= 69:
print ('D')
elif 70 <= score <= 79:
print ('C')
elif 80 <= score <= 89:
print ('B')
elif 90 <= score <= 100:
print ('A')
# Define a function that displays a letter grade for each score
# followed by the student's name and the average test score
def display_menu():
print ("Name\t\t\tnumeric grade\t\tlettergrade")
print ("---------------------------------------------------------------")
print ("%s:\t\t\t%f\t\t%s" % ('name1', 93, 'A'))
print ("%s:\t\t\t%f\t\t%s" % ('name2', 89, 'B'))
print ("%s:\t\t\t%f\t\t%s" % ('name3', 76, 'C'))
print ("%s:\t\t\t%f\t\t%s" % ('name4', 58, 'F'))
print ("%s:\t\t\t%f\t\t%s" % ('name5', 98, 'A'))
print ("---------------------------------------------------------------")
print (calculate_average)
And this is what happens when I run it:
Now, I have mainly two problems:
1) How do I get the input statements to execute and enter the data BEFORE the table is displayed?
2) How do I convert the numbers displayed so that they are in the '.2f' format? (I've already tried a few ways and none of them worked).
HOPEFULLY THE FINAL EDIT: I'm getting really close to the solution, but need help with a few more things.
Here is my code:
# Define a function that prompts the user to input names and test scores
score = input('Enter score 1:')
name1 = input('Enter name 1:')
score = input('Enter score 2:')
name2 = input('Enter name 2:')
score = input('Enter score 3:')
name3 = input('Enter name 3:')
score = input('Enter score 4:')
name4 = input('Enter name 4:')
score = input('Enter score 5:')
name5 = input('Enter name 5:')
# Define a function that determines a letter grade
# Based on the given score
def determine_grade(score):
if score < 60:
print ('F')
elif 60 <= score <= 69:
print ('D')
elif 70 <= score <= 79:
print ('C')
elif 80 <= score <= 89:
print ('B')
elif 90 <= score <= 100:
print ('A')
determine_grade(score)
# Define a function that caculates average test scores
def calculate_average(score):
total = score + score + score + score + score
average = total / 5
print(average)
calculate_average(score)
# Define a function that displays a letter grade for each score
# followed by the student's name and the average test score
def display_menu():
print ("Name\t\t\tnumeric grade\t\tlettergrade")
print ("---------------------------------------------------------------")
print ("%s:\t\t\t%f\t\t%s" % ('name1', 'score', determine_grade('score')))
print ("%s:\t\t\t%f\t\t%s" % ('name2', 'score', determine_grade('score')))
print ("%s:\t\t\t%f\t\t%s" % ('name3', 'score', determine_grade('score')))
print ("%s:\t\t\t%f\t\t%s" % ('name4', 'score', determine_grade('score')))
print ("%s:\t\t\t%f\t\t%s" % ('name5', 'score', determine_grade('score')))
print ("---------------------------------------------------------------")
calculate_average(score)
And this is what happens when I press F5:
GUYS, I'M ALMOST DONE JUST NEED HELP WITH FORMATTING:
I created another file so I could reorganize my code a bit, so that's why there's no comments. This is what I have:
score1 = float(input('Enter score 1:'))
name1 = input('Enter name 1:')
score2 = float(input('Enter score 2:'))
name2 = input('Enter name 2:')
score3 = float(input('Enter score 3:'))
name3 = input('Enter name 3:')
score4 = float(input('Enter score 4:'))
name4 = input('Enter name 4:')
score5 = float(input('Enter score 5:'))
name5 = input('Enter name 5:')
def determine_letter_grade1(score1):
if score1 < 60.0:
print ('F')
elif 60.0 <= score1 <= 69.0:
print ('D')
elif 70.0 <= score1 <= 79.0:
print ('C')
elif 80.0 <= score1 <= 89.0:
print ('B')
elif 90.0 <= score1 <= 100.0:
print ('A')
def determine_letter_grade2(score2):
if score2 < 60.0:
print ('F')
elif 60.0 <= score2 <= 69.0:
print ('D')
elif 70.0 <= score2 <= 79.0:
print ('C')
elif 80.0 <= score2 <= 89.0:
print ('B')
elif 90.0 <= score2 <= 100.0:
print ('A')
def determine_letter_grade3(score3):
if score3 < 60.0:
print ('F')
elif 60.0 <= score3 <= 69.0:
print ('D')
elif 70.0 <= score3 <= 79.0:
print ('C')
elif 80.0 <= score3 <= 89.0:
print ('B')
elif 90.0 <= score3 <= 100.0:
print ('A')
def determine_letter_grade4(score4):
if score4 < 60.0:
print ('F')
elif 60.0 <= score4 <= 69.0:
print ('D')
elif 70.0 <= score4 <= 79.0:
print ('C')
elif 80.0 <= score4 <= 89.0:
print ('B')
elif 90.0 <= score4 <= 100.0:
print ('A')
def determine_letter_grade5(score5):
if score5 < 60.0:
print ('F')
elif 60.0 <= score5 <= 69.0:
print ('D')
elif 70.0 <= score5 <= 79.0:
print ('C')
elif 80.0 <= score5 <= 89.0:
print ('B')
elif 90.0 <= score5 <= 100.0:
print ('A')
average = (score1 + score2 + score3 + score4 + score5) / 5.0
def determine_letter_grade_avg(average):
if average < 60.0:
print ('F')
elif 60.0 <= average <= 69.0:
print ('D')
elif 70.0 <= average <= 79.0:
print ('C')
elif 80.0 <= average <= 89.0:
print ('B')
elif 90.0 <= average <= 100.0:
print ('A')
def display_menu():
for x in range(10):
print("{:<10}".format("{:0.1f}".format(x)), end='')
print ("Name\t\t\tnumeric grade\t\tletter grade")
print ("---------------------------------------------------------------")
print ("%s:\t\t\t%f\t\t%s" % (name1, score1, determine_letter_grade1(score1)))
print ("%s:\t\t\t%f\t\t%s" % (name2, score2, determine_letter_grade2(score2)))
print ("%s:\t\t\t%f\t\t%s" % (name3, score3, determine_letter_grade3(score3)))
print ("%s:\t\t\t%f\t\t%s" % (name4, score4, determine_letter_grade4(score4)))
print ("%s:\t\t\t%f\t\t%s" % (name5, score5, determine_letter_grade5(score5)))
print ("---------------------------------------------------------------")
print ('Average Score:', average, determine_letter_grade_avg(average))
And when I run it:
You should be looking towards str.format() and end='' for your print statement
Here's a little example
for x in range(10):
print("{:<10}".format("{:0.1f}".format(x)), end='')
The first part for the rounding to 1 decimal place for your float values is
"{:0.1f}".format(x)
The 0 is for no left padding, the following .1f is for rounding to 1 decimal place. Next is the main part
"{:<10}".format(...)
This will print with a minimum string length of 10 characters. So if you have a string such as Hello it is printed as Hello_____ ( _ to represent empty spaces) The 10 can be changed to a value of your choosing.
Finally the end=''. By default the end parameter is \n which is what creates the new line after each print, but by changing it you can form lines from multiple print statements. Just print normally or set end='\n' when you want to end the line.
Little something to note as well. When checking if a value is between two integers you can use this instead of checking it twice (also you would need and and operator instead of or )
elif 60 <= score <= 69:
You could do something like this:
def display_menu():
print "Name\t\t\tnumeric grade\t\tlettergrade"
print "---------------------------------------------------------------"
print "%s:\t\t\t%f\t\t%s" % ('name1', 50, 'F')
print "%s:\t\t\t%f\t\t%s" % ('name2', 50, 'F')
print "%s:\t\t\t%f\t\t%s" % ('name3', 23, 'F')
print "%s:\t\t\t%f\t\t%s" % ('name4', 44, 'F')
print "%s:\t\t\t%f\t\t%s" % ('name5', 48, 'F')
print "---------------------------------------------------------------"
display_menu()
I used \t to give tabs in between.
This is the screenshot of the PythonShell Output
Well, I just got the solution back, and I did a real butchering on the code. But, I will post this so no one will have to suffer like I did:
# main function
def main():
# Local variables only have to define floats
average = 0.0
score1 = 0.0
score2 = 0.0
score3 = 0.0
score4 = 0.0
score5 = 0.0
# Get scores
score1 = float(input('Enter score 1:'))
name1 = input('Enter name 1:')
score2 = float(input('Enter score 2:'))
name2 = input('Enter name 2:')
score3 = float(input('Enter score 3:'))
name3 = input('Enter name 3:')
score4 = float(input('Enter score 4:'))
name4 = input('Enter name 4:')
score5 = float(input('Enter score 5:'))
name5 = input('Enter name 5:')
# Calculate average grade
average = calculate_average(score1, score2, score3, score4, score5)
#Display grade and average information in tabular form
print('Name\t\tnumeric grade\tletter grade')
print('----------------------------------------------------')
print(name1 + ':\t\t', score1, '\t\t', determine_grade(score1))
print(name2 + ':\t\t', score2, '\t\t', determine_grade(score2))
print(name3 + ':\t\t', score3, '\t\t', determine_grade(score3))
print(name4 + ':\t\t', score4, '\t\t', determine_grade(score4))
print(name5 + ':\t\t', score5, '\t\t', determine_grade(score5))
print('----------------------------------------------------')
print ('Average score:\t', average, '\t\t', \
determine_grade(average))
# The calc_average function returns average of 5 grades
def calculate_average(s1, s2, s3, s4, s5):
return (s1 + s2 + s3 + s4 + s5) / 5.0
# The determine_grade function receives a numeric
# grade and returns the corresponding letter grade
def determine_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
# Call the main function.
main()

Not understanding my python dilemma

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"

Categories