Changing the name of the n
for preco
maybe get a little more "didactic" to explain (and also why give names better help when programming):
maiorv = menorv = 0
while True:
preco = float(input('Digite o valor do produto: R$ '))
if preco == 1:
maiorv = menorv = preco
else:
if preco > maiorv:
maiorv = preco
if preco < menorv:
menorv = preco
etc...
That is to say, if the price entered is equal to 1 you make the highest and lowest price 1. This is wrong because in the event that the 1
is the last entered value (for example, the user type multiple values, then type 1
and then choose "N" not to continue), so both the largest and the smallest will be 1. This causes all previous values to be ignored. That one if
doesn’t make sense, remove it.
Another detail is that menorv
starts at zero. Then any positive value that is typed (1, 2, 3, any other positive value) will never be less than zero, then you’ll never get into the if preco < menorv
. Only if you enter a negative value, then it will be less than zero and will enter this if
(but by program logic, a negative price would not make sense). So if you only enter positive values, you will never enter the if
and in the end menorv
will be zero.
So one solution is to make menorv
start with as much value as possible, so anything that is typed will surely be smaller than it. The "highest possible value", in this case, is "infinite", which can be obtained using float('inf')
.
The same logic holds true for maiorv
: it must start with as little value as possible, so anything that is typed will surely be greater than it (and one option is to use the "negative infinity", which can be obtained with float('-inf')
or -float('inf')
).
And take off the if preco == 1
, as already explained:
maiorv = float('-inf') # infinito negativo
menorv = float('inf') # infinito
while True:
preco = float(input('Digite o valor do produto: R$ '))
if preco > maiorv:
maiorv = preco
if preco < menorv:
menorv = preco
continuar = ' '
while continuar not in 'SN':
continuar = input('Quer continuar: (S/N) ').upper().strip()[0]
if continuar == 'N':
break
Note also that input
already returns a string, so do str(input(...))
is redundant and unnecessary. Just do input(...)
.
Finally, I suggest you learn to do the table test and the debug the code, that logic errors like this can be easily detected.
One of the answers stores the values in a list and then uses max
and min
to get the biggest and smallest.
It also works, of course, but there is the detail that each of these calls goes through the entire list (i.e., the list is covered twice, one to check the largest, and the other to the smallest).
Of course, for a small amount of numbers, the difference is irrelevant. But if you don’t need to save all the numbers typed in, I wouldn’t create the list for this case. And anyway it is interesting to know that there are functions ready in the language.