Ways to find out the highest and least number entered in the input by the user in a for

2

Well briefly, I have a question if there is a way to make this code any more "simple". The code itself is already simple but wanted to know if there is another way using less lines or without using the power.

This was the only way I could get the desired result:

maior = -10 ** 20

menor = -10 ** 20

for c in range(1, 5, +1):
    user_input = float(input('Digite o peso da pessoa Nº{}: '.format(c)))

    if user_input >= maior:
        maior = user_input
    if user_input <= menor:
        menor = user_input

print('O menor peso é {:.2f} e o maior peso é {:.2f}kg'.format(menor, maior))
    
asked by anonymous 04.11.2017 / 22:02

1 answer

0

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.

    
04.11.2017 / 22:07