Search code examples
pythonpythonista

Python Guessing Game


For some reason the while loop never breaks as if userGuess is never becoming equal to compAnswer. I have it printing the answer at the beginning so we know. Done on Pythonista.

def guessing_game():
    compAnswer = random.randint(1,10)
    print compAnswer
    guesses = 1
    print "Okay, I\'m thinking of a number between 1 and 10."
    userGuess = raw_input("What number am I thinking of?:  ")
    while userGuess != compAnswer:
        userGuess = raw_input("Nope!  try again:  ")
        guesses += 1
    playAgain = raw_input("You got it!  My number was %s and it took you %d guesses.  Play again?:  " % (compAnswer, guesses))
    if playAgain == "yes":
        guessing_game()
    else:
        print "Okay bye!"

Solution

  • compAnswer is an integer, userGuess is a string; if you want them to be equal, use the same type:

    while userGuess != str(compAnswer):