Ways to find out which is the largest and smallest number typed in the user input in a for

Asked

Viewed 3,717 times

2

Well briefly I have a doubt whether there is a way to make this code otherwise more "simple". The code itself is already simple but wanted to know if there is another way using fewer lines or without using potentiation.

That was the only way I could achieve 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))

1 answer

0


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.