1

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!"
Luke Taylor
  • 8,631
  • 8
  • 54
  • 92
teebles
  • 21
  • 1
  • 4
  • the use of recursion here is pointless instead of entering a new function, just use a `while` loop where `playAgain != "yes"` – cmd Apr 01 '14 at 18:33
  • oh yeah the thing had some functionality I was working on at the same time that needed other stuff too but I knew how to complete that. – teebles Apr 01 '14 at 22:32

2 Answers2

3

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

while userGuess != str(compAnswer):
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

compAnswer is a integer, while userGuess is raw_input() which accepts string value from the command line so they are not the same data type, so will never be == so it will keep looping. Try this on the 6th line:

userGuess = int(raw_input("What number am I thinking of?: "))

but you the input you accept is always of numeric type, and this can break if they type non-numeric characters, so better yet, you can validate the user input by putting that line in a try block, and catch ValueError:

try: userGuess = int(raw_input("What number am I thinking of?: ")) except ValueError: print "invalid input"

theferrit32
  • 241
  • 5
  • 7