Loop to determine the smallest entered value

Asked

Viewed 380 times

0

I’m having trouble creating repetitions to get the lowest value out of a given situation.

For example, a program that registers price of products in which I have to report the lowest value and the highest, I saw in some places that would declare two variables as menorv and maiorv, then put a if equaling 1 and then making the conditions that would be like:

maiorv = menorv = 0
while True:
    n = float(input('Digite o valor do produto: R$ '))
    if n == 1:
      maiorv = menorv = n
    else:
        if n > maiorv:
           maiorv = n
        if n < menorv:
           menorv = n
    continuar = ' '
    while continuar not in 'SN':
        continuar = str(input('Quer continuar: (S/N) ')).upper().strip()[0]
    if continuar == 'N':
        break
print(f'O maior valor é {maiorv}')
print(f'O menor valor é  {menorv}')

The value always returns zero, would you have a hint of what logic to use in these cases? And what am I missing to return 0? I’ve heard about a float and -float but didn’t quite understand about.

3 answers

1

Probably, the conditional structure matching 1 serves to identify in which iteration the repetition loop is found.

In this case, it is necessary to create a counter (which I will call cont) and increment at the end of each iteration.

Note: This code was made for Python version 3.6 or higher.

# -*- coding: utf-8 -*-

maiorv = menorv = 0
cont = 1
while True:
    n = float(input('Digite o valor do produto: R$ '))
    if cont == 1:
        maiorv = menorv = n
    else:
        if n > maiorv:
            maiorv = n
        if n < menorv:
            menorv = n
    continuar = ' '
    while continuar not in 'SN':
        continuar = str(input('Quer continuar: (S/N) ')).upper().strip()[0]
    if continuar == 'N':
        break
    cont = cont + 1
print(f'O maior valor e {maiorv}')
print(f'O menor valor e  {menorv}')

0

From what I understand, you want to implement an algorithm that evaluates which maior and the menor value among the entered values.

To solve this issue, we can implement the following algorithm...

valores = list()
while True:
    n = float(input('Digite o valor do produto: R$ '))
    valores.append(n)

    resp = input('Quer continuar? [S/N] ').upper()
    while (len(resp) != 1) or (resp not in 'SN'):
        print('\033[31mValor INVÁLIDO! Digite apenas "S" ou "N"!\033[m')
        resp = input('Quer continuar? [S/N] ').upper()
    if resp == 'N':
        r = sorted(valores, reverse=True)
        menorv = r[-1]
        maiorv = r[0]
        print(f'O menor valor é: R$ {menorv:.2f}')
        print(f'O maior valor é: R$ {maiorv:.2f}')
        break

Note that this algorithm has implemented a laço de repetição that will capture the entered values. Later, each of these values is inserted in the list valores.

Also note that a second block has been implemented while. This, in turn, evaluates the user’s response [S/N] and makes a decision. According to the response the program is terminated or run again.

Note that when we decide to close, the algorithm shows us the menor and the maior value to then finish the execution.

0

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.

Browser other questions tagged

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