I have an assignment to write a number-guessing game, with these requirements:
- End the game when the guess is correct
- Tell if the guess number is smaller or larger when the guess is wrong
- Keep running until there are 5 failed attempts
I wrote this code that uses a for
loop:
number = 69
for x in range (5):
guess = float(input('Please enter a number:'))
if guess == number:
print('Congratulations')
break
elif guess < number:
print('Number too small')
else:
print('Number too large')
for x in range(5):
if guess != number:
print('Game Over')
break
How can I modify the code to use a while
loop instead? I got this far:
number = 69
guess=float(input('Please enter a number: '))
while True:
if guess == number:
break
guess=float(input('Please enter a number: '))
print('Congratulations')
but this does not verify the guess or check the number of attempts.
When I tried to add the rest of the logic, like so:
number = 69
guess=float(input('Please enter a number: '))
def guess_game():
while True:
if guess == number:
break
guess=float(input('Please enter a number: '))
if guess < number:
print('Number too small')
else:
print('Number too large')
x = 0
while x < 6:
guess_game()
if guess != number:
print('Game Over')
break
print('Congratulations')
I got this error: 'UnboundLocalError: local variable 'guess' referenced before assignment'
What is wrong, and how do I fix it?