You can start the values as None
, instead of using values too large or too small and, within the loop, check whether the value is None
; if it is, assign the first weight both to the lowest value and to the highest, but if it is not None
, it is verified which is the lowest value between the lowest current value and the new read weight, assigning the result to the lowest value; similarly it is done with the highest value.
The code below will read 5 user values, always checking if they are numerical values and, when it is not, display an error message followed by a new value request. You can test this by entering with some letter as weight. Remember that the floating point pattern of Python uses point as decimal separator and not comma as we use, so the input 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, comparing in real time, defining the lowest and highest weight values. Note that at the end of the program it will not be possible to state which were all the values entered by the user and, if necessary, within the loop of repetition, the value of weight
should be stored in a list.
Thank you Anderson! Your explanation was very good, I am beginner and did not know this function min and max. The code was much more readable and practical.
– Raphael