Readability
Firstly, Python doesn't require parentheses ((..)
) around conditionals. So you can just say:
Thirdly, logical separation of code into paragraphs greatly helps readability. A 'paragraph' should make a single 'point', and then you should have a blank line before the next paragraph.
Handling unwelcome scenarios
You should handle corner cases in your code.
Than you can safely use get_user_int
anywhere in your code. You can pass into it a custom message.
Result
Combining everything I mentioned, here's a possible outcome:
# In this program, the user must try to guess a random number generated by the computer
from random import randint
def guess_game():
replay = 1
# Replay allows a user to replay the game without having to call the function again.
# The values are: 1 = Replay, any other character = End
while replay == 1:
lives = get_user_int("How many lives would you like? ")
max_value = get_user_int("Please choose the largest number that can be generated: ")
rand_num = randint(0, max_value)
num_of_guesses = 1 #keeps track of the number of guesses made by the user
while num_of_guesses <= lives:
guess = get_user_int("Please enter your guess: ")
if guess == rand_num:
print("Good guess, that is correct! You got the right answer on guess number", num_of_guesses, ", well done!\n")
break
else:
print("Unlucky, that guess was incorrect. You have", (lives-num_of_guesses), "lives remaining.\n")
num_of_guesses += 1
if num_of_guesses > lives:
print("You have run out of guesses. The correct answer was:", rand_num)
replay = int( input("\nWould you like to play again? Enter 1 for yes, any other character for no: ") )
if replay != 1:
print("Thank you for playing. See you next time")
def get_user_int(message='Enter a number: '):
while True:
try:
return int(input(message))
except ValueError:
print('Enter a valid number.')
guess_game()