For a classroom assignment I have been asked to create a program that averages a number of user input exam grades using a while loop. I have come up with a functioning program, however it does not meet the specific criteria required by my instructor.
I need to Use a while-loop to allow the user to enter any number of exam scores, one number per line, until a sentinel value is entered.
How might I alter this program to get the same result using a while loop and a sentinel value of 9999?
here is what I have so far.
scores=int(input("how many test scores will you enter: "))
total_sum=0
for n in range(scores):
numbers=float(input("Enter exam score : "))
total_sum+=numbers
avg=total_sum/scores
print("average of ", scores, " test scores is :", avg)
The output should look something like this
Enter exam score. 9999 to quit: 100
Enter exam score. 9999 to quit: 95.5
Enter exam score. 9999 to quit: 90
Enter exam score. 9999 to quit: 9999
These 3 scores average to : 95.16666667
Think the best way to do it would be store the scores in a list and then compute the average of them after the user enters the sentinel value:
SENTINEL = float(9999)
scores = []
while True:
number = float(input("Enter exam score (9999 to quit): "))
if number == SENTINEL:
break
scores.append(number)
if not scores:
print("You didn't enter any scores.")
else:
avg = sum(scores)/len(scores)
print("average of ", len(scores), " test scores is :", avg)
There are a couple ways to go about this. The general approach would be to keep a running total of the scores, as well as how many scores you've read, and then check whether the next score to read is == 9999 to see whether or not to exit the while loop.
A quick version might be the following:
num_scores = 0
total_sum = 0
shouldExit = False
while shouldExit is False:
nextScore = float(input("Enter exam score : "))
if nextScore == 9999: #find a way to do this that does not involve a == comparison on a floating-point number, if you can
shouldExit = True
if shouldExit is False:
num_scores += 1
total_sum += nextScore
avg = total_sum / num_scores
See how that sort of approach works for you
You can just break out of your for loop after getting input.
for n in range(scores):
c = int(Input('Enter test score, enter 9999 to break'))
if c == 9999:
break;
scores += c
Something like that at least.
Related
I created a main() function and also 3 others and I am trying to get the other 3 to be executed into main()
I had it working then I messed it up at the very end, so I commented it out since it is not calling the 3 other functions.
# The program displays the letter grade and associated message for each exam score
# and the average exam score
# The program will not contain any repeated code and have a minimum of two functions besides Main.
def main():
# ask user to enter test scores
score = int(input("Enter your test scores separate by spaces, no commas: "))
# display test score
def showLetters(num, letterGrade):
print(f"{num:.1f} is an {letterGrade}\n")
# display score message
def examScores(num):
if 90 <= num <= 100:
letterGrade = "A"
print("Excellent Work")
elif 80 <= num <= 89:
letterGrade = "B"
print("Nice job")
elif 70 <= num <= 79:
letterGrade = "C"
print("Not bad")
elif 60 <= num <= 69:
letterGrade = "D"
print("Room for improvement")
else:
letterGrade = "F"
print("Go back and review")
return letterGrade
# calculate average of all scores entered by user
def calcAverages(grades):
numbers = scores.split()
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
print("Average exam score: ", sum(numbers) / len(numbers))
# ask user to repeat or quit
answer = str(input('Please enter "y" to run program again or "n" to exit: '))
if answer.lower() == 'n':
print('Thank you for using! Goodbye!')
sys.exit()
elif answer.lower() == 'y':
main()
# ??? = main()
# for n in ????? :
# showLetters(n, examScores(n, calcAverages(????)))
I made minor edits to your program and you now have the average values.
I have highlighted only the lines that need addition.
counter = 0 # tracks the number of times the function is called
#added the below 2 lines after counter
sumCredit = 0 #tracks the sum credit for all the students
sumStudyHrs = 0 #track the sum of the study hours for all the students
def myfunction():
global counter # tracks the number of times the function is called
#added two more global variables to keep track of the averages
global sumCredit #track the sum credit
global sumStudyHrs #track the sum study hours
the rest of the code can stay as is. Immediately after you print the student details, you need to accumulate the values so you can calculate the average.
print("Study hours: " + str(sumHours))
#added the below 2 lines after your print statements
sumCredit += classes
sumStudyHrs += sumHours
# Ask user if they want to end or restart
Now you need to use this information for your calculation.
When you print the average, use the above variables to compute the average.
print("Total Students: " + str(counter)) # tracks the number of times the function is called
#modified your average credits and average study with correct numerator
print("Average Credits: " + str(sumCredit / counter)) #computer average credits
print("Average Study Hours: " + str(sumStudyHrs / counter)) #compute average study hours
print('Thank you for using! Goodbye!')
This should give you the desired results.
Let me know if you need the full code.
I am trying to find scores from only 7 judges and to have the numbers between 1-10 only, what is the problem with my code I am an newbie trying to self teach myself:)
So what I'm asking is how to limt the input to have to be 7 inputs per name and to limt the user input to 1-10 for numbers.
import statistics#Importing mean
def check_continue(): #defining check_continue (checking if the user wants to enter more name/athletes
response = input('Would you like to enter a another athletes? [y/n] ') #Asking the user if they want another name added to the list
if response == 'n': #if n, ends the loop
return False
elif response == 'y': # if y, continues the loop
return True
else:
print('Please select a correct answer [y/n]') #making sure the awsener is valid
return check_continue() #calling check continue
while(True):
name = input('Please enter a athletes name: ') #asking for an athletes name
if name == (""):
print ("try again")
continue
else:
try:
print("Enter the judges scores with space inbetween each score") #asking for scores
avg = [float(i) for i in input().split( )] #spliting the scores so the user only needs to put a space for each score
except ValueError:
continue
print("Please enter scores only in numbers")
scores = '' .join(avg)
print("please only enter number")
if scores ==("") or scores <=0 or scores >=10:
print("Please enter a score between 1-10")
continue
else:
print("_______________________________________________________________________________")
print("Athlete's name ",name) #Printing athletes name
print("Scores ", avg) #printing athletes scores
avg.remove(max(avg)) #removing the highest score
avg.remove(min(avg)) #removing the lowest score
avgg = statistics.mean(avg) #getting the avg for the final score
print("Final Result: " +
str(round(avgg, 2))) #printing and rounding the fianl socre
if not check_continue():
break
else:
continue
After reading input scores from judges, make sure that len(input.split()) == 7 to match first criteria.
Once you have the list of scores, just have a check that for each score, 1 <= int(score) <= 10.
If necessary, I can provide a working code too.
import statistics # Importing mean
def check_continue(): # defining check_continue (checking if the user wants to enter more name/athletes
# Asking the user if they want another name added to the list
response = input('Would you like to enter a another athletes? [y/n] ')
if response == 'n': # if n, ends the loop
return False
elif response == 'y': # if y, continues the loop
return True
else:
# making sure the awsener is valid
print('Please select a correct answer [y/n]')
return check_continue() # calling check continue
while(True):
# asking for an athletes name
name = input('Please enter a athletes name: ')
if name == (""):
print("try again")
continue
else:
scores = [float(i) for i in input('Enter the judges scores with space inbetween each score').split() if 1 <= float(i) <= 10]
if len(scores) != 7:
print("try again")
continue
print("_______________________________________________________________________________")
print("Athlete's name ", name) # Printing athletes name
print("Scores ", scores) # printing athletes scores
scores.remove(max(scores)) # removing the highest score
scores.remove(min(scores)) # removing the lowest score
# getting the avg for the final score
avg = statistics.mean(scores)
print("Final Result: " + str(round(avg, 2))) # printing and rounding the final score
if not check_continue():
break
This one should work. Let me know if there are any issues.
scores = [float(i) for i in input('Enter the judges scores with space inbetween each score').split() if 1 <= float(i) <= 10]
This line of code only saves values between 1 and 10, thus already checking for those values. Then the number of elements is checked to be 7.
PS: Would also want to point out that in your code, nothing ever executes after the except ValueError: continue. The continue basically skips to the next iteration without running any of the next lines of code.
My two cents. All checks of input you can warp before printing results with if all(): function for length of input scores list and range of nums between 1 and 10 (see code below).
For mean calc you don't need to delete value from list. You can make sorting and then slicing of list.
check_continue() can be simplify. Check entering for y or n value and return True or False by cases in dict. Otherwise loop.
import statistics
def check_continue():
response = input('Would you like to enter a another athletes? [y/n] ').lower() # Format Y and N to y and n
if response in ['y', 'n']: # Check if response is y or n
return {'y': True, 'n': False}[response]
check_continue()
while True:
name = input('Please enter a athletes name: ') #asking for an athletes name
if name: # Check if name not empty
while True: # make a loop with break at only 7 scores enter
scores_input = input("Enter the judges scores with space inbetween each score (only 7 scores)").split(' ')
try:
scores = [float(s) for s in scores_input] # sort list for extract part for avgg calc
except ValueError:
print("Please enter scores only in numbers")
continue
if all([len(scores) == 7, max(scores) <= 10.0, min(scores) >= 1]):
print("_______________________________________________________________________________")
print(f"Athlete's name {name}") #Printing athletes name
print(f"Scores {scores}") #printing athletes scores
avgg = statistics.mean(sorted(scores)[1:-1]) #getting the avg for the final score
print(f'Final result - {avgg :.2f}')
break
else:
print("Please enter 7 numbers for scores between 1-10")
if not check_continue():
break
I have written this code for an assignment and it not working as it should. I want my program to validate user input for 3 users when they enter the names and grades for 3 test. my program just check the first input and then asks for the other user name and skips asking the user for an input or validating the input.
validInput1 = False
validInput2 = False
validInput3 = False
studentnames = []
studentMarkTest1 = []
studentMarkTest2 = []
studentMarkTest3 = []
totalScores = []
sum = 0
for i in range(3):
sname = input("Enter Student name:")
while not validInput1:
score1 = int(input("What did {} get on their test 1?".format(sname)))
if score1 < 0 or score1 >20:
print("Invalid input")
else:
validInput1 = True
while not validInput2:
score2 = int(input("What did {} get on their test 2?".format(sname)))
if score2 < 0 or score2 >25:
print("Invalid input")
else:
validInput2 = True
while not validInput3:
score3 = int(input("What did {} get on their test 3?".format(sname)))
if score3 < 0 or score3 >35:
print("Invalid input")
else:
validInput3 = True
totalScore = score1+ score2+ score3
sum = sum + totalScore
AverageTestScore = sum / 3
# saving name and grade
studentnames.append(sname)
studentMarkTest1.append(score1)
studentMarkTest2.append(score2)
studentMarkTest3.append(score3)
totalScores.append(totalScore) for i in range(3):
print(studentnames[i],"total Test score",totalScores[i]) print("class average", AverageTestScore)
here what happens when i run the program
>>>
Enter Student name:g
What did g get on their test 1?44
Invalid input
What did g get on their test 1?33
Invalid input
What did g get on their test 1?44
Invalid input
What did g get on their test 1?22
Invalid input
What did g get on their test 1?20
What did g get on their test 2?34
Invalid input
What did g get on their test 2?23
What did g get on their test 3?55
Invalid input
What did g get on their test 3?44
Invalid input
What did g get on their test 3?32
Enter Student name:e
Enter Student name:e
g total Test score 75
e total Test score 75
e total Test score 75
class average 75.0
>>>
How can I get the highest test score value stored in totalscore and then print out the highest score with the name of the student with the highest score?
its easy to get confused when you have a big chunk of code like this ... instead try and split your problem into smaller parts
start with a function to get the details of only one student
def get_student_detail(num_tests): # get the detail for just 1 student!
student_name = input("Enter Student Name:")
scores = []
for i in range(1,num_tests+1):
scores.append(float(input("Enter Score on test %s:"%i)))
return {'name':student_name,'scores':scores,'avg':sum(scores)/float(num_tests)}
now just call this for each student
student_1 = get_student_detail(num_tests=3)
student_2 = get_student_detail(num_tests=3)
student_3 = get_student_detail(num_tests=3)
print("Student 1:",student_1)
print("Student 2:",student_2)
print("Student 3:",student_3)
or better yet implement a function that lets you keep going as long as you want
def get_students():
resp="a"
students = []
while resp[0].lower() != "n":
student = get_student_detail(num_tests=3)
students.append(student)
resp = input("Enter another students details?")
return student
you may want to split out get_student_details even further writing a method to get a single test score and validate that its actually a number (this will crash as is if you enter something that isnt a number as a test score), or to keep asking for test scores until an empty response is given, etc
def get_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print ("That is not a valid number!")
def get_test_score(prompt):
while True:
score = get_number(prompt)
if 0 <= score <= 100:
return score
print("Please enter a value between 1 and 100!")
test_score = get_test_score("Enter test score for test 1:")
print(test_score)
Let's take a look at the while-loops you have:
while not validInput1:
The first time that your application runs, validInput1 is False, so this block evaluates. However, on subsequent loops (from for i in range(3):), validInput1 is already true, so this block is entirely skipped.
You can fix this by changing validInput1, validInput2 and validInput3 to False at the beginning of your for-loop.
That is because validInput1, validInput2 and validInput3 variables were set to True at first iteration but were not set to false for the second iteration.
Therefore for after first iteration your while conditions are always false due to "not True" i.e. False
Can set them to false again after each iteration i.e. at the end of the loop
You need to put validInput back to False after the while loops or even better replace them to the beginning of the for loop.
For my computer science class I have to make a program that will calculate grades.
This is my first computer science class (no prior experience) so I am struggling through it.
These are the directions:
Ask the user for the number of tests, assignments, quizzes, and labs in their course.
Ask the user if there is a final with a separate weight from the tests above, e.g. a course has 2 tests, each weighing 12.5%, and 1 final weighing 15%.
For each category having a number > 0
a. Prompt the user for the weighted percent, out of 100%, which should total
100% for all categories!!!
b. Get the score(s) for the category.
c. If the category is labs, then sum all the scores.
d. Else, average the scores.
e. Calculate the weighted average for the category.
Using the weighted average of each category, calculate the grade in the course.
Ask the user if he/she wants to calculate a grade for another class.
If the user responds yes, then go back to step 1.
Else, end the program.
My code so far:
def main():
lists = get_user_input()
get_scores(lists);
get_weighted_average(lists)
def get_user_input():
# How many?
t = int(input("How many tests?: "))
a = int(input("How many assignments?: "))
q = int(input("How many quizzes?: "))
l = int(input("How many labs?: "))
# How much weight on grade?
tw = float(input("Enter weight of tests: "))
aw = float(input("Enter weight of assignments: "))
qw = float(input("Enter weight of quizzes: "))
lw = float(input("Enter weight of labs: "))
lists = [t, a, q, l, tw, aw, qw, lw]
return lists
def get_scores(lists):
# What are the scores?
scores = [0] * 5
for(x in range(lists[0]):
test_scores = float(input("enter your test scores: "))
scores[x] = test_scores
for(x in range(lists[1]):
test_scores = float(input("enter your assignment scores: "))
scores[x] = assignment_scores
for(x in range(lists[2]):
test_scores = float(input("enter your quiz scores: "))
scores[x] = quiz_scores
for(x in range(lists[3]):
test_scores = float(input("enter your lab scores: "))
scores[x] = lab_scores
sumlabs = 0
for(x in range(lists[3]):
sumlabs = sumlabs + scores[x]
print(sumlabs)
def get_weighted_average(lists):
main()
I am not sure how to proceed so any help is much appreciated.
Averaging a score means adding them up and dividing by the number of them. You can use the fact that a list has a way to tell you how many elements it has. For example if x is a list then len(x) is the number of things in the list. You should be careful about not trying to calculate the score of an empty list, because that would mean dividing by zero. In the following function the 'if score_list:' will be true if there is something in the list. Otherwise it returns None (since the average is not defined).
def average_score(score_list):
if score_list: # makes sure list is not empty
total = 0 # our total starts off as zero
for score in score_list: # starts a loop over each score
total += score # increases the total by the score
return total / len(score_list) # returns aveage
To form a list of scores from user input, presuming the user will put them all on the same line when you prompt them, you can get a string from the user (presumably like: "13.4 12.9 13.2" And then use the string's split method to convert this to a list of strings like ["13.4", "12.9", "13.2"], and then convert this list of strings to a list of floats. Finally using the average function above you can get an average:
test_score_entry = raw_input("Enter your test scores separated by spaces: ")
test_sore_strings = test_score_entry.split()
test_scores = [float(_) for _ in test_score_strings]
average_score = average(test_scores)
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