Variable returning value that was declared initially and not what the user reported

Asked

Viewed 61 times

0

cont = soma = maiorv = media = 0
r = 'S'
menorv = 0
while r in 'Ss':
    n = int(input('Informe um número inteiro: '))
    cont += 1
    soma += n
    if n == 1:
        maiorv = menorv = n
    else:
        if n > maiorv:
            maiorv = n
        if n < menorv:
            menorv = n
    r = str(input('Quer continuar: (S/N) ')).upper().strip()[0]
media = soma/cont
print('\nA média entre os valores é {}'.format(media))
print('O maior valor é {} e o menor valor é {}'.format(maiorv, menorv))

In that last line of print, the value that returns in the menorv is being 0 instead of the lower value the user typed, someone can explain to me why?

1 answer

0


I regret to inform you that the another answer (which has been deleted) is wrong. For example, if you type the numbers 3, 2 and 1 in this order, the result is:

O maior valor é 1 e o menor valor é 1

That was the code:

cont = soma = maiorv = media = 0
r = 'S'
menorv = 0
while r in 'Ss':
    n = int(input('Informe um número inteiro: '))
    if cont == 0:
        menorv = n
    cont += 1
    soma += n
    if n == 1:
        maiorv = menorv = n
    else:
        if n > maiorv:
            maiorv = n
        if n < menorv:
            menorv = n
    r = str(input('Quer continuar: (S/N) ')).upper().strip()[0]
media = soma/cont
print('\nA média entre os valores é {}'.format(media))
print('O maior valor é {} e o menor valor é {}'.format(maiorv, menorv))

See here the code running.

He says - erroneously - that the highest value is 1. It happens because of this if:

if n == 1:
    maiorv = menorv = n

That is, if the user type 1, he becomes the greatest and the smallest. What if the 1 is the last number typed, it is as if all previous numbers were ignored. It makes no sense to have this if. In fact, it would also go wrong for the minor, if previously had been typed a negative number, for example.

And an alternative to the proposed solution (see if count is 0) is initialize maiorv with as few as possible (so any value that is entered will be with certainty greater than it), and menorv with the highest possible value (so any entered value will be smaller than it). One option is to use the positive and negative "infinites", then you eliminate the need for these if's, keeping only the essential:

cont = soma = 0
maiorv = -float('inf') # infinito negativo
menorv = float('inf') # infinito
while True:
    n = int(input('Informe um número inteiro: '))
    cont += 1
    soma += n
    if n > maiorv:
        maiorv = n
    if n < menorv:
        menorv = n
    if input('Quer continuar: (S/N) ').upper().strip()[0] != 'S':
        break # sai do while

print('\nA média entre os valores é {}'.format(soma / cont))
print('O maior valor é {} e o menor valor é {}'.format(maiorv, menorv))

I also made a loop infinite (while True) which is only interrupted if you type something other than "S". Also note that input already returns a string, so do str(input(...)) is redundant and unnecessary.

And eliminated the variable media, because if you just need to print and then will not use the value for anything else, nor need it. The same goes for the variable r, I eliminated and directly used the return of input in the if. And how you use upper to convert to uppercase, do not need to compare if it is equal to lowercase "s". The detail is that if you type anything other than "S", it exits the while (does not check if it was typed only "S" or "N").


It is not the focus of the question, but the code does not validate whether a valid number has been entered. If you want to include this validation, just do another loop that asks to type again until it is a number.

And if you’re using Python >= 3.6, you can swap format for f-string:

cont = soma = 0
maiorv = -float('inf') # infinito negativo
menorv = float('inf') # infinito
while True:
    while True:
        try:
            n = int(input('Informe um número inteiro: '))
            break
        except ValueError:
            print('Você não digitou um número inteiro')
    cont += 1
    soma += n
    if n > maiorv:
        maiorv = n
    if n < menorv:
        menorv = n
    if input('Quer continuar: (S/N) ').upper().strip()[0] != 'S':
        break # sai do while

# usando f-string em vez de format (Python >= 3.6)
print(f'\nA média entre os valores é {soma / cont}')
print(f'O maior valor é {maiorv} e o menor valor é {menorv}')
  • Thanks for the correction in some aspects, I’m starting now to program so I still have a lot to learn kk. this "infinity" that used is as if the value I declared was infinite and when the user type a value will replace that infinity?

  • @Victorhenrique The idea is that if maiorv starts with "negative infinity", so any value that is typed will be greater than it (i.e., in the first iteration, it will definitely enter the if n > maiorv (because any number is greater than infinite negative). It is only to avoid the if cont == 0, that although it works I find it unnecessary. And the same logic applies to menorv: it starts with infinity, so any value that is typed will be less than it

  • understood now, and the other infinite follows the same logic only positive? Yes, there are things that after being ready we notice that it is unnecessary, as I am at the beginning several codes I do still have to make a correction later

  • I didn’t know I was wrong, when I read it at first and performed the test for me was right. Sorry for the mistake

  • @Victorhenrique "another infinite follows the same logic only positive" - exactly! menorv starts with the value "infinite", so any value that is typed will be smaller than it. As for the error, alright, it happens :-) There is the lesson that we have to test our code well, often there are cases that can go wrong and that we do not think about the time...

Browser other questions tagged

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