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
Related
So I'm new to this programming thing... But this has me stumped. To the point that I'm wondering if the website I'm running Python on is wrong. (repl.it is the website).
So I did one of those guess the number games as a small fun challenge. This is the code that I came up with:
from random import randint
print ("Welcome to guess the number!")
answer = str(randint(0,100))
print (answer)
print ()
def something():
answerTwo = str(randint(0,100))
print (answerTwo)
idea(answerTwo)
def idea(x):
number = str(input("Guess a number between 0 and 100:"))
if number != x:
if (number > x):
print()
print(number + " is too high!")
print()
idea(x)
elif (number < x):
print()
print(number + " is too low!")
print()
idea(x)
else:
print()
print ("That is correct!")
again = input("Would you like to play again?:")
if again == "yes":
something()
else:
print ("Thanks for playing!")
idea(answer)
On the 4th and 8th line I print out the random number chosen so that I can quickly test to make sure everything works. Then I removed the print functions in the final product and tested again. Except when I removed the print functions it stopped working after some amount of time. For example, it'll say 39 is too low but 40 is too high, which is impossible since they're is no number in between them. If you put the print functions back in it works again, but remove them and it'll start acting up eventually.
I apologize if it's something really obvious but I just don't understand how this is possible.
Here is the github thingy for it
https://gist.github.com/anonymous/4a370664ae8ddb29aec5915eb20e686f
Thanks for your time!
There is no integer i such that 39 < i < 40.
There is however a numeric string s such that "39" < s < "40". Observe:
>>> "39" < "4" < "40"
True
In short: It has nothing to do with your print calls, instead, just work on actual numbers and cast your input to a number using int(). print() can handle numbers just fine.
I already have a code for weighted score.
def weighted_total_score(student_scores):
return((int(student_scores[0])*mid_1_weight)+(int(student_scores[1])*mid_2_weight)+(int(student_scores[2])*final_exam_weight)+(int(student_scores[3])*homework_weight)+(int(student_scores[4][0])*lab_weight)+(int(student_scores[5])*pr_1_weight)+(int(student_scores[6])*pr_2_weight)+(int(student_scores[7])*pr_3_weight)+(int(student_scores[8])*participation_weight))
I would like to call weighted_score in my new function overall_grade. How do i call weighted_score so that it gives me the correct answer? Currently when my code is executed, for example, I am getting F instead of C.
def overall_grade(weighted_total_score):
weighted_total_score=int()
if (weighted_total_score >=93):
print("The overall student grade is A")
elif (90<=weighted_total_score<93):
print("The overall student grade is A-")
elif (87<=weighted_total_score<90):
print("The overall student grade is B+")
elif (83<=weighted_total_score<87):
print("The overall student grade is B")
elif (80<=weighted_total_score<83):
print("The overall student grade is B-")
elif (77<=weighted_total_score<80):
print("The overall student grade is C+")
elif (73<=weighted_total_score<77):
print("The overall student grade is C")
elif (70<=weighted_total_score<73):
print("The overall student grade is C-")
elif (67<=weighted_total_score<70):
print("The overall student grade is D+")
elif (63<=weighted_total_score<67):
print("The overall student grade is D")
elif (60<=weighted_total_score<63):
print("The overall student grade is D-")
elif (weighted_total_score<60):
print("The overall student grade is F")
Problem is
weighted_total_score=int()
This will make weighted_total_score as 0
It should be
wt_score=weighted_total_score(student_scores)
Also change the variable name from weighted_total_score to something else as the function already has that name
How do i call weighted_score?
You call it like any other method...
def overall_grade(scores):
score = weighted_total_score(scores)
Note Don't name your variables or parameters weighted_total_score because you have a method with that name already. If you referenced your local variables, they would shadow that method, which is generally not good and causes confusion for beginners.
The reason you get F is because weighted_total_score=int() is the same as weighted_total_score=0, and your if statements go all the way to the bottom.
Also, tip, you actually don't need both boundaries in your conditions because the condition can "fall through".
And a suggestion, try to write simple methods, then build on top of them. Don't do too much at once. For example, make a method that only returns the letter grade, then have the method that prints the string and uses the result of the other method.
def get_letter_grade(score):
if (93 <= score):
return "A"
elif (90 <= score): # already < 93
return "A-"
elif (87 <= score): # already < 90
return "B+"
# ... etc
else: # < 60
return "F"
def overall_grade(scores):
weighted_score = weighted_total_score(scores)
print("The overall grade is {}".format(get_letter_grade(weighted_score)))
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!")
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.
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")