Im really struggling with this question, can anyone help me write a code for this program? or at least say where am I going wrong? Ive tried a lot but can't seem to get the desired output.
This is the program description: Python 3 program that contains a function that receives three quiz scores and returns the average of these three scores to the main part of the Python program, where the average score is printed.
The code I've been trying:
def quizscores():
quiz1 = int(input("Enter quiz 1 score: "))
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
average = (quiz1 + quiz2 + quiz3) / 3
print (average)
return "average"
quizscores(quiz1,quiz2,quiz3)
One, you are returning a string, not the variable. Use return average instead of return "average". You also don't need the print() statement in the function... actually print() the function.
If you call a function the way you are doing it, you need to accept parameters and ask for input outside the function to prevent confusion. Use a loop as needed to repeatedly use the function without having to rerun it every time. So the final code would be:
def quiz_average(quiz1, quiz2, quiz3):
average = (quiz1 + quiz2 + quiz3) / 3
return average
quiz1 = int(input("Enter Quiz 1 score: "))
quiz2 = int(input("Enter Quiz 2 score: "))
quiz3 = int(input("Enter Quiz 3 score: "))
print(quiz_average(quiz1, quiz2, quiz3)) #Yes, variables can match the parameters
You are returning a string instead of the value. Try return average instead of return "average".
There are a few problems with your code:
your function has to accept parameters
you have to return the actual variable, not the name of the variable
you should ask those parameters and print the result outside of the function
Try something like this:
def quizscores(score1, score2, score3): # added parameters
average = (score1 + score2 + score3) / 3
return average # removed "quotes"
quiz1 = int(input("Enter quiz 1 score: ")) # moved to outside of function
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
print(quizscores(quiz1,quiz2,quiz3)) # print the result
An alternative answer to the already posted solutions could be to have the user input all of their test scores (separated by a comma) and then gets added up and divided by three using the sum method and division sign to get the average.
def main():
quizScores()
'''Method creates a scores array with all three scores separated
by a comma and them uses the sum method to add all them up to get
the total and then divides by 3 to get the average.
The statement is printed (to see the average) and also returned
to prevent a NoneType from occurring'''
def quizScores():
scores = map(int, input("Enter your three quiz scores: ").split(","))
answer = sum(scores) / 3
print (answer)
return answer
if __name__ == "__main__":
main()
Related
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.
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)
This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 3 months ago.
So I have this assignment and I have a question about a part I don't know how to do, can you guys help me?
def main():
# Please see the comments
largest = 0
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
number1 = int(input("Please enter the first number: "))
number2 = int(input("Please enter the second number: "))
number3 = int(input("Please enter the third number: "))
# insert call to function find_largest after this comment.
# find_largest will take in three parameters and will return the largest of the 3 numbers
result = find_largest(number1, number2, number3)
# insert the statement to print the three numbers entered and the largest number after this comment.
print("The numbers you entered were, \n", [number1, number2, number3])
print ("The largest of the numbers you entered is", result)
def find_largest(a, b, c):
# insert parameters in the parenthesis
# Write the code for this function here.
# find_largest will take in three parameters and will return the largest of the 3 numbers
# These three numbers are passed in as parameters from the main function
# Hint: if and elif - no loop needed here
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
return largest
main() # this is the call to main() that will make the program run
So, my question is the part:
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
I don't know what to add so the loop run 2 more times after it has found the largest number
The loop you have makes the first two iterations of the loop pointless, as each time you loop, you are reassigning new numbers to the three number variables. As a result, only the numbers entered in the last iteration of the loop are ever used for anything. I think this would make more sense:
numbers = []
for i in range(3):
input = int(input("Enter number: "))
numbers.append(input)
This will give you a list called numbers with 3 numbers in it entered by the user. Then you can do what you want with them. Having said that, you really don't need a for loop to do this. As Craig Burgler mentioned.
Alternatively(though this doesn't use range...):
number1 = 0
number2 = 0
number3 = 0
for i in (number1, number2, number3):
i = int(input("Enter number: "))
The code as written will ask for three numbers three times, overwriting the first and second set of numbers that the user enters. If the assignment is to get three numbers from the user and tell the user which is largest, then you do not need the for loop. The three input statements will do the trick.
I'm trying to work on a school assignment that asks the user to input 3 integers, then I need to pass these three integers as parameters to a function named avg that will return the average of these three integers as a float value.
Here's what I've come up with so far, but I get this error:
line 13, in <module>
print (average)
NameError: name 'average' is not defined
Advice?
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))
def avg(a,b,c):
average = (a + b + c)/3.0
return average
print ("The average is: ")
print (average)
avg()
average only exists as a local variable inside the function avg
def avg(a,b,c):
average = (a + b + c)/3.0
return average
answer = avg(a,b,c) # this calls the function and assigns it to answer
print ("The average is: ")
print (answer)
You should print(avg(a,b,c)) because the average variable is only stored in the function and cannot be used outside of it.
You called avg without passing variables to it.
You printed average which is only defined inside the avg function.
You called avg after your print.
Change print (average) to
average = avg(a, b, c);
print(average)