jeudi 4 mai 2017

Why do I seem to be stuck in a loop?

I attempted to code a random number guessing game, mostly because I wondered if if/else could function like goto did on my Casio CFX-9850G. I haven't gotten to sanitising the inputs and generating error messages (eg for setting max too low, entering letters instead of numbers, guessing more than max etc). My initial problem is that, while my code isn't generating an error, I can't seem to guess the number, even when I set max to 3 and try 0,1,2,3,4,5. It seems like I've created a loop, and I can't figure out where. here's my code:

import random

print "GUESS MY NUMBER"

max=int(raw_input("Guess number between 1 and what?"))

randomnumber = random.randint(1,max)


def make_guess(guess):
  if guess == randomnumber:
    print "Congratulations, you guessed my number!"
  else:
    guess=raw_input("Guess again?")
    make_guess(guess)

guess=int(raw_input("What is your best guess?"))
make_guess(guess)


print "My number was" ,randomnumber

and it generates:

GUESS MY NUMBER Guess number between 1 and what? 3 What is your best guess? 0 Guess again? 1 Guess again? 2 Guess again? 3 Guess again? 4

Now I wanted the code to loop until a correct guess, but I expected a correct guess would trigger the if code.




Aucun commentaire:

Enregistrer un commentaire