find average value and above average value using def function in python - python

here is my code so far. I'm not sure whether I do something wrong on the code because the average seems to be wrong. please help me. Thank you
def enter_score ():
results = []
scores = int(input("How many results to enter? : "))
for i in range(scores):
student_name = input("enter student name: ")
student_score = int(input("Please enter score for student " + student_name + " : " ))
results.append(student_score)
results.append(student_name)
print(results)
return results
def calc_average():
total=0
total=total+student_score
average= total/scores
print("the average is ", average)
return
def above_average():
above_average=0
for i in range (scores):
if results [i] > average:
above_average = above_average + 1
print(" the above average score is ", above_average)
return above_average
enter_score()
calc_average()
above_average()

You're making a list results that contains scores and names alternating -- very hard to use. You return that list from enter_score, then completely ignore -- you throw it away! So the other two functions are supposed to work on some magic, or thin air...?
Clearly, the overall flow at the end must instead be:
results = enter_score()
average = calc_average(results)
above_average(results_average)
and calc_average must end with return average.
results is better arranged by replacing the two results.append calls with a single one:
results.append((student_score, student_name))
i.e, make it a list of tuple, not a weird mix of numbers and names.
The other two functions clearly must loop on that list (which they now receive as an argument) to do their respective jobs.
So:
def calc_average(results):
total = 0
for student_score, student_name in results:
total=total+student_score
average= total/float(len(results))
print(average)
return average
and:
def above_average(average, results):
above_average = 0
for student_score, student_name in results:
if student_score > average:
above_average += 1
print(" the number of above average scores is ", above_average)
return above_average

I fixed/ammended your code so that it works:
def enter_score ():
results = []
scores = int(input("How many results to enter? : "))
for i in range(scores):
student_name = input("enter student name: ")
student_score = int(input("Please enter score for student " + student_name + " : " ))
results.append((student_name, student_score))
print(results)
return results
def calc_average(results):
total=0
for student_name, student_score in results:
total=total+student_score
average= total/len(results)
print("the average is ", average)
return average
def above_average(results, average_score):
above_average_no=0
for student_name, student_score in results:
if student_score > average_score:
above_average_no = above_average_no + 1
print(" the above average score is ", above_average_no)
return above_average_no
results = enter_score()
average_score = calc_average(results)
above_average_no = above_average(results, average_score)
I wont provide detailed explanation on what and why things changes. Leave it to you to figure it out. Please note that I tried to make minimal changes to your code. Many things could be improved, such as calculating sum, etc. Hope this helps.

Related

How to fix, TypeError: 'float' object is not iterable

I am trying to write a program that calculates the grades, calculates the average, and shows a error when letters are typed in. I think I am pretty much done with the code, but I am confused on how to fix "TypeError: 'float' object is not iterable" problem.
def calculate_average(total, count):
average = total / count
return average
while 1:
try:
grade = float(input("Enter a test score, or a negative number to get the average: "))
total = sum(grade)
count = len(grade)
if grade < 0:
break
average = calculate_average(total, count)
print("Total: ", total)
print("Average:", round(average))
except ValueError:
print("BRUH")
Obviously you want to user to input multiple numbers. However, in your code the user can only enter a single number and a single foat can obviously not be summed up nor has it a length.
You need a list containing all grades and after the user has entered all grades and entered a negative number you can evaluate that list and calculate the average.
Here is a working example:
def calculate_average(total, count):
average = total / count
return average
while 1:
grades = []
while 1:
inp = input("Enter a test score, or a negative number to get the average: ")
try:
inpGrade = float(inp)
if inpGrade > 0:
grades.append(inpGrade)
elif inpGrade < 0:
break
except ValueError:
print("BRUH")
total = sum(grades)
count = len(grades)
average = calculate_average(total, count)
print("Total: ", total)
print("Average:", round(average))
break

Variables contain 0 and do not take in user input

