Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to write a simple grading script based off an existing script that i found in a tutorial online. The goal is to ask the user their score and give the corresponding grade.
Here is the original code:
def letterGrade(score):
if score >= 90:
letter = 'A'
else: # grade must be B, C, D or F
if score >= 80:
letter = 'B'
else: # grade must be C, D or F
if score >= 70:
letter = 'C'
else: # grade must D or F
if score >= 60:
letter = 'D'
else:
letter = 'F'
return letter
this btw didnt work at all and i really dont get the "def" command since its not mentioned again? No errors
Anyway, here is my new modified code from what i have been learning from books and online...
score = float(input("What is your score"))
if score >= 90:
letter = 'A'
else: # grade must be B, C, D or F
if score >= 80:
letter = 'B'
else: # grade must be C, D or F
if score >= 70:
letter = 'C'
else: # grade must D or F
if score >= 60:
letter = 'D'
else:
letter = 'F'
print (letter)
input ("Press Enter to Exit")
This code doesnt work either, but at least it is asking for user input now. No errors
What am i missing here?
The def keyword introduces a function. In order for your script to work interactively, can you call the letterGrade function like this:
def letterGrade(score):
if score >= 90:
letter = 'A'
else: # grade must be B, C, D or F
if score >= 80:
letter = 'B'
else: # grade must be C, D or F
if score >= 70:
letter = 'C'
else: # grade must D or F
if score >= 60:
letter = 'D'
else:
letter = 'F'
return letter
if __name__ == '__main__':
score = float(input("What is your score? "))
print letterGrade(score)
input ("Press Enter to Exit")
Here, the __name__ == '__main__': block will be executed when you invoke your script from the command line (python your_script_name.py)
Ok let's first start with some pseudo code, I always try to pseudo code my problems and draw them out as much as possible, it helps me and it might help you. So the grading scale you seem to have implemented is something like this. If you have a grade lower than 100 but greater than or equal to 90 it is an A, lower than 90 but greater than or equal to an 80 it is a b, so on and so on. Let's use conditional statements for this. You can nest it like you had, but setting up the order of conditions may be what you need. So if the grade is not greater than or equal to 90, then the grade can only be lower than 90, thus a B, C, D or F.
if (grade >= 90):
letter = 'A'
elif (grade >= 80):
letter = 'B'
elif (grade >= 70)
letter = 'C'
elif (grade >= 60)
letter = 'D'
else:
letter = 'F'
So with these conditional statements we go through the process of finding the grade, as explained a bit above the code, if the user does not have a grade greater than 90, it hops to the next elif which checks if it is greater than or equal to 80, so on and so on, if grade at one point not greater than or equal to 60, then all other values lower than 60 will be an F.
Now to cover 'def'. You use def to define a function. Here is a generic layout:
def functioname(parameters, parameters):
stuffgoeshere
Now, the parameters are optional, it all depends if you need to pass any data to the function, in your case, you are passing the grade of the user:
def gradeLetter(grade):
if (grade >= 90):
return 'A'
elif (grade >= 80):
return 'B'
elif (grade >= 70)
return 'C'
elif (grade >= 60)
return 'D'
else:
return 'F'
At this point you can call the function, passing in the value the user typed in. We return the character in the function, so that you can assign it to a variable to print it, or you can just print it within the function, whichever is your preference.
g = input("Please enter your grade: ")
l = gradeLetter(g)
print("Your letter grade is " + l)
Hope this helps you out. If you have any questions feel free to comment below.
Since you are a noobie, let me give you a few tips.
1: SO is hostile to easily google-able things
If you google "python def" you'll see that it's the keyword for defining a function. What's a function? google. Oh, a function is a block of code that can be called multiple times.
def letterGrade(score):
if score >= 90:
letter = 'A'
else: # grade must be B, C, D or F
if score >= 80:
letter = 'B'
else: # grade must be C, D or F
if score >= 70:
letter = 'C'
else: # grade must D or F
if score >= 60:
letter = 'D'
else:
letter = 'F'
return letter
print(letterGrade(95)) # A
print(letterGrade(70)) # C
print(letterGrade(20)) # F
2: "else" and "if" can be combined in python:
def letterGrade(score):
if score >= 90:
letter = 'A'
elif score >= 80: # grade must be B, C, D or F
letter = 'B'
elif score >= 70: # grade must be C, D or F
letter = 'C'
elif score >= 60: # grade must D or F
letter = 'D'
else:
letter = 'F'
return letter
Omg hoooooooooooly crap! I need to apologize for wasting everyone's time. RPGillespie was correct, my code was working this entire time. Im new to using PyCharm and for some reason its set up in a way that you can be doing code at the top for one project, but actually "running" the code for a different project at the bottom. Iv been running the wrong code this entire time...day wasted!!! =(
I will say that i wont be making that mistake anymore. Geez, what a fiasco!!!
Thanks again for EVERYONE'S help and warm welcome. I will admit that as i am new to this forum, i am not new to forums in general. And its nice to not get eaten alive for asking a "noob" question or not knowing the un spoken rules of said forum. Its nice to find a place that actually tries to help its members.
My sincerest apologies again, i promise my next problem/question wont be wasting this forums time =).
iv undoubtedly earned the badge of "DOH" and "Facepalm".
Related
I don't understand why I cannot go out from simple loop.
Here is the code:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
elif b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
Thanks for your help.
This should solve your problem:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
if b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
the following condition
if b == '0':
a = 0
should be in the same scope as the if b: condition.
You cant break out of the loop because. actually, there is nobreak. You need to putbreak` command at the end of every loop branch where you would like to stop looping in order to break out of the loop.
Also, you could break out assigning a = 0 instead of the break.
The program is as follows: Write a program that asks the user to input 5 test scores. The program should display a letter grade for each score and the average test score.
I am having issues with my output showing me a letter grade of the first inputted grade for every grade including the average. My numeric average is also being outputted as a letter grade, but it gives the correct average letter for that rather than the correct numeric result for the grade. I am in a low level coding class, therefore the program must be written in this format.
Here is the code:
a=float(input("Enter score 1:"))
b=float(input("Enter score 2:"))
c=float(input("Enter score 3:"))
d=float(input("Enter score 4:"))
e=float(input("Enter score 5:"))
def determine_grade(a,b,c,d,e):
num=a
if(num<=100 and num>=90):
grade='A'
elif(num<=89 and num>=80):
grade='B'
elif(num<=79 and num>=70):
grade='C'
elif(num<=69 and num>=60):
grade='D'
else:
grade='F'
return grade
def calc_average(a,b,c,d,e):
mean=(a+b+c+d+e)//5
if mean<=100 and mean>=90:
avggrade='A'
elif(mean<=89 and mean>=80):
avggrade='B'
elif(mean<=79 and mean>=70):
avggrade='C'
elif(mean<=69 and mean>=60):
avggrade='D'
else:
avggrade='F'
return avggrade
grade=determine_grade(a,b,c,d,e)
avggrade=determine_grade(a,b,c,d,e)
mean=calc_average(a,b,c,d,e)
determine_grade(a,b,c,d,e)
calc_average(a,b,c,d,e)
print("Score Numeric Grade Letter Grade")
print("--------------------------------------------")
print("Score 1: ",a," ",grade)
print("Score 2: ",b," ",grade)
print("Score 3: ",c," ",grade)
print("Score 4: ",d," ",grade)
print("Score 5: ",e," ",grade)
print("--------------------------------------------")
print("Average Score: ",mean," ",avggrade)
Whenever I put in (a):
num=a,b,c,d,e
in place of what is shown in the code, I get a syntax error saying:
TypeError: '<=' not supported between instances of 'tuple' and 'int'
If I don't do what has been shown in (a), my output is this:
Enter score 1:90
Enter score 2:88
Enter score 3:76
Enter score 4:68
Enter score 5:40
Score Numeric Grade Letter Grade
--------------------------------------------
Score 1: 90.0 A
Score 2: 88.0 A
Score 3: 76.0 A
Score 4: 68.0 A
Score 5: 40.0 A
--------------------------------------------
Average Score: C A
Okay, so there's some things to talk about here. First, I suggest that you experiment a bit more with simpler functions to properly get used to them. When you define determine_grade(a,b,c,d,e) your function will expect to find a,b,c,d,e arguments inside the function, but if you read it again, you'll notice that you only mention a. This means when you call grade=determine_grade(a,b,c,d,e) you're only calculating a's grade, and that's why you have the same grade for everyone (if you type grade with your code you'll notice it will output 'A'.
Another way to write a function that does exactly what you're looking for is this:
def determine_grade(score):
num=score
if(num<=100 and num>=90):
grade='A'
elif(num<=89 and num>=80):
grade='B'
elif(num<=79 and num>=70):
grade='C'
elif(num<=69 and num>=60):
grade='D'
else:
grade='F'
return grade
You input a score (that can be a,b,c,d or e) and it calculates a grade. If you want to get everyone's grade, then you can do something like this:
grades=[]
for i in [a,b,c,d,e]:
grades.append(determine_grade(i))
This will bring a list with all grades.
Then, if you want the average grade, it's better to calculate the average score, so you can use your same function to get the grade:
mean_score=np.array([a,b,c]).mean()
mean_grade(determine_grade(mean_score)
Doing this you'll have all the information you need with way less lines of code (And you can make it even more efficient using list comprehensions, but that's a bit more advanced).
To answer your question, your functions should be rewritten to accept a single input and then called several times. Also, your program is a classic case of something that should be DRYed up (Don't Repeat Yourself). Instead of manually typing a = input(), b = input() why not consider just tossing all these inputs into a list (perhaps with some string formatting on your prompt like my code). Below is a program that can easily be adjusted to accept arbitrary amounts of inputs:
input_scores = [] # make our list
scores_input = 5 # tell the program we have 5 scores to record
for input_count in range(1, scores_input + 1):
input_scores.append(float(input("Enter score {}:".format(input_count))))
def determine_grade(percent): # single input
if 90 <= percent <= 100:
grade = 'A'
elif 80 <= percent <= 89:
grade = 'B'
elif 70 <= percent <= 79:
grade = 'C'
elif 60 <= percent <= 69:
grade = 'D'
else:
grade = 'F'
return grade # single output
def calc_average(local_score_list): # expects the list we made earlier (many inputs)
mean = sum(local_score_list) // len(local_score_list)
if 90 <= mean <= 100:
average_grade = 'A'
elif 80 <= mean <= 89:
average_grade = 'B'
elif 70 <= mean <= 79:
average_grade = 'C'
elif 60 <= mean <= 69:
average_grade = 'D'
else:
average_grade = 'F'
return mean, average_grade # have our function return both values, since it calculated them both anyways
compiled_scores = []
for test_score in input_scores:
letter_grade = determine_grade(test_score) # calling our single input/output function many times in a for loop
compiled_scores.append((test_score, letter_grade)) # creating a tuple so each letter and percent is stored together
mean_percent, mean_letter_grade = calc_average(input_scores) # decompile both values from our function
print("Score Numeric Grade Letter Grade")
print("--------------------------------------------")
# now we iterate through all the scores made and print them
for count, result_tuple in enumerate(compiled_scores, 1): # just print the scores in a loop
print("Score {}: ".format(count), result_tuple[0], " ", result_tuple[1])
print("--------------------------------------------")
print("Average Score: ", mean_percent, " ", mean_letter_grade)
You can see that we condensed our input() lines -> a single line, and condensed the print statements as well! Now our program can take, say, 30 scores and work just as well!!! (This is huge)!! And all that is required to change is the number 5 at the top of our script -> 30. No longer will we have to type print('this') or input('that')! Our script will automatically adjust because we made it able to scale with our list.
My test case (using same numbers from your post):
Enter score 1:90
Enter score 2:88
Enter score 3:76
Enter score 4:68
Enter score 5:40
Score Numeric Grade Letter Grade
--------------------------------------------
Score 1: 90.0 A
Score 2: 88.0 B
Score 3: 76.0 C
Score 4: 68.0 D
Score 5: 40.0 F
--------------------------------------------
Average Score: 72.4 C
Let me know if you need further clarification on something I posted!
I am a beginner programmer and am self learning python programming at home from a book. I am currently learning about strings. There is a question there which i solved it but I was thinking if there are other easier ways to solve it.
Q. A certain professor gives 100-point exams that are graded on the scale 90-100:A, 80-89:B, 70-79:C, 60-69:D, <60:F. Write a program that accepts an exam score as input and prints out the corresponding grade.
def main():
## making a list from 0-100
num = list(range(0,101))
## asking for the exam points
points = int(input("Enter the exam points 0-100: "))
## iterating num 0-60
for i in num[0:60]:
if i == points:
print("Your corresponding grade is F.")
## iterating num 60-70
for i in num[60:70]:
if i == points:
print("Your corresponding grade is D.")
## iterating num 70-80
for i in num[70:80]:
if i == points:
print("Your corresponding grade is C.")
## iterating num 80-90
for i in num[80:90]:
if i == points:
print("Your corresponding grade is B.")
## iterating num 90-100
for i in num[90:101]:
if i == points:
print("Your corresponding grade is A.")
main()
Yes, there is a much better way of writing that.
Given that you have an int, which is the score, all you have to do is compare it to the boundaries that determine the grade (using < or >).
points = int(input("Enter the exam points 0-100: "))
if points < 60:
grade = 'F'
elif points < 70:
grade = 'D'
elif points < 80:
grade = 'C'
elif points < 90:
grade = 'B'
else:
grade = 'A'
print("Your corresponding grade is", grade)
To make your code clearer, you can put the comparison logic into a function that returns the grade for a given score.
def calculate_grade(score):
if score < 60:
return 'F'
if score < 70:
return 'D'
if score < 80:
return 'C'
if score < 90:
return 'B'
return 'A'
def main():
points = int(input("Enter the exam points 0-100: "))
grade = calculate_grade(points)
print("Your corresponding grade is", grade)
There's still an easier and more concise way to do this. Try this:
points = int(input("Enter the exam points 0-100: "))
if 0 < points <= 60:
print "Your grade is F"
elif 60 < points <= 70:
print "Your grade is E"
elif 70 < points <= 80:
print "Your grade is D"
[and so on...]
Benefits are:
Plain comparisons instead of heavy linear search
No need to define any kind of dictionaries, methods or even classes or the like (especially since you mentioned you're not that experienced in Python by now)
Exits when it has found the right grade and doesn't evaluate further needless ifs
It is correct (gives the expected grade) and terribly inefficient:
you create an array when it could be avoided
you use linear search in arrays where simple comparisons would be enough
In addition you use a pure linear (unstructured) design.
You could:
make a function that converts points to grade
call it from a main that deals with input and output
Code example
def points_to_grade(points):
limits = [90, 80, 70, 60]
grades = ['A', 'B', 'C', 'D']
for i,limit in enumerate(limits):
if points >= limit:
return grade[i]
return 'F'
def main():
## asking for the exam points
points = int(input("Enter the exam points 0-100: "))
## convert to grade
grade = points_to_grade(points)
print("Your corresponding grade is {}.".format(grade))
#Maybe using dictionaries is more fun :)
marks = {'F':60, 'D':70,'C':80,'B':90}
points = int(input("Enter the exam points 0-100: "))
for key,value in marks.items():
if points<=value:
print("Your corresponding grade is ", key)
break
print("Your corresponding grade is A")
I do not code in python so I might not use right syntax but this is pretty much same in all languages. Iterating trough all values is bad practice. You just need few if statements (or switch/case), something like this:
if i<=100 and i>=90:
print("Grade is A")
if i<=89 and i>=80:
print("Grade is B")
etc....
def main():
points = int(input('Enter the exam points:'))
if points >= 90:
print('Your corresponding grade is A')
elif 80 <= points <= 90:
print('Your corresponding grade is B.')
elif 70 <= points <= 80:
print('Your corresponding grade is C.')
elif 60 <= points <= 70:
print('Your corresponding grade is D.')
elif 0 <= points <= 60:
print('Your corresponding grade is F.')
your solution is pretty not optimal and could be solved really nice using some basic logic, like below, which will perform better and would be more readable:
## asking for the exam points
point = int(input("Enter the exam points 0-100: "))
point_set = 'FEDCBA'
if point == 100:
print('A')
else:
print(point_set[point // 10 - 5])
code is using simple logic, once point is less than 60, 59 // 10 evaluates to 5 and 5 - 5 = 0, so grade at index 0 will be used - F. In case point is 100, this is some edge case, and that's why I'm using special if, for other cases there is simple math, which is self explanatory.
Yes there is, I would have used this approach
def main():
points = int(input("Enter the exam points 0-100: "))
if points >= 60:
print("Your corresponding grade is F.")
elif points > 60 and points < 70:
print("Your corresponding grade is D.")
elif points > 70 and points < 80:
print("Your corresponding grade is C.")
elif points > 80 and points < 90:
print("Your corresponding grade is B.")
elif points > 90:
print("Your corresponding grade is A.")
else:
print("Error: invalid value")
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 6 years ago.
Improve this question
The code:
#Loop to conduct program. User input required for each option.
count = 1
while count == 1:
score = input("Enter Test Score: ")
if (score >= 90) and (score <= 100):
print "A"
elif (score >= 80) and (score <= 89):
print "B"
elif (score >= 70) and (score <= 79):
print "C"
elif (score >= 60) and (score <= 69):
print "D"
elif (score <= 59):
print "F"
elif (score == quit):
print "Program Finsihed. Goodbye."
count = 0 #Count to end loop
else:
print "Please enter valid response."
All other conditions work, however, if something typed it does not meet the parameters, the code is supposed to prompt them again (which is what the while loop is for). However, an error arises whenever a string that does not match the parameters is attempted.
Don't use input. input on Python 2 tries to evaluate the input as a Python expression, so if you type something like fhqwhgads, Python thinks that's supposed to be Python code and throws an error because there's no fhqwhgads variable.
Use raw_input, which gives you the input as a string. You can then perform string operations on it, or (try to) convert it to an integer and handle the exception if the conversion fails:
while True:
user_input = raw_input("Enter Test Score: ")
if user_input == 'quit':
print "Program Finsihed. Goodbye."
break
try:
score = int(user_input)
except ValueError:
print "Please enter valid response."
continue
if 90 <= score <= 100:
print "A"
elif 80 <= score < 90:
...
Incidentally, quit is one of the few choices you could have made for your "we're done here" option that wouldn't have caused an error with your original code, because there's (usually) an actual quit object for that to resolve to when input tries to treat it as Python code.
There were many problems with your code. I think it would be much easier to see and resolve the issues if you break your code down into functional units. I made two functions: get_score deals with prompting the user for input and score_to_grade converts a number score into a letter score. Doing this makes the code much more readable and easier to refactor, debug, etc. in the future.
def get_score():
while True:
user_in = raw_input("Enter Test Score: ")
try:
return float(user_in)
except ValueError:
if user_in == "quit":
print "Program Finished. Goodbye."
raise SystemExit
print "Please enter valid response."
def score_to_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"
while True:
print score_to_grade(get_score())
quit needs to be in quotes, since it is a string, not a variable:
...
elif (score == "quit")
...
Im really stumped. Im writing a program for my teacher (Im using Python 3 btw), so that he can give this code to students to calculate their grade instead of waiting for their report card. I'm only a beginner so try and keep the answer simple please :D
Okay here is the problem. I have all of the inputs needed for the code. the inputs work like this. A = 5 B = 4 C = 3 D = 2 E = 1. If you got straight A's you'd get 50 points, and so on, but if it results in say, 35 points all the grade calculators will crash. Because if its >30 its a B, but if its >20 its a C, But >20 and >30 print at the same time. Because they both execute if the result is greater than 30. And i dont know how to make it so that it will print say, "B" if it is 31 to 40.
This is the code
a = eval(input())
b = eval(input())
c = eval(input())
d = eval(input())
e = eval(input())
f = eval(input())
g = eval(input())
h = eval(input())
i = eval(input())
j = eval(input())
average = a + b + c + d + e + f + g + h + i + j
print(average)
if average >41:
print(" Grade A ")
if average >31:
print(" Grade B")
if average >21:
print(" Grade C")
if average >11 :
print(" Grade D")
if average >0
print(" Grade E")
Any Help Would Be Greatly Appreciated! Thanks.
The best way to do what you want is to define a group of data. if/elif blocks work, but are ungainly, and require a lot of extra typing:
import sys
mark_boundaries = [("A", 41), ("B", 31), ("C", 21), ("D", 11), ("C", 0)]
try:
marks = []
for i in range(10):
marks.append(int(input()))
except ValueError:
print("You entered an invalid mark, it must be a number.")
sys.exit(1)
average = sum(marks) #I'd just like to note the misleading variable name here.
#average = sum(marks)/len(marks) #This would be the actual average mark.
print(average)
for mark, boundary in mark_boundaries:
if average >= boundary:
print("Grade "+mark)
break #We only want to print out the best grade they got.
Here we use a list of tuples to define our boundaries. We check from highest to lowest, breaking out if we match (so it doesn't 'fall through' to the lower scores).
Likewise, you can see that I have used a loop to gather the data in for the marks. A good sign that you are doing something in an inefficient way while programming is that you have copy and pasted (or typed out again and again) a bit of code. This generally means you need to put it in a loop, or make it a function. I also used int(input()) rather than eval(input()), which is a safer option, as it doesn't allow execution of anything the user wants. It also allows us to nicely catch the ValueError exception if the user types in something which isn't a number.
Note that an enterprising individual might look at a list of pair tuples and think a dict would be a good replacement. While true in most cases, in this case, we need to order to be right - in a dict the order is arbitrary, and might lead to us checking lower scores first, giving them a lower mark than they deserve.
Just as a note, it is entirely possible to do
if 31 < average < 41: #Equivalent to `if 31 < average and average < 41:`
print("Grade B")
In python. That said, for this usage, this would mean a lot more typing than using a list and loop or if/elif.
Basically, this is what you want:
if average >41:
print(" Grade A ")
elif average >31:
print(" Grade B")
elif average >21:
print(" Grade C")
elif average >11 :
print(" Grade D")
elif average >0
print(" Grade E")
else
print("You broke the system")
elif is short for else if, so it executes ONLY if the previous if/elif block was not executed.