I can't seem to figure this out - I want to get the average of all the inputs at the end of this program but I don't know how to save the inputs with each iteration of the loop. Any help would be much appreciated, thanks!
students = int(input("How many students are in your class?"))
while students <= 0:
print ("Invalid # of students. Try again.")
students = int(input("How many students are in your class?"))
studentnum = 1
for x in range (0, students):
print ("*** Student", studentnum, " ***")
score1 = int(input("Enter score for test #1"))
while score1 < 0:
print ("Invalid score. Try again.")
score1 = int(input("Enter score for test #1"))
score2 = int(input("Enter score for test #2"))
while score1 < 0:
print ("Invalid score. Try again.")
score1 = int(input("Enter score for test #1"))
part1 = score1 + score2
av = part1 / 2
print ("Average score for student #", studentnum, "is", av)
studentnum = studentnum + 1
# figure out how to average out all student inputs
Just create something to store them in outside your loop
scores = []
for x in range (0, students):
...
scores.append({'score1': score1, 'score2': score2, 'avg', av})
total_avg = sum(d['avg'] for d in scores) / len(scores)
You can build up a list of average scores for each student (by appending to it on each loop iteration), and then find the average of those after exiting the loop:
student_average_scores = []
for student in xrange(students):
# <your code that gets av>
student_average_scores.append(av)
average_score = sum(student_average_scores) / float(len(student_average_scores))
Related
Image to problem
The for loop works, though I can't figure out how to put the grade on a single line as shown in the photo. It asks for grades individualy when ran instead.
Here is my code:
num_students = int(input("Enter the number of students: "))
scores = []
for i in range(num_students):
scores.append(int(input("Enter a score: ")))
best_score = max(scores)
for i in range(num_students):
if scores[i] >= best_score - 10:
grade = "A"
elif scores[i] >= best_score - 20:
grade = "B"
elif scores[i] >= best_score - 30:
grade = "C"
elif scores[i] >= best_score - 40:
grade = "D"
else:
grade = "F"
print("Student", i, "score is", scores[i], "and grade is", grade)
Use a single input() call instead of a loop, and use .split() to get each individual score.
num_students = int(input("Enter the number of students: "))
scores = input(f"Enter {num_students} scores: ")
scores = [int(score) for score in scores.split()]
As John Gordon answered, your main issue is calling input inside a loop. That dictates that each user response will be on its own line. To fix this, call input once, then break the resulting string up using .split(). Split when called with no arguments will break a string into a list at each space.
Here is an example of how to do this (without the f strings and list comprehensions from John's answer):
num_students = int(input("Enter the number of students: "))
score_string = input("Enter " + str(num_students) + " scores: ")
scores = []
for score in score_string.split():
scores.append(int(score))
In this exercise you will create a program that #computes the average of a collection of values #entered by the user. The user will enter 0 as a #sentinel value to indicate that no further values #will be provided. Your program should display an #appropriate error message if the first value entered #by the user is 0.
print("You first number should not be equal to 0.")
total=0
average_of_num=0
i=0
num=input("Enter a number:")
for i in num:
total=total+num
i=i+1
num=input("Enter a number(0 to quit):")
if i==0:
print("A friendly reminder, the first number should not be equal to zero")
else:
average_of_num=total/i
print("Counter",i)
print("The total is: ", total)
print("The average is: ",average_of_num)
See if this works for you.
entry_list = []
while True:
user_entry = int(input("Enter a non Zero number(0 to quit entering: "))
if user_entry == 0:
break
entry_list.append(user_entry)
total = 0
for i in entry_list:
total = total + i
avg = total/len(entry_list)
print("Counter",len(entry_list))
print("The total is: ", total)
print("The average is: ",avg)
If only for loop should be used try this..
num=[int(input("Enter a number:"))]
total=0
for i in num:
if i == 0:
break
total=total+i
x = int(input("Enter a number(0 to quit):"))
if x != 0:
num.append(x)
avg = total/len(num)
print("Counter: ",len(num))
print("The total is: ", total)
print("The average is: ",avg)
Write a python application that allows a user to enter any number of student test scores until the user enters 999. If the score entered is less than 0 or more than 100, display an appropriate message and do not use the score. After all the scores have been entered, display the number of scores entered and the arithmetic average.
I am having trouble breaking the loop when the score entered is less than 0 or more than 100.
The code I have is
total_sum = 0
count = 0
avg = 0
numbers = 0
while True:
num = input("Enter student test score: ")
if num == "999":
break
if num < "0":
break
print("Number is incorrect")
if num > "100":
break
print ("Number is incorrect")
total_sum += float(num)
count += 1
numbers = num
avg = total_sum / count
print("The average is:", avg)
print("There were " +str(count) + " numbers entered")
There are multiple issues with your code.
You want to compare numbers, not strings. Try using float(input(...))
break will break out of the loop in exactly the same way for numbers under 0, above 100, or for the "finished" token 999. That's not what you described that you want. Rather, for "incorrect numbers" just print the message, and don't add the numbers and counter...But no need to break the loop, amirite?
You've got an indentation problem for the < 100 case. Your print is missing an indentation.
No need to have avg = 0
numbers isn't used
Try something like -
total_sum = 0
count = 0
while True:
num = float(input("Enter student test score: "))
if num == 999:
break
elif num < 0 or num > 100:
print("Number is incorrect")
else:
total_sum += num
count += 1
avg = total_sum / count
print("The average is:", avg)
print("There were " +str(count) + " numbers entered")
I am the given the following problem and asked to write a solution algorithm for it using python.
problem:
Write a Python program to determine the student with the highest average. Each student takes a midterm and a final. The grades should be validated to be between 0 and 100 inclusive. Input each student’s name and grades and calculate the student’s average. Output the name of the student with the best average and their average.
Here is my code:
def midTerm():
midtermScore = int(input("What is the midterm Score: "))
while (midtermScore <= 0 or midtermScore >= 100):
midtermScore = int(input("Please enter a number between 0 and 100: "))
return midtermScore
def final():
finalScore = int(input("What is the final Score: "))
while (finalScore < 0 or finalScore > 100):
finalScore = int(input("Please enter a number between 0 and 100: "))
return finalScore
total = 0
highest = 0
numStudents = int (input("How Many Students are there? "))
while numStudents < 0 or numStudents > 100:
numStudents = int (input("Please enter a number between 0 and 100? "))
for i in range (1, numStudents+1):
students = (input("Enter Student's Name Please: "))
score = (midTerm()+ final())
total += score
avg = total/numStudents
if (highest < avg):
highest = avg
winner = students
print ("The Student with the higgest average is: ", winner, "With the highest average of: ", avg)
The issue I am running into is the last part. The program does not print the name of the person with the highest average, but the name of the person that was entered at the very last. I am very confused on how to go forward from here. Can you please help? Thanks in advance for any help.
You're not far off. Take a look here:
for i in range (1, numStudents+1):
students = (input("Enter Student's Name Please: "))
score = (midTerm()+ final())
total += score
avg = total/numStudents
if (highest < avg):
highest = avg
winner = students
Besides the indentation error (hopefully just clumsy copy-pasting) You're not actually calculating each student's average score anywhere. Try something like this:
for i in range (numStudents):
student_name = (input("Enter Student's Name Please: "))
student_avg = (midTerm() + final()) / 2 # 2 scores, summed and divided by 2 is their average score
if (highest < student_avg):
highest = student_avg
winner = student_name # save student name for later
print ("The Student with the higgest average is: ", winner, "With the highest average of: ", highest)
It looks like you were originally trying to calculate the total class average, which is not what's described by the problem statement. Hope this helps!
I have to write code that will calculate the average of three grades for each of a number of students, and display a message depending on the resulting average grades.
The program needs to be able process any number of students; but each student will have only 3 grades. I have to use a method to calculate the average score for each student, and also to determine the appropriate message depending on the average.
This is the code I have so far and I am stuck:
def main():
more = 'y'
while more == 'y' and more == 'Y':
numScore = int(input('How many test score per student: '))
for numtest in range(numScore):
print ("The score for test")
score = int(input(': '))
total += score
total = 0
print ("Student number", students + 1)
print ('-----------------------------------------')
avg = getAvg(numScore)
if avg > 90:
print ("You're doing excellent work")
elif avg > 85 and avg <= 90:
print("You are doing pretty good work")
elif avg > 70 and avg <= 85:
print ("You better get busy")
else:
print ("You need to get some help")
def getAvg (numScore):
avg = total / numScore
print ("The average for student number", student + 1, \ "is:", avg)
more = input('Do you want to enter another student test score and get the average score of the student (Enter y for yes and n for no): ')
main()
You had most of the elements correct in your script, but you need to think more about the order of everything.
Make sure you pass any arguments that are needed to a function. Your getAvg function needed three arguments for it to calculate the average and display it with the student number. Also you forgot to return average.
When calculating the avg ranges, if you first test for >90, then by definition the next elif avg > 85 will be less than or equal to 90 so it is only necessary to then test for >85.
The following has been rearranged a bit to work:
def getAvg(student, total, numScore):
average = total / numScore
print ("The average for student number", student, "is:", average)
return average
def main():
student = 0
more = 'y'
while more == 'y':
student += 1
total = 0
numScore = int(input('How many test scores per student: '))
for test_number in range(numScore):
print ("The score for test", test_number+1)
score = int(input(': '))
total += score
print ("Student number", student)
print ('-----------------------------------------')
avg = getAvg(student, total, numScore)
if avg > 90:
print ("You're doing excellent work")
elif avg > 85:
print("You are doing pretty good work")
elif avg > 70:
print ("You better get busy")
else:
print ("You need to get some help")
print()
print('Do you want to enter another student test score and get the average score of the student?')
more = input('Enter y for yes, and n for no: ').lower()
main()
Giving you the following kind of output:
How many test scores per student: 3
The score for test 1
: 93
The score for test 2
: 89
The score for test 3
: 73
Student number 1
-----------------------------------------
The average for student number 1 is: 85.0
You better get busy
Do you want to enter another student test score and get the average score of the student?
Enter y for yes, and n for no: n