Python - How can I put a range of user inputs into a function

Viewed 196

This is my python code:

def calc_average(arg1, arg2, arg3, arg4, arg5):
    average = (arg1 + arg2 + arg3 + arg4 + arg5) / 5
    return print("The average of your scores is ", average)

for number in range(1, 6):
    scores = float(input("Enter test score " + str(number) + " of 5: "))
    
calc_average(scores) #This does not work. It counts as 1 argument instead of 5.

The function calc_average takes in 5 arguments and divides them by 5, creating an average. The 'for number in range(1,6):' asks the user to input a test score 5 times. I want to be able to put those 5 user inputs into the function calc_average. How can I do this? I have only done python for a few weeks and I am not really good at it. This is actually my first time using a function.

2 Answers

Create a list, for example scores. You will append a number into it each iteration of for-loop. Then use this list to call your calc_average function:

def calc_average(arg1, arg2, arg3, arg4, arg5):
    average = (arg1 + arg2 + arg3 + arg4 + arg5) / 5
    return "The average of your scores is " + str(average)

scores = []
for number in range(1, 6):
    n = float(input("Enter test score " + str(number) + " of 5: "))
    scores.append(n)
    
print(calc_average(*scores))

Prints (for example):

Enter test score 1 of 5: 1
Enter test score 2 of 5: 2
Enter test score 3 of 5: 3
Enter test score 4 of 5: 4
Enter test score 5 of 5: 5
The average of your scores is  3.0

Note: you can call your function like this calc_average(scores[0], scores[1], scores[2], scores[3], scores[4]), but it's easier to use * to unpack the list as function arguments.


Note 2: return print(...) returns always None. Just return a string and print it afterwards.

Simply, you can solve this by using a list :

Solution : the argument of calc_average is a list :

def calc_average(scores):
   return sum(scores)/len(scores)

scores = []
for number in range(1, 6):
    scores.append(float(input("Enter test score " + str(number) + " of 5: ")))

calc_average(scores)

PS :

you can use the mean() function from statistics library

from statistics import mean
def calc_average(scores):
   return mean(scores)
Related