You can start values as None
, rather than using very large or very small values, and within the loop repeat, check whether the value is None
; if it is, it assigns the first weight to both the lowest value and the highest, but if it is not None
, it is verified which is the lowest value between the lowest current value and the new weight read, assigning the result to the lowest value ; the same is done with the highest value.
The code below will read 5 user values, always checking for numeric values and, if not, displaying an error message followed by a new request for the value. You can test this by entering some letter as weight. Note that the Python floating-point pattern uses dot as the decimal separator and not a comma as we used it, so the entry should be something like 70.5
and not 70,5
.
smaller = None
bigest = None
for i in range(5):
while True:
try:
weight = float(input('Entre com o peso da pessoa nº{}'.format(i+1)))
except ValueError:
print('Ooops, parece que você digitou um valor não numérico.')
continue
break
smaller = weight if smaller is None else min(smaller, weight)
bigest = weight if bigest is None else max(bigest, weight)
print('Menor peso: {}'.format(smaller))
print('Maior peso: {}'.format(bigest))
This solution, unlike my previous one, does not store all the values in memory, making the comparison in real time, defining the smallest and largest values of weight. Note that at the end of the program it will not be possible to determine which values were entered by the user and, if necessary, within the loop, the weight
value should be stored in a list.