Simple errors 4


#1

Hi everybody,

İ have a simple question for you, i think that i should use "or" in my while loop. However an infinite loop occurs when i use the cod which is below.

while choice!="y" or choice!="n" :

But the right solution is like this, but i didn't understand the idea of doing that.

while not choice == "y" or choice == "n":

so, what is the difference between using "while not" and "choice!=y" ?

Thanks in advance


#2

Hi @gartuns ,

Your code needs to keep prompting the user until the user enters either y or n.

It is important to remember that when a condition containing comparators and boolean operators is evaluated, the comparators are evaluated first, then the boolean operators are applied in the following order, unless parentheses are used to control that order
- not
- and
- or
Accordingly, this ...

while choice!="y" or choice!="n" :

... is equivalent to this ...

while (choice!="y") or (choice!="n" ):

Let's consider three cases.

1) The user enters y
This makes the portion of the expression to the right of the or operator True, so the entire expression is True. Therefore, the loop continues to iterate, when it should not, because the user has entered a valid answer.

2) The user enters n
This makes the portion of the expression to the left of the or operator True, so the entire expression is True. Therefore, the loop continues to iterate, when it should not, because the user has entered a valid answer.

3) The user enters m, for maybe
This makes both portions of the expression True, so the entire expression is True. Therefore, the loop continues to iterate, which it should do, because the user has entered an answer that is unacceptable.

The overall problem with the above is that if the user enters a valid answer, the loop continues, and there is no way to break out of it, except to crash the program.

One good choice for the loop header would be this ...

while choice != "y" and choice != "n":

The above condition is True as long as the user entered neither y nor n. You can consider both parts of the expression, in order to verify that, because the loop continues while both parts of the expression are True. A valid y or n breaks out of the loop, because that makes one part of the expression False. Since we have an and operator, the entire expression then becomes False.

This would also work ...

while not (choice == "y" or choice == "n"):

#4

choice=raw_input('Enjoying the course? (y/n)')
y="y"
n="n"
while choice!=y and choice!=n:
choice=raw_input("Sorry, I didn't catch that. Enter again: ")

"this is the answer"