February 9th, 2013, 07: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, 08: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: openSUSE 13.2 (home desktop, home laptop, work desktop), Ubuntu 14.04 LTS (server), OpenELEC 5.0 (HTPC), Debian GNU/Linux 7.7.0 (mini laptop), Android 4.2.1 (tablet)
February 9th, 2013, 08:59 AM
thanks a heap! it was driving me mad!