I try to calculate several properties of students:
the amount of students
the sum of the marks of the students
the lowest, the average and the highest mark they received.
Yet, the variable mark only shows 0.
How can I solve this problem using function but not max() and min()?
mark = 0
a = 0
student = 0
a = int(input("Enter Marks :"))
def maxx():
maxx = 0
for i in range(1, a):
if a> maxx :
maxx = a
return maxx
def minn():
minn = 0
for i in range(1, a):
if a < minn :
minn = a
return minn
while (a >= 0):
mark = mark + a
student = student + 1
a = int(input("Enter Marks :"))
print("Exit")
print("Total students :", student)
print ("The total marks is:", mark)
average = mark/student
print ("The average marks is:", average)
print("The max marks is :", maxx())
print("The min marks is :", minn())
Your code has a lot of problems. One of them is
for i in range(1, a):
This part makes no sense if you want a min or max value. You need to iterate over a list of grades instead.
mark and student are also unnecessary considering they can be replaced by sum and len respectively.
The entire code seems to lack a proper structure. Here's an example implementation. If you are not allowed to use sum or len, you may bring your own mark and student method back, but try not to make a mess and keep it readable:
def maxx(grades):
if (not grades): # if empty, we let the caller know
return None
res = grades[0] # we know the list is not empty
for i in grades:
if i > res:
res = i
return res
def minn(grades):
if (not grades):
return None
res = grades[0]
for i in grades:
if i < res:
res = i
return res
def main():
grades = [] # list of grades
while (True):
grade = int(input("Enter Mark: "))
if (grade < 0): break
grades.append(grade)
student_cnt = len(grades)
total = sum(grades)
print("Exit")
print("Total students :", student_cnt)
print("The total marks is:", total)
print ("The average marks is:", total / student_cnt)
print("The max marks is :", maxx(grades))
print("The min marks is :", minn(grades))
if __name__ == "__main__":
main()
Input/Output:
Enter Mark: 30
Enter Mark: 20
Enter Mark: 10
Enter Mark: 40
Enter Mark: -1
Exit
Total students : 4
The total marks is: 100
The average marks is: 25.0
The max marks is : 40
The min marks is : 10

Get average grade for 10 students - python

I have a program that asks a user to enter a Student NETID and then what grades they got on 5 assignments plus the grade they got on the mid-term and final. It then adds them and divides to get that students average grade which displays in table format.
What I need to do, is loop through that whole process 9 more times. So essentially, Ill be asking 9 more students the same input, which then Ill need to display in the table format.
My question is how would I loop through the process that I have right now 'x' amount of times, then display the average of all students.
This is my code right now:
# x holds the list of grades
x = []
# count of assignments
assignments = 5
# Ask for a student ID from user
NETID = int(input('Enter your 4 digit student NET ID: '))
# fill list with grades from console input
x = [int(input('Please enter the grade you got on assignment {}: '.format(i+1))) for i in range(assignments)]
midTermGrade = int(input('Please enter the grade you got on you Mid-Term: '))
finalGrade = int(input('Please enter the grade you got on you Final: '))
# count average,
average_assignment_grade = (sum(x) + midTermGrade + finalGrade) / 7
print()
print('NET ID \t Average Final Grade')
print('---------------------------------')
for number in range(1):
print(NETID, '\t\t', format(average_assignment_grade, '.1f'),'%')
main()
And this is how it looks on console:
You really did the hardest part. I don't see why you couldn't so the loop of the average. Anyway:
student_count = 5;
A = [student_count]
for id_student in range(student_count):
print("STUDENT #", id_student+1)
# x holds the list of grades
x = []
# count of assignments
assignments = 5
# Ask for a student ID from user
NETID = int(input('Enter your 4 digit student NET ID: '))
# fill list with grades from console input
x = [int(input('Please enter the grade you got on assignment {}: '.format(i+1))) for i in range(assignments)]
midTermGrade = int(input('Please enter the grade you got on you Mid-Term: '))
finalGrade = int(input('Please enter the grade you got on you Final: '))
# count average,
average_assignment_grade = (sum(x) + midTermGrade + finalGrade) / 7
print()
print('NET ID | Average Final Grade')
print('---------------------------------')
for number in range(1):
print(NETID, " | ", format(average_assignment_grade, '.1f'),'%')
A.append(average_assignment_grade);
grades_sum = sum(A)
grades_average = grades_sum / 5;
print("SUM OF ALL STUDENTS = " + grades_sum)
print("AVERAGE OF ALL STUDENTS = " + grades_average)
Update: As suggested above, you should make a function for a single student and loop through that function in another, since SO is not a coding service I won't do that for you, but I think you got the idea.

Printing an average in python, using a list

