School test grader - python

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

Related

How To Determine Grades in Python [closed]

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.

Cant get str to work in if-loop Python 3

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.

How to have a percentage chance of a command to run

I have 10 things that I want to be printed if they are picked. However each should have a different percentage chance of happening though.
I tried doing the following:
chance = (random.randint(1,100))
if chance < 20:
print ("20% chance of getting this")
The problem is that if I do another one with say, chance <25, if the randint is 10, wouldn't both the chance <25 and chance <20 both run at the same time?
Here is the code I want to have the chance stuff going on after.
print ("You selected Grand Theft Auto")
gta = input ("To commit GTA input GTA")
if gta in ("gta", "Gta", "GTA"):
EDIT:
Alright so I tried this but it keeps giving 3 outputs.
print ("You selected Grand Thief Auto")
gta = input ("To commit GTA type GTA")
if gta in ("gta", "Gta", "GTA"):
chance = random.randint(0,100)
if chance <= 1:
print ("You stole a Bugatti Veryron")
chance = random.randint(0,100)
if chance <= 5:
print ("You stole a Ferrari Spider")
chance = random.randint(0,100)
if chance <= 10:
print ("You stole a Audi Q7")
chance = random.randint(0,100)
if chance <= 15:
print ("You stole a BMW X6")
chance = random.randint(0,100)
if chance <= 20:
print ("You stole a Jaguar X Type")
chance = random.randint(0,100)
if chance <= 25:
print ("You stole a Ford Mondeo")
chance = random.randint(0,100)
if chance <= 30:
print ("You stole a Audi A3")
chance = random.randint(0,100)
if chance <= 35:
print ("You stole a Ford Fiesta")
chance = random.randint(0,100)
if chance <= 40:
print ("You stole a Skoda Octavia")
chance = random.randint(0,100)
if chance <= 45:
print ("You got caught!")
okay so if you want two mutually exclusive events with one occurring 20% of the time and the other occurring 25% of the time, then
chance = random.randint(1,100)
if chance <= 20:
print("20% chance of getting this")
elif chance <= 20+25:
print("25% change of getting this")
if you want them to be independent and not influence each other, you have to generate another random number.
chance = random.randint(1,100)
if chance <= 20:
print("20% chance of getting this")
chance = random.randint(1,100)
if chance <= 25:
print("25% change of getting this")
You're code is correct. The way to solve this is to first, add an = inside of your first if-statement, as such:
if chance <= 20
The next thing that can be done is to add a return statement at the end of your print, as such:
if (chance <= 20):
print(#Stuff)
return
This return statment will finish doing whatever the program is doing, and return to another task, or just be done.
Finally, the last thing to do is to add all of the other increments, as such:
if (chance <= 20):
print(#Stuff)
return
if (chance <= 25):
print(#Stuff)
return
...
if (chance <= #last_number):
print(#Stuff)
return
It would be wise to be sure that you are bumping everything up as indicated by the odds that you are look for, as well.
Best of luck.

New to python and getting syntax errors, can any one assist me?

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

Program not running at all

I am trying to complete this challenge:
Write a program that allows the user to enter the grade scored in a
programming class (0-100). If the user scored a 100 then notify the
user that they got a perfect score.
★ Modify the program so that if the user scored a 90-100 it informs
the user that they scored an A
★★ Modify the program so that it will notify the user of their letter
grade 0-59 F 60-69 D 70-79 C 80-89 B 90-100 A
What I've tried so far is this:
#!/usr/bin/python
import random
a = lambda: random.randint(0, 100)
if a == 100:
print "You have a perfect score"
if a == range(90, 99):
print "You have scored an A"
if a == range(80, 89):
print "You have scored a B"
if a == range(70, 79):
print "You have scored a C"
if a == range(60, 69):
print "You have scored a D"
if a == range(0, 59):
print "You have scored an F"
Not sure what I did wrong but I'm running Ubuntu 13.10 and this is what happens when I try to run it in terminal:
blurr#blurr-pc:~/code$ chmod u+x gradingprogram.py
blurr#blurr-pc:~/code$ ./gradingprogram.py
The program doesn't run at all.
The program does run, but is does not generate any output, because you are in fact comparing a function to a list, so none of the if statements apply. There are a few problems with your code:
a is a function for generating a random number, not the random number itself. Either remove the lambda:, or call a() and assign the result to some variable.
If you want to actually have the user input a number, use a = int(raw_input())
If you want to check whether a is in the range, use the in keyword, i.e., if a in range(90, 99), or better (more efficient), use if 90 <= a < 100
First a is a function, so you shouldn't try to compare it to a number. Call the function and assign it to a variable. grade = a();
Second you can check if a number is in a range with number > lower and number < upper
You can also use print statements to help debug you code.
#!/usr/bin/python
import random
a = lambda: random.randint(0, 100)
print a
grade = a()
print grade
if grade == 100:
print "You have a perfect score"
if grade >= 90 and grade < 100:
print "You have scored an A"
if grade >= 80 and grade <= 89:
print "You have scored a B"
if grade >= 70 and grade <= 79:
print "You have scored a C"
if grade >= 60 and grade <= 69:
print "You have scored a D"
if grade < 59:
print "You have scored an F"
In this case, type(a) is function - so as #tobias_k says, you have to call it.
func = lambda: random.randint(0, 100)
a = func()
...
# alternatively
a = (lambda: random.randint(0,100))()
....
would almost fix it up.
You'll also need to check you're within a range differently then you have here.
Example:
if a >= lower_bound and a <= upper_bound:
# within range

Categories