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)))
Related
def calc_average(a,b,c,d,f):#function used to calculate average
return (a+b+c+d+f)//5
def determine_grade(test_score):#function used to determine letter grade
if gradeAverage > 89:
return "A"
elif gradeAverage > 79:
return "B"
elif gradeAverage > 69:
return "C"
elif gradeAverage > 59:
return "D"
else:
return "F"
test1 = float(input("Please enter test score for test1: "))#prompt user to enter grade
test2 = float(input("Please enter test score for test2: "))#prompt user to enter grade
test3 = float(input("Please enter test score for test3: "))#prompt user to enter grade
test4 = float(input("Please enter test score for test4: "))#prompt user to enter grade
test5 = float(input("Please enter test score for test5: "))#prompt user to enter grade
gradeAverage = calc_average(test1, test2, test3, test4, test5)#variable
finalgrade = determine_grade(gradeAverage)#variable
print(finalgrade)#display grade
print(gradeAverage)display grade letter
This is a problem in the "starting out with Python" book, I am supposed to calculate the average grade of 5 test scores and give a letter grade. My problem is, I wonder if I need the variables or not. If there is a better way I would like to know.
You can use for loops and lists to eliminate some variables and also generalize a bit:
def calc_average(grades): #function used to calculate average, now takes a list
return sum(grades)//len(grades)
grades = []
number_of_tests = int(input("input the total number of test results >>"))
for i in range(1, number_of_tests+1):
g = int(input("input grade " + str(i) +" >>"))
grades.append(g)
avg = calc_average(grades)
print(avg)
I would explain everything in detail, but I am sure your text book will soon enough tell you about "for loops", "lists", and so on. They usually start slow, and let you do unnecessary work so you can get used to the basics. Keep on reading m8 :)
(Or watch this video, in my opinion this is one of the best beginners guides out there: https://youtu.be/rfscVS0vtbw)
Please allow me to share a few comments:
The function determine_grade(test_score) takes in a parameter test_score, and should be using this parameter to determine the grade, instead of the global parameter gradeAverage. So your code should be:
def determine_grade(test_score):#function used to determine letter grade
if test_score > 89:
return "A"
elif test_score > 79:
return "B"
elif test_score > 69:
return "C"
elif test_score > 59:
return "D"
else:
return "F"
The calculation for average should not be a floor division (a+b+c+d+f)//5. This floor division formula outputs only the integer value and ignores the decimals behind. So the formula should be (a+b+c+d+f)/5.
A for loop would be elegant, and avoiding repeated codes. Then a list test_list could be used to store the test scores and be passed to the function calc_average to calculate the average.
The final code should look like this:
def calc_average(test_list): #function used to calculate average
return sum(test_list)/len(test_list)
def determine_grade(test_score): #function used to determine letter grade
if test_score > 89:
return "A"
elif test_score > 79:
return "B"
elif test_score > 69:
return "C"
elif test_score > 59:
return "D"
else:
return "F"
n = 5
test_list = []
for i in range(n):
score = float(input("Please enter test score for test{}: ".format(i+1))) #prompt user to enter grade
test_list.append(score)
gradeAverage = calc_average(test_list) #variable
finalgrade = determine_grade(gradeAverage) #variable
print(finalgrade) #display grade
print(gradeAverage) #display grade letter
Output
Please enter test score for test1: 66
Please enter test score for test2: 77
Please enter test score for test3: 88
Please enter test score for test4: 86
Please enter test score for test5: 69
C
77.2
I want to make this easier so the user wont have to re-input their data for a second time to get the results. It was easier for myself to separate the functions as they have two different purposes but if possible I don't want the user to have to re input data as it can be a long and tedious process to repeat.
def scores():
''' print('we are starting')
count = int(input('Enter amount of scores: '))
print('Each will be entered one per line')
scoreList = []
for i in range(1, count+1):
scoreList.append(int(input('Enter score: '))) '''
for score in scoreList:
if score >= 91:
print('A')
elif score >= 81 and score <=90:
print('B')
elif score >= 71 and score <=80:
print('C')
elif score >= 61 and score <=70:
print('D')
else:
print('F')
Within the quote section, that is what I have in the previous funtcion but Ive been fiddling with the idea of just targeting the scoreList and seeing if that will carry down to the next function but I'm not sure how
Return the list from the first function, and accept the score list as a parameter for the second function.
def get_scores():
print('we are starting')
count = int(input('Enter amount of scores: '))
print('Each will be entered one per line')
scoreList = []
for i in range(1, count+1):
scoreList.append(int(input('Enter score: ')))
return scoreList
def grade_scores(scoreList):
for score in scoreList:
if score >= 91:
print('A')
elif score >= 81 and score <=90:
print('B')
elif score >= 71 and score <=80:
print('C')
elif score >= 61 and score <=70:
print('D')
else:
print('F')
scores = get_scores()
grade_scores(scores)
You have to decide if you want to do this the easy way, or the hard but more beautiful way.
The easy escaping way would be defining a global variable, passing it into both functions so the user only has to enter once. You can use this for small programs or single projects.
However, the best way would be defining a Score or Student class, define methods then, create a student instance with a score assigned to it. Than you can call those methods on that student object.
For a beginner, using a global variable is maybe the best way, but Classes are important parts of Python and OOP, and one should learn it sooner than later.
Given in your question, you should probably unite them as a single function. Otherwise, as your question title suggests, use the result of the first function in the second one.
Write a function called evaluate_letter_grade which accepts a single float argument (representing the student's grade) and returns a string which represents the corresponding letter grade. Letter grades are assigned as follows:
Grade Letter
90-100 A
80-89.99 B
70-79.99 C
60-69.99 D
0-59.99 F
Greater than 100 or less than 0 Z
I think I have created my function correctly (maybe), but I can not figure out how to get it to output the correct letter grade. Any suggestions?
This is what I have:
def evaluate_letter_grade(grade, lettergrade):
if grade >= 90 or grade <= 100:
lettergrade = "A"
elif grade >= 80 or grade <= 89.99:
lettergrade = "B"
elif grade >= 70 or grade <= 79.99:
lettergrade = "C"
elif grade >= 60 or grade <= 69.99:
lettergrade = "D"
elif grade >= 0 or grade <= 59.99:
lettergrade = "F"
else:
lettergrade = "Z"
return lettergrade
grade = float(input("Enter the student's grade: "))
evaluate = evaluate_letter_grade(grade, lettergrade)
finalgrade = evaluate
print finalgrade
Your function is correct as you have written it, except you only want one input parameter, grade, the float value of the grade.
Also, why not simply condense:
evaluate = evaluate_letter_grade(grade, lettergrade)
finalgrade = evaluate
print finalgrade
to:
print evaluate_letter_grade(grade)
I think I have created my function correctly (maybe), but I can not figure out how to get it to output the correct letter grade.
Whatever is in your return statement is the "output". In this case you are passing in float values and returning a String. Your function will "resolve" to that return value from which you can assign it to other variables or pass it as a parameter (as you did with the print function).
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.
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