Well done.
You could make it better by 'encapsulating' it into a function, so that you can use it or use a modified version of it in your other projects.
Instead of checking 'maxGuesses' several times, you can make use of logical flags.
personally I prefer using "for loops" if you know number of iterations.
maybe you can improve it by asking the user if he wants to play again or not.
from random import randint
def GuessNumber(maxGuesses=5):
randnumb = randint(1,100)
# a logical flag to check whether user guessed the number or not - at the end of all guesses
user_won = False
for i in range(maxGuesses):
personInput = int(input('What is your guess? '))
if personInput == randnumb:
print()
print('You won! It took you {} guess(es).'.format(i+1))
user_won = True
break
elif personInput > randnumb:
print('Guess lower, {} guess(es) left.'.format(maxGuesses-i-1))
print()
else:
print('Guess higher, {} guess(es) left.'.format(maxGuesses-i-1))
print()
# if user did not guess the number in all guesses
if not user_won:
print()
print('You lost! You ran out of your guesses!')
print('The answer was', randnumb, '!')
=====
update:
a way to play it several times:
Here is what we want to do:
we want to make a function, that works with "any" game.
that function asks the user if he want to play again or not:
______ if he wants to play again, then we run the game again.
______ if he does not want to play again, then end the program.
we can "break" the problem to smaller problems,
by making another function that asks the user if he wants to play again or not:
______ if he want, then that function returns True
______ if he does not want, then it returns False
- I encourage you to stop reading and try to do it yourself, and below is a code to do it.
=====
def playAgain():
"""returns True if user wants to play again, False otherwise."""
while True:
# ask user if he/she wants to play again
play_again = input('Play again? <y/n>:')
# if first character of user's answer is 'y', then return True.
# strip: is used to remove empty spaces that could be in start or end of user's input
# lower: is used to take the first character and make it in lowercase, for example
# if user types 'Yes' or 'yes' both will be accepted, and return True
if play_again.strip().lower()[0] == 'y':
return True
# if user types 'no' - either in lowercase or uppercase - return False
elif play_again.strip().lower()[0] == 'n':
return False
# if user writes another word that does not start with 'y' nor 'n', ask him again - that's why its a loop
else:
print('Wrong input! Please enter "yes" or "no"!')
def playSeveralTimes(game_func):
"""takes game's function - without () - runs it as many times as user wants."""
while True:
# run the game
game_func()
# if user does not want to play again - break out of loop
if not playAgain(): break
# run the game
playSeveralTimes(GuessNumber)