Python already has functions ready to identify the smallest and largest value of a list, as well as calculate the average of it.
- To identify the lowest value:
min
- To identify the highest value:
max
- To calculate the average:
statistics.mean
Thus, we simply create an infinite loop loop, as we do not know how many numbers will be informed and interrupt the loop when an empty line is received.
from statistics import mean
numbers = []
while True:
number = input()
if number == '':
break
numbers.append(float(number))
print('O menor valor informado foi', min(numbers))
print('O maior valor informado foi', max(numbers))
print('A média dos valores foi', mean(numbers))
With Python 3.8, using Walrus Operator (sometimes cited in Portuguese as a walrus operator - because apparently :=
reminds the fangs of a walrus) you can make the loop repeat as follows:
from statistics import mean
numbers = []
while (number := input()) != '':
numbers.append(float(number))
print('O menor valor informado foi', min(numbers))
print('O maior valor informado foi', max(numbers))
print('A média dos valores foi', mean(numbers))
And if you cannot use the functions min
, max
and mean
to solve the problem, just iterate on your list and apply the necessary conditions.
- To identify the lowest value, start by assuming that the first value in the list is the lowest value, scroll through the entire list and for each value compare with the lowest current value; if lower, refresh the value of this;
- To identify the highest value, start assuming that the first value in the list is the highest value, scroll through the entire list and for each value compare with the highest current value; if higher, refresh the value of this;
- To calculate the average as expected, simply calculate the sum of all the values and divide by the quantity;