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?
CodePudding user response:
Your loop will be endless if you don't specify the fail scenario (in your case if x = 5) so you need to add that too. Also, don't forget to increment the x variable!
number = 69
guess = float(input('Please enter a number: '))
x = 0
while True:
if x == 4:
print('Game over!')
break
if guess == number:
print('Congratulations!')
break
guess = float(input('Please enter a number: '))
x = 1
CodePudding user response:
You made some good efforts.
This works:
number = 69
while guess != number:
guess = float(input('Please enter a number:'))
if guess < number:
print('too low')
elif guess > number:
print('too high')
else:
print('you got it')
print('game over')
CodePudding user response:
I just used an incrementation variable instead, try this:
number = 69
i = 0
while i < 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')
i =1
if guess != number:
print('Game over')