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.
Related
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
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).
I have tried to write a code where you simply type your test score (out of 100) and it gives you a grade (A,B,C,D..etc). However the code I have written, for some reason, gives me the wrong grade when I give it a random number. for example, I typed 6 and it give me a D (instead of a U).
Here is my code:
score=int(input("What score did you get on your test?"))
if int(0)>=score<=int(39):
print ("You have got a U in your test.")
elif int(40)>=score<=int(49):
print ("You have got a D in your test.")
elif int(50)>=score<= int(59):
print ("You have got a C in your test.")
elif int(60)>=score<= int(69):
print ("You have got a B in your test.")
else:
("You have got an A in your test, well done!")
Your inequalities are incorrect. Currently, the condition for U is
if score is smaller than 0 and smaller than 39
It should be
if score is greater than 0 and smaller than 39
so
if int(0) <= score <= int(39)
However, you can simplify all of your code a considerable amount, as others have pointed out. You can remote the double-sided inequalities and replace them with single ones, remove the int conditions, since you're not expecting any non-ints (the numbers 39, 49 etc. are hardcoded), and you should also add an error message of some kind for any grades below 0 or above 100 (currently, they return a U and A respectively, but it should really be an error).
A better solution:
score=int(input("What score did you get on your test?"))
if score < 0:
print("How did you manage to get less than zero?!")
elif score <= 39:
print ("You have got a U in your test.")
elif score <= 49:
print ("You have got a D in your test.")
elif score <= 59:
print ("You have got a C in your test.")
elif score <= 69:
print ("You have got a B in your test.")
elif score <= 100:
print ("You have got an A in your test, well done!")
else
print ("This isn't a valid grade, it should be between 0 and 100!")
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.
can you tell me whats wrong with this please? I keep getting SyntaxErrors and im not really to sure whats going on becasue im new to the language and have been given very little information from my school work booklet.
score = int(input("What Score did you get?"))
if score <= 39 :
print ("You might want to try a bit harder, you got a grade U.")
if score =>40 and <=49:
print("Good, but you could try a little harder next time. You got a grade D")
if score =>50 and <= 59:
print ("Good Job! You got a grade C")
if score =>60 and <= 69:
print("Great! You got a grade B")
if score =>70:
print ("Excellent! Thats a grade A!")
Python is not English; and will not guess that you are testing against the same variable. You'll have to spell it out instead:
if score >= 40 and score <= 49:
or you can use comparison chaining:
if 40 <= score <= 49:
where Python essentially will do the same thing (it means the same as (40 <= score) and (score <= 49) but you don't have to repeat the score variable or use and anymore).
However, because only ever one test will match if you use a combination of if .. elif .. else branches, you could test for higher values instead, and only need to test for one boundary in each branch:
if score >= 70:
print("Excellent! Thats a grade A!")
elif score >= 60:
print("Great! You got a grade B")
elif score >= 50:
print("Good Job! You got a grade C")
elif score >= 40:
print("Good, but you could try a little harder next time. You got a grade D")
else:
print("You might want to try a bit harder, you got a grade U.")
Note the difference between this and your separate series of if statements; those are not related to one another, while using elif and else very much is.
So if the score is 70 or up, the first test matches and all the tests are skipped. If the score is merely 55, say, then the first two tests don't match, but the third one does, so the remainder is skipped.
If you preferred your ordering, then test for the upper bounds instead of the lower:
if score < 40:
print("You might want to try a bit harder, you got a grade U.")
elif score < 50:
print("Good, but you could try a little harder next time. You got a grade D")
elif score < 60:
print("Good Job! You got a grade C")
elif score < 70:
print("Great! You got a grade B")
else:
print("Excellent! Thats a grade A!")
You are missing three score(s):
if score ==40 and score <=49:
instead of
if score ==40 and <=49:
Final Code:
score = int(input("What Score did you get?"))
if score <= 39 :
print ("You might want to try a bit harder, you got a grade U.")
if score ==40 and score<=49:
print("Good, but you could try a little harder next time. You got a grade D")
if score >=50 and score<= 59:
print ("Good Job! You got a grade C")
if score >=60 and score <= 69:
print("Great! You got a grade B")
if score >=70:
print ("Excellent! Thats a grade A!")
Your Syntax errors are happening here.
if score ==40 and <=49:
print("Good, but you could try a little harder next time. You got a grade D")
if score =>50 and <= 59:
print ("Good Job! You got a grade C")
if score =>60 and <= 69:
print("Great! You got a grade B")
Python's and statement combines 2 boolean statements, in your case:
score =>60
<= 69
while the first one is valid, python does not recognize the second. I am assuming you are comparing the score variable in both cases so you can fix it by adding score next to the second boolean statement like so:
if score ==40 and score <=49:
print("Good, but you could try a little harder next time. You got a grade D")
if score =>50 and score <= 59:
print ("Good Job! You got a grade C")
if score =>60 and score <= 69:
print("Great! You got a grade B")