#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    A logical error of some kind..


    Hi!
    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".

    Code:
    ## This is the offending while loop. 
    
    answer = "yes"
    
    while answer.lower() == "yes" or "y":
        answer = input("\n Would you like to keep on looping? ")
    
    input("\nGoodbye!")
    Thanks so much for your.... input! LOL
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    439
    Rep Power
    67
    Originally Posted by keeners
    Code:
    while answer.lower() == "yes" or "y":
    This is a classic... In Python, any value that is not zero is true. Hence, y is true:

    Code:
    >>> if "y":
    	print("true")
    
    	
    true
    Further:

    Code:
    answer.lower() == "yes" or "y"
    # is equivalent to:
    (answer.lower() == "yes") or "y"
    And since "y" is True, the whole thing is always True.

    Do it this way:

    Code:
    while answer.lower() in ("yes", "y"):

    Comments on this post

    • Dietrich agrees : nice explanation
    My armada: openSUSE 13.2 (home desktop, work desktop), openSUSE 13.1 (home laptop), Debian GNU/Linux 7.7.0 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0
    of course!

    thanks a heap! it was driving me mad!


IMN logo majestic logo threadwatch logo seochat tools logo