I'm writing a simple text-based game to enhance my knowledge of Python. In one stage of the game, the user needs to guess a number in the set [1, 5] in order to have his or her wish granted. They only get three attempts. I have two questions:
1) Lets assume that genie_number
is randomly selected to be 3. Does this value change after each guess by the user? I don't want the program to randomly choose another integer after each guess. It should remain the same so the user has a 3/5 chance of guessing it correctly.
2) I want to penalize users for not guessing only an integer, and I've done that under the except ValueError
section. But if the user makes three non-integer guesses in a row and exhausts all their attempts, I want the loop to re-direct to else: dead("The genie turns you into a frog.")
. Right now it gives me the error message below. How do I fix this?
'Before I grant your first wish,' says the genie, 'you must answer this
'I am thinking of a discrete integer contained in the set [1, 5]. You ha
(That isn't much of a riddle, but you'd better do what he says.)
What is your guess? > what
That is not an option. Tries remaining: 2
What is your guess? > what
That is not an option. Tries remaining: 1
What is your guess? > what
That is not an option. Tries remaining: 0
Traceback (most recent call last):
File "ex36.py", line 76, in <module>
start()
File "ex36.py", line 68, in start
lamp()
File "ex36.py", line 48, in lamp
rub()
File "ex36.py", line 38, in rub
wish_1_riddle()
File "ex36.py", line 30, in wish_1_riddle
if guess == genie_number:
UnboundLocalError: local variable 'guess' referenced before assignment
Here is my code so far:
def wish_1_riddle():
print "\n'Before I grant your first wish,' says the genie, 'you must answer this riddle!'"
print "'I am thinking of a discrete integer contained in the set [1, 5]. You have three tries.'"
print "(That isn't much of a riddle, but you'd better do what he says.)"
genie_number = randint(1, 5)
tries = 0
tries_remaining = 3
while tries < 3:
try:
guess = int(raw_input("What is your guess? > "))
tries += 1
tries_remaining -= 1
if guess == genie_number:
print "Correct!"
wish_1_grant()
else:
print "Incorrect! Tries remaining: %d" % tries_remaining
continue
except ValueError:
tries += 1
tries_remaining -= 1
print "That is not an option. The genie penalizes you a try. Be careful!"
print "Tries remaining: %d" % tries_remaining
if guess == genie_number:
wish_1_grant()
else:
dead("The genie turns you into a frog.")