debugging? calculating grade and get nonetype? - python

keep on getting error report
File "/home/hilld5/DenicaHillPP4.py", line 72, in main
gradeReport = gradeReport + "\n" + studentName + ":\t%6.1f"%studentScore+"\t"+studentGrade TypeError: cannot concatenate 'str' and 'NoneType' objects
but can't seem to figure out why student grade is returning nothing
studentName = ""
studentScore = ""
def getExamPoints (total): #calculates Exam grade
total = 0.0
for i in range (4):
examPoints = input ("Enter exam " + str(i+1) + " score for " + studentName + ": ")
total += int(examPoints)
total = total/.50
total = total * 100
return total
def getHomeworkPoints (total):#calculates homework grade
total = 0.0
for i in range (5):
hwPoints = input ("Enter homework " + str(i+1) + " score for " + studentName + ": ")
total += int(hwPoints)
total = total/.10
total = total * 100
return total
def getProjectPoints (total): #calculates project grade
total = 0.0
for i in range (3):
projectPoints = input ("Enter project " + str(i+1) + " score for " + studentName + ": ")
total += int(projectPoints)
total = total/.40
total = total * 100
return total
def computeGrade (total): #calculates grade
if studentScore>=90:
grade='A'
elif studentScore>=80 and studentScore<=89:
grade='B'
elif studentScore>=70 and studentScore<=79:
grade='C'
elif studentScore>=60 and studentScore<=69:
grade='D'
else:
grade='F'
def main ( ):
classAverage = 0.0 # initialize averages
classAvgGrade = "C"
studentScore = 0.0
classTotal = 0.0
studentCount = 0
gradeReport = "\n\nStudent\tScore\tGrade\n============================\n"
studentName = raw_input ("Enter the next student's name, 'quit' when done: ")
while studentName != "quit":
studentCount = studentCount + 1
examPoints = getExamPoints (studentName)
hwPoints = getHomeworkPoints (studentName)
projectPoints = getProjectPoints (studentName)
studentScore = examPoints + hwPoints + projectPoints
studentGrade = computeGrade (studentScore)
gradeReport = gradeReport + "\n" + studentName + ":\t%6.1f"%studentScore+"\t"+studentGrade
classTotal = classTotal + studentScore
studentName = raw_input ("Enter the next student's name, 'quit' when done: ")
print gradeReport
classAverage = int ( round (classTotal/studentCount) )
# call the grade computation function to determine average class grade
classAvgGrade = computeGrade ( classAverage )
print "Average class score: " , classAverage, "\nAverage class grade: ", classAvgGrade
main ( ) # Launch

You have two errors in your computeGrade function:
You do not reference the function's single parameter (total) anywhere in the function.
The function has no return statement.
A corrected version might look like:
def computeGrade (studentScore): #calculates grade
if studentScore>=90:
grade='A'
elif studentScore>=80 and studentScore<=89:
grade='B'
elif studentScore>=70 and studentScore<=79:
grade='C'
elif studentScore>=60 and studentScore<=69:
grade='D'
else:
grade='F'
return grade

Related

Append is adding the sum instead of adding to a list python

