Show smaller, average and larger until an empty line is typed

Asked

Viewed 116 times

1

I have the following code:

qtdNumeros = int(input())
if qtdNumeros <= 0:
    menor = "Nenhum"
    media = "Nenhuma"
    maior = "Nenhum"
else:
    menor = maior = soma = float(input())
    for proximo in range(1, qtdNumeros):
        valor = float(input())
        soma += valor
        if valor < menor:
            menor = valor
        elif valor > maior:
            maior = valor
    media = soma / qtdNumeros
print("Menor Lido:", menor)
print("Média dos Lidos:", media)
print("Maior Lido:", maior)

I would like to implement the following: Instead of me passing an input amount, I insert input until an empty row is entered and then it processes and displays the smaller, the average and the larger one and, instead of typing a negative number, type only an empty row. Could you help me? As a beginner I’m not getting :(

2 answers

3


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;

1

I made some changes to the code and put some blocks try/except because in the question code there was no validation and when a different value was passed than expected the code gave error. However, in the second try/except, put a if not to display the message in case of exit of the execution.

I put a first while only to accept the first value when it is actually valid.

Then I removed the for that existed and I traded it for a while checking if the input value was equal to an empty string, so it would not be necessary to put a fixed number of values and the loop would end when receiving an empty value and giving the final result, also the if because there was no need for it to exist.

The new code went like this:

menor = "Nenhum"
media = "Nenhuma"
maior = "Nenhum"
qtdNumeros = 0
valor_valido = False
while valor_valido == False:
    try:
        entrada = input()
        menor = media = maior = soma = float(entrada)
        qtdNumeros = qtdNumeros + 1
        valor_valido = True
    except:
        print("Insira um valor valido!")
while entrada != '':
    entrada = input()
    try:
        valor = float(entrada)
        qtdNumeros = qtdNumeros + 1
        soma += valor
        if valor < menor:
            menor = valor
        elif valor > maior:
            maior = valor
        media = soma / qtdNumeros
    except:
        if entrada != '':
            print("Insira um valor valido!!")
print("Menor Lido:", menor)
print("Média dos Lidos:", media)
print("Maior Lido:", maior)

Browser other questions tagged

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