I am learning python. The question is "Write a grade program using a function called computegrade that takes a score as its parameter and returns a grade as a string."
# Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
# < 0.6 F
How do I get the grades when I run this program? As I am not assigning the grades to any variable. Hence, unable to get the output.
def computegrade():
if score >=0.9:
print('Grade A')
elif score >=0.8 and score<0.9:
print('Grade B')
elif score >=0.7 and score<0.8:
print('Grade C')
elif score >=0.6 and score<0.7:
print('Grade D')
else:
print('Grade F')
score = input('Enter the score: ')
try:
score = float(score)
except:
print('Enter numbers only')
No Error messages, but I unable to see the grades when entering a value
You're not seeing the grades because you're not telling python to run computegrade. If you do
try:
score = float(score)
computegrade()
It'll be done with.
Some observations about the computegrade method. I advise you to make it accept score as an argument
def computegrade(score):
# grade calculations...
Although it works without this - as long as there is a score variable in the same scope, Python takes it - it feels counterintuitive to call a function that requires as score, not passing a score to it.
Also, currently your program accepts grades bigger than 1.0 and smaller than 0.0, which is something you may want to raise an AssertionError in the future. I don't know if that is in the scope of your learning program, but having an
def computegrade():
if score > 1.0 or score < 0.0:
raise AssertionError('Scores must be within the 1.0 and 0.0 range!')
Is a good practice.
def compute_grade(marks):
try:
if float(marks)>1.0 or float(marks)<0.0:
print("Invalid enteries")
else:
if float(marks) >= 0.9:
print("Grade A")
elif float(marks) >= 0.8:
print("Grade B")
elif float(marks) >= 0.7:
print("Grade C")
elif float(marks) >= 0.6:
print("Grade D")
elif float(marks) < 0.6:
print("Grade F")
except:
print("Please enter numeric value")
compute_grade(input("Please enter your marks\n"))
sco = float(input('Enter your score: '))
def compute_grade(score):
if score > 1.0:
s = 'Out of Range!'
return s
elif score >= 0.9:
s = "A"
return s
elif score >= 0.8:
s = 'B'
return s
elif score >= 0.7:
s = 'C'
return s
elif score >= 0.6:
s = 'D'
return s
elif score >= 0.5:
s = 'E'
return s
else:
s = 'Bad score'
return s
sc = compute_grade(sco)
print(sc)
You aren’t calling the function; you have told Python what the function is, but not called it.
What you need to do is
score = float(score)
grade = computegrade()
print(‘Score :’, score,’ Grade :’, grade)
It is better practice to define your function so that it takes a parameter ;
def computegrade( score):
Instead of your current ‘def’ line, and then when you call the function:
grade = computegrade( score)
It is far better practice to write functions with parameters rather than rely on external variables.
You forgot to call the function.
The following is only a definition of the wanted function.
def computegrade():
if score >=0.9:
print('Grade A')
elif score >=0.8 and score<0.9:
print('Grade B')
elif score >=0.7 and score<0.8:
print('Grade C')
elif score >=0.6 and score<0.7:
print('Grade D')
else:
print('Grade F')
You need to call the function for it to be "activated".
You do so by writing:
computegrade()
So i would guess that the resulting code should look like this:
score = input('Enter the score: ')
try:
computegrade()
except:
print('Enter numbers only')
(no need to convert to float, the command input() does it for you...)
Related
Why wouldn't my for loop work? If I put in 0.85 for grade score it'd print out F and error message instead of B. Why is this?
grade=input('Score Grade:')
fg=float(grade)
for fg in range(0,1):
if fg >= 0.9:
print('A')
elif fg>=0.8:
print('B')
elif fg>=0.7:
print('C')
elif fg>=0.6:
print('D')
else:
print('F')
print('error grade out of range')
quit()
You are misusing the range() function. range() is used to iterate over multiple values, not to validate if a number is in a range. You should instead check that fg greater than or equal to 0, or less than or equal to 1. Like this:
grade=input('Score Grade:')
fg=float(grade)
if 0 > fg or 1 < fg:
print('error grade out of range')
quit()
if fg >= 0.9:
print('A')
elif fg>=0.8:
print('B')
elif fg>=0.7:
print('C')
elif fg>=0.6:
print('D')
else:
print('F')
you are doing this for one time you dont need to use a loop
you can do this
grade = float(input('Score Grade:'))
if grade < 1 and grade > 0:
if grade > 0.9:
print('A')
elif grade >= 0.8:
print('B')
elif grade >= 0.7:
print('C')
elif grade >= 0.6:
print('D')
elif grade < 0.6:
print('F')
else:
print('error grade out of range')
quit()
You do not need to use for operator neither range. The simplest solution is:
'''
grade = input("Enter number:")
try:
grade = float(grade)
except:
grade = -1
if grade >= 0.9:
print("A")
elif grade >= 0.8:
print("B")
elif grade >= 0.7:
print("C")
elif grade >= 0.6:
print("D")
elif grade < 0.6:
print("F")
else:
print("Error!")
quit()
'''
I am Writing a program to prompt for a score between 0.0 and 1.0. If the score is out of range print an error. If the score is between 0.0 and 1.0, print a grade using the following table:Score Grade >= 0.9 A>= 0.8 B>= 0.7 C>= 0.6 D< 0.6 F.
To give an example of what it should do at the end it is:
Enter score: 0.95, A
Enter score: perfect, Invalid input
Enter score: 10.0, Invalid input
Enter score: 0.75, C
Enter score: 0.5, F
This is the code I have now:
score = input("Enter Score: ")
try:
score= float(score)
if(score >= 0.0 and score <= 1.0):
if (score>= 0.9):
print("A")
elif (score>= 0.8):
print("B")
elif(score>= 0.7):
print("C")
elif (score>= 0.6):
print("D")
elif (score < 0.6):
print("F")
else:
print("Invalid input")
I cant seem to get it up and running. Any help would be appreciated.
Your try statement probably wants to do two things: verify that the user input can be converted to a float, and that the resulting float is in the range 0-100. Nothing else should be in the try statement.
If the value is not a float or out of range, you can let the loop continue to get another input. Otherwise, you can proceed with a single if statement to map the score to a letter grade.
while True:
score = input("Enter score: ")
try:
score = float(score) # Could raise ValueError
if not (0 <= score <= 1.0):
raise ValueError
except ValueError:
print("invalid input")
else:
break
if (score>= 0.9):
print("A")
elif (score>= 0.8):
print("B")
elif(score>= 0.7):
print("C")
elif (score>= 0.6):
print("D")
else: # Only option left for an in-range value.
print("F")
Strictly speaking, the range check could be moved out of the try statement as well:
while True:
try:
score = float(score)
except ValueError:
print("invalid input")
continue
if 0 <= score <= 1.0:
break
print("invalid input")
I converted the failed range check to a ValueError mainly to have one error message and one place where we use break, rather than an explicit continue. There are several ways to structure it, but the common feature is that you verify that score has a value suitable for the following grade map first.
Green-Avocado has a great answer. I would add a while loop to retry until the input is valid;
# loop until complete
while True:
score = input("Enter Score: ")
# let's try this
try:
score = float(score)
if score >= 0.0 and score <= 1.0:
if score >= 0.9:
print("A")
elif score >= 0.8:
print("B")
elif score >= 0.7:
print("C")
elif score >= 0.6:
print("D")
elif score < 0.6:
print("F")
# exit the loop on completion
break
# else raise an exception
raise
# if problem with float(score) or exception raised
except:
print("Invalid input")
You need an except block after your try block to handle errors.
Instead of printing the error in the last elif, this can be used to handle all errors.
You can manually raise the error using raise.
score = input("Enter Score: ")
try:
score = float(score)
if score >= 0.0 and score <= 1.0:
if score >= 0.9:
print("A")
elif score >= 0.8:
print("B")
elif score >= 0.7:
print("C")
elif score >= 0.6:
print("D")
else:
print("F")
else:
raise
except:
print("Invalid input")
I am trying to print a grade with the score value for instance 0.85
At first I tried like this below:
score = input("Enter Score: ")
float(score)
if 0.0 <= score <= 1.0:
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif score >= 0.6:
print('D')
else:
print('F')
else:
print("ERROR")
But this returns an ERROR message.
Does anyone know why?
I know I can do this like: score = float(input("Enter Score: "))
What the difference?
you didn't store your float(score) in a variable . you can do it this way .
score_string = input("Enter Score: ")
score = float(score_string)
if 0.0 <= score <= 1.0:
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif score >= 0.6:
print('D')
else:
print('F')
else:
print("ERROR")
You can use isinstance(score, float) or type(score).__name__ to check, for example:
score = input("Enter Score: ")
print(type(score).__name__) # str
print(isinstance(score, float))
And you can use the method of eval that parsed and evaluated the variable as a Python expression.
for cur_exp in ('12345', '"abc"', '[1, 3, 5]', '("a", "b", "c")'):
var = eval(cur_exp)
print(type(var).__name__) # int, str, list, tuple
By the way, I think this way is more readable, just for your reference
while 1:
score = float(input("Enter Score: "))
rank = (print('error'), exit()) if not 0.0 <= score <= 1.0 else \
'A' if score >= 0.9 else \
'B' if score >= 0.8 else \
'C' if score >= 0.7 else 'D'
print(rank)
I am writing this program to take a list of input classes along with scores to with them. The goal is to print the class input along with the letter grade associated with the number score input.
However when more than 1 class is put in, it gives me an error saying the sequence index is out of range. Also no matter what score I input it always prints "A" next to the class.
course_list = []
score_list = []
grade_list = []
while True:
course = requestString("Enter a class name or 'q' to quit")
if course == 'q':
break
else:
course_list.append(course)
score = requestString("Enter the class score")
score_list.append(score)
if score >= 90:
grade_list.append(" A")
elif score >= 80:
grade_list.append(" B")
elif score >= 70:
grade_list.append(" C")
elif score >= 60:
grade_list.append(" D")
else:
grade_list.append(" F")
print "-=Class Scores=-"
final_list = [course_list, grade_list]
for i in range(len(course_list)):
final = ''
for j in range(len(final_list)):
final += (final_list[j][i])
print final
This has nothing to do with Jython.
All you have to do is to indent the whole if score [...]-Block to the same level as the score_list.append(score).
The problem with your code is that this block was outside the while-loop, so you extend the course_list and the score_list until the input is q, but only after this is done you take the last score and extend the grade_list once.
So the grade_list always has the length of 1 (or 0, if no course was given) and the indexing final_list[j][i] fails, because it expects the length of the course_list to be equal to the length of the grade_list.
course_list = []
score_list = []
grade_list = []
while True:
course = requestString("Enter a class name or 'q' to quit")
if course == 'q':
break
else:
course_list.append(course)
score = requestString("Enter the class score")
score_list.append(score)
# this has to happen inside the while-loop:
if score >= 90:
grade_list.append(" A")
elif score >= 80:
grade_list.append(" B")
elif score >= 70:
grade_list.append(" C")
elif score >= 60:
grade_list.append(" D")
else:
grade_list.append(" F")
print "-=Class Scores=-"
final_list = [course_list, grade_list]
for i in range(len(course_list)):
final = ''
for j in range(len(final_list)):
final += (final_list[j][i])
print final
I’m trying to make a system where, if you input a number, it tells you what grade it would be, but it doesn’t work.
My code is
percentage = input(“Please input a number”)
if percentage == 100:
Grade = (“A*”)
print (“A”)
elif percentage ==80:
Grade = (“A”)
print (“A”)
elif percentage == 60:
Grade = (“B”)
print (“B”)
elif percentage == 40:
Grade = (“C”)
print (“C”)
else:
Grade == (“D”)
print (“D”)
The error says
NameError: name ‘grade’ is not defined
Help, sorry in advance if I missed something obvious
The below code working in python2.7.
percentage = input("Please input a number")
if percentage == 100:
Grade = ("A*")
print ("A*")
elif percentage ==80:
Grade = ("A")
print ("A")
elif percentage == 60:
Grade = ("B")
print ("B")
elif percentage == 40:
Grade = ("C")
print ("C")
else:
Grade = ("D")
print ("D")
== and = are different operations. == is comparison while = is assignment.
Try the following code:
percentage = int(input("Please input a number"))
if percentage == 100:
grade = "A*"
elif percentage == 80:
grade = "A"
elif percentage == 60:
grade = "B"
elif percentage == 40:
grade = "C"
else:
grade = "D"
print(grade)
Please learn about Comparisons
I think this is what you are trying to achieve:
percentage = int(input("Please input a number: "))
grade = ''
if percentage == 100:
grade = "A*"
elif percentage == 80:
grade = "A"
elif percentage == 60:
grade = "B"
elif percentage == 40:
grade = "C"
else:
grade = "D"
print(grade)
There are a number of things going on here.
Your input is a string, but you're comparing it to an int (always false).
You are only checking exact percentages, what about ranges? In your code, an input percent of 81 would result in a D grade, probably not the result you want for real-world input data.
Try something like this:
from collections import OrderedDict as od
CUTOFFS = od()
CUTOFFS[100.0] = 'A*'
CUTOFFS[80.0] = 'A'
CUTOFFS[60.0] = 'B'
CUTOFFS[40.0] = 'C'
CUTOFFS[0.0] = 'D'
def percent_to_grade(p):
for k, v in CUTOFFS.items():
if k <= float(p):
return v
raise ValueError('Invalid CUTOFFS data')
def get_grade(percent=None):
while True:
if percent is not None:
try:
percent = float(percent)
if percent < 0.0 or percent > 100.0:
percent = None
raise ValueError('Invalid value for percent')
break
except Exception as exc:
print str(exc), 'Trying again ...'
percent = input('What is your grade? ')
##
grade = percent_to_grade(percent)
return grade
def test():
vals = [100, 80, 79.9, 39, 0, -2, 'TBD', None]
for v in vals:
print v, get_grade(v)
print
Run the test function to see this in action:
>>> test()
100 A*
80 A
79.9 B
39 D
0 D
-2 Invalid value for percent Trying again ...
What is your grade? 10
D
TBD could not convert string to float: TBD Trying again ...
What is your grade? 20
D
None What is your grade? 30
D
I gave manual input to the last three so we could see all test cases.