I tried to append but whenever I would try to print it down in the main(), it would print the average but added up.
def letter_grade(test_score):
if int(test_score) >= 90:
grade = 'A'
elif int(test_score) >= 80:
grade = 'B'
elif int(test_score) >= 70:
grade = 'C'
elif int(test_score) >= 60:
grade = 'D'
else:
grade = 'F'
return grade
def calc_avg_grade(test_score):
average = []
func_sum = sum(test_score)
avg = func_sum/5.00
average.append(avg)
average.reverse()
return average
def main():
grades = []
i = 0
outfile = open('studentgrades.txt', 'w')
while i < 4:
name = input("Enter the student name: ")
for x in range(5):
score = float(input("Enter number grade: "))
grades.append(score)
gradle = letter_grade(score)
print(str(score) + ' - ' + gradle)
avg_grade = calc_avg_grade(grades)
avgg = avg_grade
print(name + "'s average grade is: " + str(avgg))
outfile.write(name + ', ' + str(avg_grade) + "\n")
txtcontents = outfile.read()
print(txtcontents)
if __name__ == "__main__":
main()
The part where it runs the append that I have the problem at is:
print(name + "'s average grade is: " + str(avgg))
This is def main().
I think that you are not reinitialising grades:
def main():
# grades = [] # Not Here!
i = 0
outfile = open('studentgrades.txt', 'w')
while i < 4:
name = input("Enter the student name: ")
grades = [] # here instead
for x in range(5):
score = float(input("Enter number grade: "))
grades.append(score)
gradle = letter_grade(score)
print(str(score) + ' - ' + gradle)
avg_grade = calc_avg_grade(grades)
avgg = avg_grade
print(name + "'s average grade is: " + str(avgg))
outfile.write(name + ', ' + str(avg_grade) + "\n")
txtcontents = outfile.read()
print(txtcontents)
This way you get a new empty grades for each student and avg_grade will be the right average for that student.

Avoiding using / overwriting global variables (with simple example)

TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
requestedTickets = ticketsWanted(userName)
def calculateCost():
ticketQuantity = requestedTickets
totalCost = ticketQuantity * TICKETPRICE
return totalCost
costOfTickets = calculateCost()
def confirm():
global requestedTickets
global costOfTickets
tickets = requestedTickets
totalCost = calculateCost()
print("Okay so that will be " + str(tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/N) : ")
while confirmationResponse == "n":
requestedTickets = ticketsWanted(userName)
costOfTickets = calculateCost()
print("Okay so that will be " + str(requestedTickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/N) : ")
confirm()
def finalStage():
print("Your order is being processed.")
finalStage()
This is a simple program that:
Asks a user how many tickets they want
Calculates the cost of the tickets
Then asks if it's okay to go ahead with the purchase
How could I change the way I'm doing things to not have to overwrite the requestedTickets and costOfTickets global variables?
(they're being overwritten in the confirm function, if a user replies with an "n" declining the confirmation of purchase.)
I'm trying to learn best practices.
TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
def calculateCost(n_tickets):
totalCost = n_tickets * TICKETPRICE
return totalCost
def confirm(userName):
n_tickets = ticketsWanted(userName)
totalCost = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/n) : ")
while confirmationResponse == "n":
n_tickets = ticketsWanted(userName)
costOfTickets = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/n) : ")
def finalStage():
print("Your order is being processed.")
confirm(userName)
finalStage()

How to count the numbers of A's, B's, C's, D's and F's in average score calculator?

I am attempting to write a Python script that calculates the average score and the numbers of A's, B's, C's, D's and F's from a user input number of exams and exam scores.
I've tried a variety of methods for the part of the script currently in the function:
"def letter_score(scores):"
but have had no success with being able to assign the input exam grades with their corresponding letters.
sum_of_scores = 0
number_of_exams = int(input("What is the size of the class? "))
print("Now enter the scores below.")
for i in range(1, number_of_exams + 1):
scores = int(input("Student %d : " %(i)))
sum_of_scores += scores
def letter_score(scores):
if scores >= 90:
scores = "A"
elif scores < 90 and scores >= 80:
scores = "B"
elif scores < 80 and scores >= 70:
scores = "C"
elif scores < 70 and scores >= 60:
scores = "D"
else:
scores = "F"
average_score = sum_of_scores/number_of_exams
print("The average is " + str(average_score))
print("There are " + str(scores) + " A's.")
print("There are " + str(scores) + " B's.")
print("There are " + str(scores) + " C's.")
print("There are " + str(scores) + " D's.")
print("There are " + str(scores) + " F's.")
I was successful in finding the average score, but the letter grades are giving me trouble.
Consider using python dictionary to store the count of letter_score
You can initialize the dictionary with all 0 by:
letter_score_count = { "A": 0, "B": 0, "C": 0, "D": 0, "F": 0}
Give return value in the function letter_score using return keyword
def letter_score(scores):
if scores >= 90:
return "A"
elif scores < 90 and scores >= 80:
return "B"
elif scores < 80 and scores >= 70:
return "C"
elif scores < 70 and scores >= 60:
return "D"
else:
return"F"
By then, call the letter_score method, use the result as the key of dictionary to increase the counter of each letter score when inputting the scores
letter_score_count[letter_score(scores)] += 1
In the end, you can print the result
print("There are " + str(letter_score_count["A"]) + " A's.")
The edited version from your code. Hope this help
sum_of_scores = 0
number_of_exams = int(input("What is the size of the class? "))
print("Now enter the scores below.")
letter_score_count = { "A": 0, "B": 0, "C": 0, "D": 0, "F": 0}
def letter_score(scores):
if scores >= 90:
return "A"
elif scores < 90 and scores >= 80:
return "B"
elif scores < 80 and scores >= 70:
return "C"
elif scores < 70 and scores >= 60:
return "D"
else:
return"F"
for i in range(1, number_of_exams + 1):
scores = int(input("Student %d : " % (i)))
sum_of_scores += scores
letter_score_count[letter_score(scores)] += 1
average_score = sum_of_scores / number_of_exams
print("The average is " + str(average_score))
print("There are " + str(letter_score_count["A"]) + " A's.")
print("There are " + str(letter_score_count["B"]) + " B's.")
print("There are " + str(letter_score_count["C"]) + " C's.")
print("There are " + str(letter_score_count["D"]) + " D's.")
print("There are " + str(letter_score_count["F"]) + " F's.")
Let me know if this helps. You need to include count logic in your letter score function.
from collections import defaultdict
def letter_score(scores,counter_store):
if scores >= 90:
scores = "A"
counter_store["A"]+=1
elif scores < 90 and scores >= 80:
scores = "B"
counter_store["B"]+=1
elif scores < 80 and scores >= 70:
scores = "C"
counter_store["C"]+=1
elif scores < 70 and scores >= 60:
scores = "D"
counter_store["D"]+=1
else:
scores = "F"
counter_store["F"]+=1
return(counter_store)
sum_of_scores = 0
counter_store=defaultdict(int)
number_of_exams = int(input("What is the size of the class? "))
print("Now enter the scores below.")
for i in range(1, number_of_exams + 1):
scores = int(input("Student %d : " %(i)))
score_count=letter_score(scores,counter_store)
sum_of_scores += scores
average_score = sum_of_scores/number_of_exams
print("The average is " + str(average_score))
print("There are " + str(counter_store["A"]) + " A's.")
print("There are " + str(counter_store["B"]) + " B's.")
print("There are " + str(counter_store["C"]) + " C's.")
print("There are " + str(counter_store["D"]) + " D's.")
print("There are " + str(counter_store["F"]) + " F's.")

Finding a class avg within a nested loop

I am working a small practice program that will allow you to input the 3 test scores in for as many students as you'd like and at the end I would like it to calculate the average between all the students. I am able to enter all the students name and scores and it will give me back their average but when you enter "*" it only calculates the last students average and I was trying to figure out how to make it calculate all the students average from their test scores
def GetPosInt():
nameone = str
while nameone != "*":
nameone =(input("Please enter a student name or '*' to finish: "))
if nameone != "*":
scoreone = int(input("Please enter a score for " + nameone +": "))
if scoreone < 0:
print("positive integers please!")
break
else:
scoretwo = float(input("Please enter another score for "+nameone+": "))
scorethree = float(input("Please enter another score for "+nameone+": "))
testscores = scoreone + scoretwo + scorethree
avg = testscores / 3
print("The average score for",nameone,"is ",avg)
classtotal = avg
if nameone == "*":
classavg = classtotal / 3
print("The class average is: ",classavg)
# main
def main():
GetPosInt()
main()
Here's a simplified version of your code that uses lists to store data for multiple students and then displays these details at the end, and also calculates the class average (comments inlined).
def GetPosInt():
names = [] # declare the lists you'll use to store data later on
avgs = []
while True:
name = ...
if name != "*":
score1 = ...
score2 = ...
score3 = ...
avg = (score1 + score2 + score3) / 3 # calculate the student average
# append student details in the list
names.append(name)
avgs.append(avg)
else:
break
for name, avg in zip(names, avgs): # print student-wise average
print(name, avg)
class_avg = sum(avg) / len(avg) # class average
COLDSPEED sent you a solution for your question while I was working on it. If you want to see a different solution. It's here... You can put conditions for the scores.
def GetPosInt():
numberOfStudents = 0.0
classtotal = 0.0
classavg = 0.0
while(True):
nam = (raw_input("Please enter a student name or '*' to finish "))
if(nam == '*'):
print("The average of the class is " + str(classavg))
break
numberOfStudents += 1.0
scoreone = float(input("Please enter the first score for " + str(nam) + ": "))
scoretwo = float(input("Please enter the second score for " + str(nam) + ": "))
scorethree = float(input("Please enter the third score for " + str(nam) + ": "))
testscores = scoreone + scoretwo + scorethree
avg = testscores / 3.0
print("The average score for " + str(nam) + " is " + str(avg))
classtotal += avg
classavg = classtotal / numberOfStudents
def main():
GetPosInt()
main()

bug while trying to create a function from other functions in python

I have been trying to create a calculator and i had for practical reasons i tried to import functions from a separate python file. It works at some extent but it breaks when it tries to do the calculations. The bug is is that the add is not defined but i did defined it while importing the function. Here is the code:
class Calculator(object):
import a10 as add
import d10 as div
import m10 as mult
import s10 as sub
def choice(self):
print("A. Addition\l B. Substraction\l C. Division\l D. Multiplication")
xn = input("What do you want to do? ")
if xn == "a":
addition = add.addition
x = self.addition()
self.x = x
return x
elif xn == "b":
subtraction = sub.subtraction
z = self.subtraction()
self.z = z
return z
elif xn == "c":
division = div.division
y = self.division()
self.y = y
return y
elif xn == 'd':
Multiplication = mult.multiplication
v = self.Multiplication()
self.v = v
return v
objcalc = Calculator()
print(objcalc.choice())
Here is the a10
def addition(self):
try:
n = int(input("enter number: "))
n_for_add = int(input("What do you want to add on " + str(n) + " ? "))
except ValueError:
print("you must enter an integer!")
n_from_add = n + n_for_add
print(str(n) + " plus " + str(n_for_add) + " equals to " + str(n_from_add))
s10
def subtraction(self):
try:
nu = int(input("enter number: "))
nu_for_sub = int(input("What do you want to take off " + str(nu) + " ? "))
except ValueError:
print("you must enter an integer!")
nu_from_sub = nu - nu_for_sub
print(str(nu) + " minus " + str(nu_for_sub) + " equals to " + str(nu_from_sub))
m10
def Multiplication(self):
try:
numb = int(input("enter number: "))
numb_for_multi = int(input("What do you want to multiply " + str(numb) + " on? "))
except ValueError:
print("you must enter an integer!")
numb_from_multi = numb * numb_for_multi
print(str(numb) + " multiplied by " + str(numb_for_multi) + " equals to " + str(numb_from_multi))
d10
def division(self):
try:
num = int(input("enter number: "))
num_for_div = int(input("What do you want to divide " + str(num) + " off? "))
except ValueError:
print("you must enter an integer!")
num_from_div = num / num_for_div
print(str(num) + " divided by " + str(num_for_div) + " equals to " + str(num_from_div))
In the if statements, like this:
if xn == "a":
addition = add.addition
x = self.addition()
self.x = x
return x
addition is created as a variable local to the function choice, but you're then setting x to be self.addition(), which isn't defined.
If you mean to write x = add.addition() then be warned that your addition function doesn't return anything, it just prints out a value. The same for the other functions - none of them return anything. So self.addition is not defined, and x will be a NoneType object
Your addition, subtraction and other functions also take self as an argument, when they're not methods in a class, so this doesn't make much sense.

Categories

Resources