Python Forum

Full Version: Questions about while loop - why does one work, and the other variant does not
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I am learning Python by studying and doing exercises. Currently I am programming a Tictactoe game as an exercise. it includes the following code snippet:
def GetMove(player):
# Get move for Current Player
    # Clear the Terminal
    Clear()
    # Print Game Title
    Title()
    #Print the Current Board
    PrintCurrBoard()
    #Show the Moves available to the current player
    Choices()
    move=input("\nPlayer {} Please enter the move of your choice: ".format(player))
    response=""
    response=ValidMove(move,player)
    while not response:
        TryAgain=""
        TryAgain=input("That is an Invalid move - Would you like to try again to Continue the Game \
(Y or N)\n\n")
        while TryAgain != "":  # I realize I have to change this statement, it is not what I am working on now.
            GetMove(player)
Now, the above code functions as it is supposed to / correctly, however the <while not response"> was originally written as

while response =="False":
functionally, when written that way, the while loop will only functions if response is actually set equal to false, rather than being set to the return of the ValidateMove function (which is returning True or False, as appropriate). This I do not understand as
while not response:
and

While response == "False":
should be logically equivalent and function in an identical fashion. Help a noob out and explain why my logic seems to be functioning differently than python's.

Wall
Thank You
swgeel
False and "False" are two different things. One is bool and the other is str object.
That said, comparing variable for equality or identity to True or False is against PEP8 recommendations.

Quote:Don’t compare boolean values to True or False using ==:

# Correct:
if greeting:
# Wrong:
if greeting == True:
Worse:
# Wrong:
if greeting is True:

Also note
Truth Value Testing

Quote:By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:
  • constants defined to be false: None and False
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '', (), [], {}, set(), range(0)
Buran: Thank you for instructing a noob and thank you for your answer. I will check out pep 8 and the other suggestion about bbcode. Buran's answer did answer the original question sufficiently
Thank You
swgeek