This code needs to calculate an average to retrieve an integer between 0-100. Any suggestions would be great.
Prompt the user for the number of points they expect to receive
for engagement at the end of class. This number should not be
adjusted by the program (engagement is a total of 302).
Calculate the final based on an average of the quiz scores to
date.
Prompt the user for the various scores. -1 = no more scores, 0 -
zero for that assignment. Keep looping for the grade until the user
enters a -1.
Here is my code, I definitely do not understand lists very well. Probably clearly.
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
list1.append(tot)
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
totalnum+=1
total= total+num
list1.append(num)
average= tot/eng+num
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
print("your average is",average)
If you can use built ins you can just use sum(your_list) / len(your_list) for the average.
If len(your_list) is zero, you will get a ZeroDivisionError, because you just broke math.
It's not clear to me that this is what you're trying to accomplish, but if you just want an average of all the values in the list, you can just do:
average = sum(list)/len(list)
This would return an integer, if you don't want it rounded you could do:
average = sum(list)/float(len(list))
As an aside, you have this:
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
Which could be made simpler, like:
for e in list1:
print e
Python will do the counting for you. :)
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
else:
list1.append(num)
totalnum+=1
total= (num+eng)/tot
print(len(list1))
average = (sum(list1)/tot)*100
counter=0
for e in list1:
print (e)
print("your average is",average)
This is more what I was looking for. Thanks to #Tommy, #SQLnoob, and #Slayer for the tips that I have implemented into the code.

Ask for five values, subtract the lowest and take the average

I'm having trouble with this python code that is supposed to ask for five values, find the minimum value and subtract it and find the average of the remaining four numbers. I want to use a for loop and if anyone can help me also create a list, i can't seem to get that to work either so I'm doing it as you see below
def get_data():
name = raw_input("What is your name: ")
for i in range(5):
scores = int(input("what are your test scores? ")
return name, scores
def low_score(scores):
low = min(scores)
print low
return low, scores
def find_avg(scores, low):
avg = sum(scores)
print name, "your average = ", avg
return avg
name, scores = get_data()
low, scores = low_score(scores)
avg = find_avg(scores, low)
There are a few problems with your approach. Take a look at this while I write some comments:
def get_data():
name = raw_input("What is your name: ")
scores = []
for i in range(5):
scores.append(int(input("what are your test scores? ")))
return name, scores
def drop_low_score(scores):
sorted_scores = sorted(scores)
print "Dropping", sorted_scores[0]
highest_four_scores = sorted_scores[1:]
return scores
def find_avg(scores):
avg = sum(scores) / float(len(scores))
print name, "your average = ", avg
return avg
name, scores = get_data()
scores = drop_low_score(scores)
avg = find_avg(scores)
When you assign the value from input to score, you are overwriting it each time. Here I am appending it to a list I create before the loop.
Think of it like this:
scores = []
for i in range(5):
new_score = int(input("test score?"))
scores.append(new_score)
Each time through the loop you are appending a new value to the list of scores. At the end of the loop you have 5 scores in your list.
The next problem is you are getting the low_score, but you are doing nothing with it. There are a few ways to deal with that. Read about list to find ways to do it. In my code (since the list is so small) I simply sort it and slice the list, cutting off the first one after it is sorted (default sorting is small to large), so it removes the smallest value. You can read up on list slicing too, but this is an example,
>>> my_list = [1, 2, 3, 4]
>>> print my_list[2:]
[3, 4]
>>> print my_list[3:]
[4]
>>> print my_list[:2]
[1, 2]
The last problem is your find_avg which doesn't find an average at all, it is just summing the scores. You need to sum and divide by the number of elements in the list.
You have a missing bracket in the line -
scores = int(input("what are your test scores? ")
I'm guessing that's the source of your problem because you haven't provided any traceback.
In your loop
for i in range(5):
scores = int(input("what are your test scores? ")
you are overwriting scores five times, without saving the previous values.
Maybe you want something like this:
scores = [int(input("what are your test scores? ") for _ in range(5)]
So the whole assignment would boil down to:
scores = [int(input("what are your test scores? ") for _ in range(5)]
print('Your top four average is', (sum(scores)-min(scores))/4.0)
def get_data():
name = raw_input("What is your name: ")
scores = []
for i in range(5):
scores.append(int(input("what are your test scores? ")))
return name, scores
def low_score(scores):
low = min(scores)
print low
return low, scores
def find_avg(scores, low):
indvalue = scores.index(low)
scores.pop(indvalue)
avg = sum(scores)/len(scores)
print name, "your average = ", avg
return avg
name, scores = get_data()
low, scores = low_score(scores)
avg = find_avg(scores, low)
the above code should wrk fine... with minor modifications in your logic

Categories