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
Related
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 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...)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
This is my first program in Python and I am having some trouble so forgive me if I have some simply syntax issues.
I am writing a program that calculates a student's final score based on one exam grade worth 60% and 7 other test scores worth a combined 40% of the final grade. The user is asked to input the one exam score then asked to input the 7 test scores which are read in a loop. The letter grade is then determined from the final score calculated from the exam and tests. After that a grade comment is printed corresponding to the letter grade given to the student. This is my code so far:
def read_test_scores() :
print("ENTER STUDENT ID: ")
id = int(input())
print("ENTER EXAM SCORE: ")
exam = int(input())
print("ENTER ALL TEST SCORES: ")
score1 = int(input())
score2 = int(input())
score3 = int(input())
score4 = int(input())
score5 = int(input())
score6 = int(input())
score7 = int(input())
sum = (score1 + score2 + score3 + score4 + score5 + score6 + score7)
tavge = sum/7
return tavge
def compute_final_score(tavge, exam) :
final_score = 0.4 * tavge + 0.6 * exam
return final_score
def get_letter_grade(final_score) :
if 90 <= final_score <= 100:
grade = 'A'
elif 80 <= final_score <= 89:
grade = 'B'
elif 70 <= final_score <= 79:
grade = 'C'
elif 60 <= final_score <= 69:
grade = 'D'
else:
grade = 'F'
return grade
def print_comment(grade) :
if grade = 'A':
print "COMMENT: Very Good"
elif grade = 'B':
print "COMMENT: Good"
elif grade = 'C':
print "COMMENT: Satisfactory"
elif grade = 'D':
print "COMMENT: Need Improvement"
elif grade = 'F'
print "COMMENT: Poor"
read_test_scores()
print "TEST AVERAGE IS: " + str(tavge)
compute_final_score()
print "FINAL SCORE IS: " + str(final_score)
get_letter_grade(final_score)
print "LETTER GRADE IS: " + str(grade)
print_comment(grade)
Here's my answer. The code should run. Notes are inserted as comments.
# NOTE: I haven't checked whether your math is right, or
# if the computed values are correct. I did however get your
# script to work.
def read_test_scores():
print("ENTER STUDENT ID: ")
id = int(input())
print("ENTER EXAM SCORE: ")
exam = int(input())
print("ENTER ALL TEST SCORES: ")
score1 = int(input())
score2 = int(input())
score3 = int(input())
score4 = int(input())
score5 = int(input())
score6 = int(input())
score7 = int(input())
sum = (score1 + score2 + score3 + score4 + score5 + score6 + score7)
tavge = sum / 7.0
# NOTE: if you want to use any variables from this function,
# then you have to "bring them outside" by "returning"
# them. Here, I return the values tavge, id, and exam. I noticed
# that bringing out "exam" is necessary since you'll
# be using it later on.
return tavge, id, exam
def compute_final_score(tavge, exam):
final_score = 0.4 * tavge + 0.6 * exam
return final_score
def get_letter_grade(final_score):
if 90 <= final_score <= 100:
grade = 'A'
elif 80 <= final_score <= 89:
grade = 'B'
elif 70 <= final_score <= 79:
grade = 'C'
elif 60 <= final_score <= 69:
grade = 'D'
else:
grade = 'F'
return grade
def print_comment(grade):
# NOTE `=` is for assignment. We use it when we want to
# tell python to make a variable mean something. For example:
# a = "some_name" basically means that when we call a, it would
# return the string "some_name".
# What you want to use here is `==` which is the equality operator.
# This checks whether or thing are equal.
if grade == 'A':
print("COMMENT: Very Good")
elif grade == 'B':
print("COMMENT: Good")
elif grade == 'C':
print("COMMENT: Satisfactory")
elif grade == 'D':
print("COMMENT: Need Improvement")
elif grade == 'F':
print("COMMENT: Poor")
# NOTE 1: you need to assign the function results to a
# variable (or variables), otherwise, the result or return value
# will go nowhere and you can't use it
tavge, id, exam = read_test_scores()
print "TEST AVERAGE IS: " + str(tavge)
# NOTE 2: variable names do not have to be the same as
# the name in their respective functions. Here, you can see
# that it will still run even if I changed the variable
# name final_score to my_variable. Although, of course, using
# final_score would still work.
# NOTE 3: the final_score function requires 2 inputs,
# namely tavge and exam. This basically means that you have to feed
# it with these 2 values for it to work. I took the
# tavge and exam variables as the results from your read_test_scores
# function
my_variable = compute_final_score(tavge, exam)
print("FINAL SCORE IS: " + str(my_variable))
grade = get_letter_grade(my_variable)
print("LETTER GRADE IS: " + str(grade))
print_comment(grade)
# FINAL NOTE: I haven't commented regarding coding style etc (like say
# for instance, there are best practices regarding variable names
# within functions, that is, if they should be similar to variable names
# outside the function), but regardless, the code is a good start. I
# would also advise you to try to narrow down your question first
# before posting. This can be done by running your code, and searching
# the internet for the particular erro messages, and if you're still stuck,
# ask here on stackoverflow.
there are many errors in your code, some of them are in the comment, but the most critical part is that you use global and local variables incorrectly
here is and example of fixing your code using the correct way to use global variables.
https://repl.it/repls/SorrowfulOddballSongbird
tavge = 0
exam = 0
sid = 0
final_score = 0
grade = ''
def read_test_scores() :
global sid
print("ENTER STUDENT ID: ")
sid = int(input())
global exam
print("ENTER EXAM SCORE: ")
exam = int(input())
print("ENTER ALL TEST SCORES: ")
score1 = int(input())
score2 = int(input())
score3 = int(input())
score4 = int(input())
score5 = int(input())
score6 = int(input())
score7 = int(input())
total = (score1 + score2 + score3 + score4 + score5 + score6 + score7)
global tavge
tavge = total/7
#return tavge
def compute_final_score() :
global final_score
final_score = 0.4 * tavge + 0.6 * exam
#return final_score
def get_letter_grade() :
global grade
if 90 <= final_score <= 100:
grade = 'A'
elif 80 <= final_score <= 89:
grade = 'B'
elif 70 <= final_score <= 79:
grade = 'C'
elif 60 <= final_score <= 69:
grade = 'D'
else:
grade = 'F'
#return grade
def print_comment() :
if grade == 'A':
print("COMMENT: Very Good")
elif grade == 'B':
print ("COMMENT: Good")
elif grade == 'C':
print ("COMMENT: Satisfactory")
elif grade == 'D':
print ("COMMENT: Need Improvement")
elif grade == 'F':
print ("COMMENT: Poor")
read_test_scores()
print ("TEST AVERAGE IS: " + str(tavge))
compute_final_score()
print ("FINAL SCORE IS: " + str(final_score))
get_letter_grade()
print ("LETTER GRADE IS: " + str(grade))
print_comment()
but you should consider using parameters instead using globals
As several people have mentioned you need to use == for comparison, you also are missing a colon after one of your if/else.
This is my take on your code. Keep in mind that this doesn't have and tests to make sure someone is actually entering in a number for a test score instead of text
"sum" is also the name of a built in function to Python, which sums up anything you provide it.
def read_test_scores():
scores = []
num_tests = 7
print("ENTER ALL TEST SCORES: ")
for i in range(num_tests):
score = input("Test " + str(i + 1) + ":")
scores.append(int(score))
return sum(scores) / num_tests
def compute_final_score(average, exam_score):
score = 0.4 * average + 0.6 * exam_score
return score
def get_letter_grade(finalized_score):
if 90 <= finalized_score <= 100:
letter_grade = 'A'
elif 80 <= finalized_score <= 89:
letter_grade = 'B'
elif 70 <= finalized_score <= 79:
letter_grade = 'C'
elif 60 <= finalized_score <= 69:
letter_grade = 'D'
else:
letter_grade = 'F'
return letter_grade
def print_comment(letter_grade):
if letter_grade == 'A':
print("COMMENT: Very Good")
elif letter_grade == 'B':
print("COMMENT: Good")
elif letter_grade == 'C':
print("COMMENT: Satisfactory")
elif letter_grade == 'D':
print("COMMENT: Need Improvement")
elif letter_grade == 'F':
print("COMMENT: Poor")
def get_student_id():
print("ENTER STUDENT ID: ")
identity = int(input())
return identity
def get_exam_score():
print("ENTER EXAM SCORE: ")
exam_score = int(input())
return exam_score
if __name__ == '__main__':
student_id = get_student_id()
exam = get_exam_score()
tavge = read_test_scores()
print("TEST AVERAGE IS: " + str(tavge))
final_score = compute_final_score(tavge, exam)
print("FINAL SCORE IS: " + str(final_score))
grade = get_letter_grade(final_score)
print("LETTER GRADE IS: " + str(grade))
print_comment(grade)
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.
I have the program working how I'd like it to, but I cannot seem to figure out how to add validation for the user test score input. The inputs need to be from 0 - 100 and validate each entered score.
How would I modify my code to use a validation loop for input to be >= 0 and <= 100 in the prompt_scores function?
I previously attempted a while loop but it was ignored when placed on each individual input.
def calc_average(scoreOne, scoreTwo, scoreThree):
average = (scoreOne + scoreTwo + scoreThree)/3
return average
def determine_grade(studentScore):
if studentScore < 60:
return "F"
elif studentScore < 70:
return "D"
elif studentScore < 80:
return "C"
elif studentScore < 90:
return "B"
elif studentScore < 101:
return "A"
def prompt_scores():
enteredScoreOne = int(input("Please enter score 1: "))
enteredScoreTwo = int(input("Please enter score 2: "))
enteredScoreThree = int(input("Please enter score 3: "))
return enteredScoreOne, enteredScoreTwo, enteredScoreThree
def print_results(scoreOne, scoreTwo, scoreThree):
print("\nScore\tLetter Grade" )
print(str(scoreOne) + "\t\t" + determine_grade(scoreOne), \
str(scoreTwo) + "\t\t" + determine_grade(scoreTwo), \
str(scoreThree) + "\t\t" + determine_grade(scoreThree), sep = "\n")
def main():
scoreOne, scoreTwo, scoreThree = prompt_scores()
print_results(scoreOne, scoreTwo, scoreThree)
print("-----------------------")
print("Average score: " + str(int(calc_average(scoreOne, scoreTwo,scoreThree))))
print(" Final grade: " + determine_grade(int(calc_average(scoreOne, scoreTwo, scoreThree))))
rerun_main = input("Do you want to continue? Enter y/n: ")
if rerun_main == "Y" or rerun_main == "y":
main()
main()
enteredScoreOne = int(input("Please enter score 1: "))
while enteredScoreOne not in range(0, 101):
print("[!] Invalid input!")
enteredScoreOne = int(input("Please enter score 1: "))
And so on for the other variables.
If you're running Python 2 (given that you're using input to read strings, you're not, but I'll add this just in case), you'd better replace in range(...) with (0 <= enteredScoreOne <= 100) as range would return a list, which would consume a little bit of extra memory.
You can check the entered value while getting input if you use function and can force the user to enter the value between 0-100 using recursion also i can see you are using additional functions for which python itself has a built in eg: sum(). Also try to save memory and processing wherever possible now it may not seem a big issue but when you have 1000 lines of code even these small things will save you. Here i mean instead of calling a function twice you can save the result in a variable and use it. I added all these in my code and have given the answer.
def get_input():
try:
score=int(input("please enter score : "))
if (score >=0 and score <100):
return score
else:
print("Score should be inbetween 0-100. Try again :-(:-(:-(")
get_input()
except:#if user enters any special char except float or int tell him to enter int
print("Only integer is accepted")
def determine_grade(avg):
if studentScore < 60:
return "E"
elif studentScore < 70:
return "D"
elif studentScore < 80:
return "C"
elif studentScore < 90:
return "B"
elif studentScore < 101:
return "A"
def print_results(*args):
for i,j in enumerate(args):
print("score "+str(i)+" = "+str(j)+" grade = "+determine_grade(j))
def main():
score1 = get_input()
score2 = get_input()
score3 = get_input()
print_results(score1, score2, score3)
print("-----------------------")
avg=sum([score1,score2,score3])/3
print("Average score: " + str(avg))
print(" Final grade: " + determine_grade(avg))
rerun_main = input("Do you want to continue? Enter y/n: ")
if rerun_main.lower() == "y":
main()
main()