I tried to make a simple “guess game”, but all it does is asks for an input and that’s it.
Here is my code:
import random
def guess():
if a == b:
print "Correct!"
n = input("Press 0 to quit or 1 to try again.")
if n == 0:
print ""
if n == 1:
return guess
else:
print "Wrong! "
n = input("Press 0 to quit or 1 to try again.")
if n == 0:
print ""
if n == 1:
return guess
a = random.randint(1,2000)
b = input("Guess a number between 1 and 2000 ")
You are not calling the
guessfunction. You should add at the end:and you should modify the
guessfunction as follows:This is necessary because you need to pass the values
aandbto yourguessfunction. Otherwise,aandbinside theguessfunction have no value (they are just undefined local variables) and Python would not know what to do.By doing the above, you can at least check if you guessed correctly or not. But you’ll need to modify the code a bit more if you want to repeat the guessing.
As an example, here is an updated version of the guess game that does work:
The function
guessnow takes one integer: the integer that needs to be guessed. Inside the function, we ask the user for an integer and we store it inb. We then tell the user whether the guess is correct or not. If the guess is correct then the functionguessjust ends.If the guess was wrong then we give the user to chance to try again if they want to. Note that we are now checking
if n == "0":instead ofif n == 0:becausenis a string, not an integer. If the user typed1then we callguessagain with the integer to be guessed (a) and the whole thing starts again.