Issue
I'm trying to make a guessing game that allows three tries. So far, it works exactly as I want it to, but the user isn't allowed three tries. After the first, the program just ends and you have to restart it to continue playing. I don't want the program to end until three tries are finished.
How can I do this?
Current code:
from random import randint
guesses = 3
secret = randint(0, 999)
number = 1
PreGuess = input("Enter a number: ")
try:
guess = int(PreGuess)
except:
number = 0
if input:
if number == 1:
if 0 < guesses:
if 0 <= guess <= 999:
if guess < secret:
print("too low")
guesses -= 1
elif guess > secret:
print("too big")
guesses -= 1
elif guess == secret:
print("correct")
else:
print("Number is not in the playable range!")
else:
print("game over")
else:
print("Please enter a number.")
Solution
Notice that you only call input() once - at the beginning. You also do not have any loops that make the program jump back to the beginning to allow the player to make another guess.
What you should do is enclose the part that you want repeated in a while loop.
...
while guesses > 0:
PreGuess = input("Enter a number: ")
...
if input:
if number == 1:
if 0 <= guess <= 999:
if guess < secret:
print("too low")
guesses -= 1
elif guess > secret:
print("too big")
guesses -= 1
elif guess == secret:
print("correct")
break
else:
print("Number is not in the playable range!")
else:
print("Please enter a number.")
Then, after the while loop, you can check if the loop was terminated because the user won or if the user made 3 incorrect guesses. If the user made 3 incorrect guesses, guesses
would equal 0, and if the user successfully guessed the number, guesses
would be greater than 0.
if guesses == 0:
print("game over")
Answered By - jdabtieu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.