Finding a class avg within a nested loop - python

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

Related

Need help for python, I cant get it to calculate

I really don't know what I am doing wrong here but whenever I run the code the output doesn't calculate the variable and only sets it to 0.0
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
except ValueError:
print("Invalid Input")
continue
total = total + num
num1 = num1 + 1
average = total / num1
print("total: ", total)
print("count: ", num1)
print("average: ", average)
I got the following after running the code
[Image of code run]: (https://imgur.com/a/lEz6ibh)
Your code isn't indented properly, so the code after continue never gets executed. To get it to work, unindent the lines after continue:
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
except ValueError:
print("Invalid Input")
continue
total = total + num
num1 = num1 + 1
average = total / num1
print("total: ", total)
print("count: ", num1)
print("average: ", average)
This should work.
num_list = []
while True:
input_num = input("Enter a number ")
if input_num == 'done':
total = sum(num_list)
average = total / len(num_list)
break
num_list.append(float(input_num))
print(f"Average: {average}")
print(f"Total: {total}")
print(f"num_list: {num_list}")
total = 0.0
num1 = 0.0
average = 0.0
while True:
input_num = input("Enter a number ")
if input_num == 'done':
break
try:
num = float(input_num)
total = total + num
num1 = num1 + 1
average = total / num1
except ValueError:
print("Invalid Input")
continue
print("total: ", total)
print("count: ", num1)
print("average: ", average)
Your code to calculate values should be inside the try block rather than the except block otherwise they are never executed.

How to make an array to find an average score?

I'm trying to make an average score that lists a student's average score with this:
name = input("Name: ")
first_score = int(input("First score: "))
second_score = int(input("Second score: "))
third_score = int(input("Third score: "))
avg_score = (first_score + second_score + third_score)/3
print("Hello, " + name + ". Your average score is: ")
print(avg_score)
But this is only for one person. How do I record n number of students that I want to input with an array?
Example for the several students:
students_count: int = 2
def input_student():
name = input("Name: ")
first_score = int(input("First score: "))
second_score = int(input("Second score: "))
third_score = int(input("Third score: "))
avg_score = (first_score + second_score + third_score) / 3
return name, avg_score
student_scores = [input_student() for _ in range(0, students_count)]
for name, avg_score in student_scores:
print(f"Hello, {name}. Your average score is: {avg_score}")
For the several scores:
students_count: int = 2
def input_student():
name = input("Name: ")
scores = []
while s := input("Score: "):
scores.append(int(s))
avg_score = sum(scores) / len(scores)
return name, avg_score
student_scores = [input_student() for _ in range(0, students_count)]
for name, avg_score in student_scores:
print(f"Hello, {name}. Your average score is: {avg_score}")
Output for the first code snippet:
Name: 213
First score: 2
Second score: 2
Third score: 3
Name: 123
First score: 2
Second score: 34
Third score: 2
Hello, 213. Your average score is: 2.3333333333333335
Hello, 123. Your average score is: 12.666666666666666

How can I print variable which is int from while loop and if else in Python

The error I get from the program is undefined variable.
*
# Python 3.9.4
# import sys
# print(sys.version)
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
Iterate = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
for i in range(Iterate): # It will run how many time based on Iterate input
Score = float(input("Enter score: "))
Counter = True
while Counter:
if 80 <= Score < 100:
Accumulate1 = Accumulate + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate + 1
elif Score < 50:
Accumulate4 = Accumulate + 1
else:
print("The number is a negative value or incorrect")
Again = input("Enter yes for restarting again or if you want to exit the program please press anything: ")
if Again in ("y", "Y", "YES", "Yes", "yes"):
continue
else:
break
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)
This is my first post in Stackoverflow.
pardon me for any inappropriate content.
Thanks you so much.
You stated
Counter = True
without iteration, thus it will run indefinitely. With while loop you need to set some constraints.
I realised why you had the While loop in there, but it still wasn't working for me effectively - if all answers were within range it never terminated. This should work for you, it does for me. I changed it so it checks every time somebody enters a score that it is within the correct range, so you don't have to repeat the whole loop in the event of incorrect values
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
NoOfStudents = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
Accumulate1 = 0
Accumulate2 = 0
Accumulate3 = 0
Accumulate4 = 0
def validRange(score):
if 0 <= score <=100:
return True
else:
return False
i = 1
while (i <= NoOfStudents): # It will run how many time based on Iterate
validInput = False
while (not validInput):
Score = float(input("Enter score: "))
if ( not validRange(Score)):
print("The number is a negative value or incorrect")
else:
validInput = True
if 80 <= Score < 100:
Accumulate1 = Accumulate1 + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate2 + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate3 + 1
elif Score < 50:
Accumulate4 = Accumulate4 + 1
i = i+1
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)

Finding A Collective Average & Letter Grade For Tests & Assignments

I am using Python 3.4.1 and I am trying to write a code that does the following:
class Student(object):
def __init__(self, name):
self.name, self.grades = name, []
def append_grade(self, grade):
self.grades.append(grade)
def average(self):
return sum(self.grades) / len(self.grades)
def letter_grade(self):
average = self.average()
for value, grade in (90, "A"), (80, "B"), (70, "C"), (60, "D"):
if average >= value:
return grade
else:
return "F"
def main():
print()
a_class = [] # "class" by itself is a reserved word in Python, avoid using
while True:
print()
print('{} students in class so far'.format(len(a_class)))
another_student = input('Do you have another student to enter (y/n) ? ')
if another_student[0].lower() != 'y':
break
print()
student_name = input('What is the student\'s ID? ')
a_class.append(Student(student_name))
print()
print('student :', student_name)
print('------------------------------------------------')
number_of_tests = int(input('Please enter the number of tests : '))
for test_num in range(1, number_of_tests+1):
print('test grade {}'.format(test_num), end='')
score = float(input(' : '))
if score < 0: # stop early?
break
number_of_assignments = int(input('Please enter the number of assignments : '))
for assignment_num in range(1, number_of_assignments+1):
print('assignment grade {}'.format(assignment_num), end='')
score2 = float(input(' : '))
if score2 < 0: # stop early?
break
number_of_participation = int(input('Please enter 1 to add participation grade : '))
for participation_num in range(1, number_of_participation+1):
print('participation grade {}'.format(participation_num), end='')
score3 = float(input(' : '))
if score3 < 0: # stop early?
break
a_class[-1].append_grade(score + score2 + score3) # append to last student added
print_report(a_class)
def print_report(a_class):
print()
print('Student Grades')
print()
for student in sorted(a_class, key=lambda s: s.name):
print('student: {:20s} average test score: {:3.2f} grade: {}'.format(
student.name, student.average(), student.letter_grade()))
print()
print('The class average is {:.2f}'.format(class_average(a_class)))
def class_average(a_class):
return sum(student.average() for student in a_class) / len(a_class)
main()
The task here is to get the letter grade of a student by adding 3 different things and getting the average. I need to be able to input the test scores, assignment scores, and 1 participation grade. Those need to average out and give me a final letter grade. I was able to find out how to do just one set of scores to average but when I added the other scores, the average is wrong. What can I edit here?
I didn't look in great detail, but this:
a_class[-1].append_grade(score + score2 + score3)
...makes me suspect that you are adding a single value to the list of grades, that is above 100%. That might account for your averages being too high.
Instead, you likely should:
a_class[-1].append_grade(score)
a_class[-1].append_grade(score2)
a_class[-1].append_grade(score3)

debugging? calculating grade and get nonetype?

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

Categories

Resources