This is the code i wrote for a guessing game in Python. It asks the user to guess the number between 1 and 1000. If the user is is correct or runs out of guesses, it will ask the user if he wants to play again.
I used sys.exit
to terminate the program. I was just wondering if there was a better way.
import random
import sys
def main():
#Assigning the variables
max_guess = 10
num_guesses = 0
max_number = 1000
number = random.randint(1, max_number)
guess = 0
# Loop
while guess != number:
# Exceeding the guessing limit
if max_guess == num_guesses:
print("You have run out of guesses! The correct answer was " + str(number))
if game_over():
main()
else:
print("Thank you for playing!")
sys.exit(0)
# Asking for the user's guess
guess = int(input("Guess the number between 1 and 1000: "))
#Checking if the guess is appropriate
if guess > 1000 or guess <= 0:
print("The number has to be between 1 and 1000!")
num_guesses -= 1
#Checkng if the guess is too high or too low
if 1000 > guess > number:
print("Lower!")
if 0 < guess < number:
print("Higher!")
# Winning the game
if guess == number:
print("Congratulations your guess is correct!")
if game_over():
main()
else:
print("Thank you for playing!")
sys.exit(0)
num_guesses += 1
# After the game is over
def game_over():
while True:
game_over = input("Would you like to play again(y/n)? ")
if game_over == "y":
return True
elif game_over == "n":
return False
main()
I initially used break
function but it repeated "Guess the number between 1 and 1000: " even after it printed "Thank you for playing". I tried an endless amount of times but break
didn't work. Is it okay to use sys.exit()
in this situation, if not how can i use break
?
Thanks!