need help finding error on my python code - python

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

Related

python grade calculator to drop lowest score

im working on a python grade calculator for class where i can only use if/else/elif statements to drop the lowest score and then average the scores. this is what i have so far but i dont know how to determine the lowest score from the input using ONLY if/else statements. any help is appreciated!
# Input
sName = str(input("Name of person that we are calculating the grades for: "))
iTest1 = int(input("Test 1: "))
iTest2 = int(input("Test 2: "))
iTest3 = int(input("Test 3: "))
iTest4 = int(input("Test 4: "))
sDrop = str(input("Do you wish to drop the lowest grade Y or N? "))
# Test If Statements
if iTest1 <= 0:
print("Test scores must be greater than 0.")
raise SystemExit
if iTest2 <= 0:
print("Test scores must be greater than 0.")
raise SystemExit
if iTest3 <= 0:
print("Test scores must be greater than 0.")
raise SystemExit
if iTest4 <= 0:
print("Test scores must be greater than 0.")
raise SystemExit
# Drop Lowest If Statements
if sDrop != "Y" or "N" or "y" or "n":
print("Enter Y or N to drop the lowest grade.")
raise SystemExit
# Grade Scale
if score >= 97.0:
grade = "A+"
elif score >= 94.0 and score <= 96.9:
grade = "A"
elif score >= 90.0 and score <= 93.9:
grade = "A-"
elif score >= 87.0 and score <= 89.9:
grade = "B+"
elif score >= 84.0 and score <= 86.9:
grade = "B"
elif score >= 80.0 and score <= 83.9:
grade = "B-"
elif score >= 77.0 and score <= 79.9:
grade = "C+"
elif score >= 74.0 and score <= 76.9:
grade = "C"
elif score >= 70.0 and score <= 73.9:
grade = "C-"
elif score >= 67.0 and score <= 69.9:
grade = "D+"
elif score >= 64.0 and score <= 66.9:
grade = "D"
elif score >= 60.0 and score <= 63.9:
grade = "D-"
else:
grade = "F"
Test the first two to find the smallest of those. Now compare the other two in turn to smallest and update smallest if necessary.
if iTest1 < iTest2:
smallest = iTest1
else:
smallest = iTest2
if iTest3 < smallest:
smallest = iTest3
if iTest4 < smallest:
smallest = iTest4
Of course, all of this is a tedious way to write:
smallest = min([iTest1, iTest2, iTest3, iTest4])

Python for everybody assignment 3.3

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

data type error on 'if' conditional statement

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)

Grade computing program

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

Adding input validation to a function with three separate inputs

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

Categories

Resources