February 9th, 2013, 06:27 AM
A logical error of some kind..
I'm completely new to this forum (and to python as well!).
Basically, I've been learning python 3.11, and for the life of me, I cant understand why the following code doesn't work the way I want it to (I've tried searching the forums, but I'm afraid I was a tad unsuccessful, sorry).
Anyway the code is as below. I basically want a 'while loop' to keep on um.. looping when the user types in either yes or y. Any other answers would break the loop. However, the code below keeps looping regardless of whether the answer is anything but "yes" or "y".
Thanks so much for your.... input! LOL
## This is the offending while loop.
answer = "yes"
while answer.lower() == "yes" or "y":
answer = input("\n Would you like to keep on looping? ")
February 9th, 2013, 07:41 AM
This is a classic... In Python, any value that is not zero is true. Hence, ”y” is true:
Originally Posted by keeners
>>> if "y":
And since "y" is True, the whole thing is always True.
answer.lower() == "yes" or "y"
# is equivalent to:
(answer.lower() == "yes") or "y"
Do it this way:
while answer.lower() in ("yes", "y"):
Comments on this post
My armada: Debian GNU/Linux 8 (desktop, home laptop, work laptop), Raspbian GNU/Linux 8 (nameserver), Ubuntu 14.04.3 LTS (HTPC), PC-BSD 10.2 (testbed), Android 4.2.1 (tablet)
February 9th, 2013, 07:59 AM
thanks a heap! it was driving me mad!