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: openSUSE 13.1 (home desktop, home laptop), Crunchbang Linux 11 (work laptop), Trisquel GNU/Linux 6.0.1 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)
February 9th, 2013, 07:59 AM
thanks a heap! it was driving me mad!