Sentence while - not true... understanding logic

Asked

Viewed 195 times

0

I’m having a lot of trouble understanding why the program stops when I type n=0.

when type 0 the finished turns to True, and the while logic is just this, no?

I’ve run the program and it’s correct, I’m not getting it. Really the not confuses me a little.

terminou = False
p = i = 0
while (not terminou):
    n = int(input("Digite um número, ou zero para terminar: "))
    if n == 0:
        terminou = True
    else:
        if n % 2 == 0:
            p = p + 1
        else:
            i = i + 1

print ("P = ", p)
print ("I = ", i)
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

2

The program stops because its code determined it. A first place it stops because it completed what it had to do. It can only conclude after it comes out of the loop and the condition of the while is what determines that.

To get into it is waiting for the value of terminou be it False. And why does it have to be that value? Because it has a negation operator in condition, the not, then it inverts the value of the variable. If the value is False he becomes True there in that expression. Like the while hopes that something will be True to perform is what happens, it enters the loop.

From there to get out only when you go through the while and at that moment the expression False, so how do you have a not the value of terminou must be True.

Any amount you enter will fall on else of if and there the value of terminou does not change. Only when you type 0 will you fall into if same. And in this block what you are doing is just the variable having the value True, that reversed is what makes the loop close.

So just follow the flow of the code and it determines what happens.

In fact this code be simplified:

p = i = 0
while (True):
    n = int(input("Digite um número, ou zero para terminar: "))
    if n == 0:
        break;
    else:
        if n % 2 == 0:
            p = p + 1
        else:
            i = i + 1
print ("P = ", p)
print ("I = ", i)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

This way you don’t need a variable controlling the output and you have a command that tells you to leave whenever you want, in a more explicit way that you want to leave, without windings.

  • Thank you, but what I knotted is that at the beginning it is determined that the variable ended = false. so if na while is as not finished, it means to get into the loop wait that finished = true ... right? thanks for the simplified code! :)

  • No, the answer says it’s the opposite of that.

Browser other questions tagged

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