Doubt with the counter at the while

Asked

Viewed 56 times

3

Analyzing this code that serves to calculate arithmetic progression and that is working correctly:

primeiro_termo = int (input ('Primeiro termo: ')) 
razao = int (input ('Razão: '))
contador = 1
resultado = primeiro_termo
total = 0
a_mais = 10

while a_mais != 0:
    total = total + a_mais
    print ('Resultado = ', end='')
    while contador <= total:
        resultado += razao
        contador += 1
        print (resultado, end=' ')
    a_mais = int (input ('\nQuantos termos a mais você quer mostrar?: '))
print (contador)
print (f'Obrigado por jogar. Você consultou {total} termos.')

In this case the variable contador should not continue adding, as I were assigning new values to the variable a_mais? That wouldn’t stop the condition while to work? Once the aggregate value in the variable contador would be greater than the value of the variable total?

The print that I made of the counter in the penultimate line shows that it is adding normally, but still, the condition while is executed as if the contador was zeroed.

Just to be clear, the code is working correctly, my question is understand why it works, since in my understanding of beginner the variable contador should be zero for the condition while be enforceable.

1 answer

3


Make a table test would help to understand better. But anyway, let’s see what happens:

Supposing it was typed primeiro_termo = 1 and razao = 2. The other variables will be:

variable value
accountant 1
outworking 1
total 0
a_more 10

Like a_mais vale 10, he enters the while a_mais != 0.

The line total = total + a_mais is executed, so we have:

variable value
accountant 1
outworking 1
total 10
a_more 10

Then it prints the message "Result = ", and by the values above we have to contador is less than total and therefore enters the while contador <= total.

When executing resultado += razao and contador += 1, we have:

variable value
accountant 2
outworking 3
total 10
a_more 10

He prints the resultado (that is 3), and how contador is still less than total, he continues in the while contador <= total.

This process is repeated several times. I will skip these steps because it will be repetitive - after all, it is a loop :-) - but when contador come to 11, he comes out of while contador <= total. At this point, we will have:

variable value
accountant 11
outworking 21
total 10
a_more 10

Then you read again a value for a_mais. Let’s assume that now I type 1. I mean, right now a_mais will be 1 and so it continues on while a_mais != 0. So he runs the line total = total + a_mais, and then we’ll have:

variable value
accountant 11
outworking 21
total 11
a_more 1

Notice that total has been updated, and so the condition of the while contador <= total continues to be satisfied. That’s why he executes this while again. There is no such story of "while condition is executed as if the counter is zeroed". The contador has not been zeroed, only that the total has been updated and so the condition of the while is still valid.


Just for the record that this code is not printing the first term. In the above example I typed primeiro_termo = 1 and razao = 2 and the first printed number is 3, but if the first term is 1, then you shouldn’t start with 1?

Anyway, I understand that - probably - this is an exercise and such, but only to leave registered, you can do this using the resources of the language itself. If you want a sequence of numbers, use range, which is done just for this. So you can already print and pick up the size more easily (no longer need the counter):

primeiro_termo = int(input('Primeiro termo: ')) 
razao = int(input('Razão: '))
quantidade = 10 # quantidade de termos que será impressa
total = 0

while True:
    numeros = range(primeiro_termo, primeiro_termo + quantidade * razao, razao)
    total += len(numeros)
    print(*numeros, sep=' ', end=' ')
    quantidade = int(input('\nQuantos termos a mais você quer mostrar?: \n'))
    if quantidade == 0:
        break # sai do while
    # nova sequência começa do próximo termo (ou seja, o último a ser impresso + a razão da PA)
    primeiro_termo = numeros[-1] + razao

print(f'Obrigado por jogar. Você consultou {total} termos.')
  • I get it. That’s right, it’s just a while exercise. Actually, I was going to start the first term with 1, but I don’t know how to do that either.

  • 1

    @Marcosfacini To start from 1, just invert (add the ratio only after printing): https://ideone.com/gV3aZs

Browser other questions tagged

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