Input multiple values on single line and get the average of the values entered using Python

Viewed 95

Using python I need to write a script that will allow the user to input 3 numbers (no more and no less) and then calculates the average of the three numbers that have been input and print them out.

I figured out how to have the user input three entries on the same line and can get all three entries to print as needed. But since I'm using x, y, z I'm not sure how to get the average.

x, y, z = input("avg3: ").split()
print("Average of " + (x) + ", " + (y) + " and " + (z) + " is ")
print()
2 Answers

Try:

x, y, z = input("avg3: ").split()
print("Average of " + (x) + ", " + (y) + " and " + (z) + " is " , (int(x)+int(y)+int(z))/3)

You can load them into a numpy array and get the average of that array.

import numpy as np

array = np.zeros(3)
array[0] = x
array[1] = y
array[2] = z
print(np.average(array))

This is particularly useful when you have more than a handful of values.

Related