1

I am fairly new to programming, and I am working through the book "Invent Your Own Computer Games with Python". To test that I've understood the chapters, I try to redo whatever game the chapter has been working on and add embellishments without referring to the text for help. I've programmed a certain part differently from the book, but I don't understand why it isn't working.

def chooseletter():
    loop = True
    playerletter = ""
    computerletter = ""
    while playerletter not in "X O".split():
        playerletter = input("What letter would you like to be? X or O? \n").upper
        if playerletter == ("X"):
            computerletter = "O"
        elif playerletter == ("O"):
            computerletter = "X"
        else:
            loop = True
    return [playerletter, computerletter]

For some reason, this code keeps on looping and looping, no matter what I input. When I open the debugger, is says nothing has even been assigned to the variable "playercharacter".

I bet it's something pretty obvious and I'll laugh at myself when someone point out the solution. Thanks for your help.

1 Answer 1

4

You're missing parenthesis from the .upper() method call.

playerletter = input("What letter would you like to be? X or O? \n").upper

should read

playerletter = input("What letter would you like to be? X or O? \n").upper()

The following code

playerletter = input("What letter would you like to be? X or O? \n").upper

assigns the method object of the string returned to the playerletter variable. If you print playerletter after that line you'd get:

<built-in method upper of str object at 0x7fa45670e508>

Now, as python is dynamically typed, it is perfectly valid to compare this value against 'X' or 'O'. Since it matches neither, the else: clause is run, and the condition playerletter not in "X O".split(): is satisfied, since ['X', ' ', 'O'] does not certainly contain <built-in method upper of str object at 0x7fa45670e508>, thus the while loop is repeated ad infinitum.


Here is your code in idiomatic Python:

def chooseletter():
    playerletter = ''

    # use a tuple of letters in condition instead of splitting
    while playerletter not in ('X', 'O'):
        playerletter = input("What letter would you like to be? X or O? \n").upper()

    # move the setting of computerletter outside the loop
    # use the X if Z else Y construction for simplicity
    computerletter = 'O' if playerletter == 'X' else 'X'

    # instead of returning 2 values in a list, return a tuple
    return playerletter, computerletter
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help! My mistake was pretty obvious in retrospect. But thank you for going above and beyond and helping me with a problem that I didn't even know that I had!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.