user2280173
user2280173

Reputation: 11

Python loop keeps repeating? Why?

Another_Mark = raw_input("would you like to enter another mark? (y/n)")

while Another_Mark.lower() != "n" or Another_Mark.lower() != "y":
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

if Another_Mark == "y":
    print "blah"

if Another_Mark == "n":
    print "Blue"

This is not the actual code I'm using except for the 1st three lines. anyways my question is why does the while loop keep repeating even when I input a value 'y' or 'n', when it asks again if you want to input another mark on the third line. I'm stuck in a infinitely repeating loop. It shouldn't repeat when the value for Another_Mark is changed to either "y" or "n"

Upvotes: 1

Views: 1695

Answers (4)

Piotr Hajduga
Piotr Hajduga

Reputation: 608

Try:

while Another_Mark.lower() not in 'yn':
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

not in operator returns true if given object is not found in the given iterable and false otherwise. So this is the solution you're looking for :)


This wasn't working due to boolean algebra error fundamentaly. As Lattyware wrote:

not (a or b) (what you describe) is not the same as not a or not b (what your code says)

>>> for a, b in itertools.product([True, False], repeat=2):
...     print(a, b, not (a or b), not a or not b, sep="\t")
... 
True    True    False   False
True    False   False   True
False   True    False   True
False   False   True    True

Upvotes: 5

chappy
chappy

Reputation: 1107

You need to use AND instead of OR.

It's the way boolean logic distributes. You can say:

NOT ("yes" OR "no")

Or you can distribute the NOT into the parenthesis (which is what you're trying to do) by flipping the OR to an AND:

(NOT "yes") AND (NOT "no")

Upvotes: 1

Rushy Panchal
Rushy Panchal

Reputation: 17552

Your logic behind the looping is wrong. This should work:

while Another_Mark.lower() != "n" and Another_Mark.lower() != "y":
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

Upvotes: 1

n00dle
n00dle

Reputation: 6053

Your loop logic only every comes out true - if the input is "n", then it's not "y" so it's true. Conversely if it's "y" it's not "n".

Try this:

while not (Another_Mark.lower() == "n" or Another_Mark.lower() == "y"):
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

Upvotes: 3

Related Questions