1. Guess the number
1.1. Version 1
import random
# Version 1: Simple one-guess game
print("I have selected a number between 1 and 9. Can you guess it?")
secret_num = random.randint(1, 9)
guess = int(input("Enter your guess: "))
if guess == secret_num:
print("Congratulations! You guessed correctly.")
else:
print("Wrong guess. The number was:", secret_num)
1.2. Version 2
import random
# Version 2: Repeated guessing until correct
print("\nI have selected a number between 1 and 9. Keep guessing until you get it right!")
secret_num = random.randint(1, 9)
while True:
guess = int(input("Enter your guess: "))
if guess == secret_num:
print("Congratulations! You guessed correctly.")
break
elif guess > secret_num:
print("Too high!")
else:
print("Too low!")
1.3. Version 3
import random
# Version 3: Adding a guess counter
print("\nI have selected a number between 1 and 9. How many guesses will you need?")
secret_num = random.randint(1, 9)
guesses = 0
while True:
guess = int(input("Enter your guess: "))
guesses += 1
if guess == secret_num:
print(f"Congratulations! You guessed correctly in {guesses} guesses.")
break
elif guess > secret_num:
print("Too high!")
else:
print("Too low!")
1.4. Version 4
import random
# Version 4: game with replay option
total_guesses = 0
total_games = 0
while True:
secret_num = random.randint(1, 9)
game_guesses = 0
print("\nI have selected a number between 1 and 9. Can you guess it?")
while True:
try:
guess = int(input("Enter your guess (1-9): "))
if 1 <= guess <= 9:
game_guesses += 1
total_guesses += 1
if guess == secret_num:
print("Congratulations! You guessed the number in",
game_guesses, "guesses.")
break
elif guess > secret_num:
print("Too high!")
else:
print("Too low!")
else:
print("Please enter a number between 1 and 9.")
except ValueError:
print("Invalid input. Please enter a number.")
total_games += 1
avg_guesses = round(total_guesses / total_games, 1)
print(
f"Average guesses per game: {avg_guesses} over {total_games} game(s).")
play_again = input("Do you want to play again? (y/n): ").strip().lower()
if play_again != "y":
print("Thanks for playing!")
break
1.5. Version 5
Modular design: - The game logic is split into clearly defined functions:
play_game(): Handles a single round of the game.
get_guess(): Manages user input and validation.
generate_secret_number(): Generates a random number.
check_guess(): Compares the user’s guess to the secret number and provides feedback.
main(): Oversees game flow, tracking stats and replay options.
Docstrings: - Each function includes a clear docstring explaining its purpose, inputs, and outputs. - This enhances maintainability and makes the codebase easier to understand for future development.
Compared to the previous version, this update emphasizes better structure by separating feedback logic from the main game loop. The code is now more modular, extendable, and professional — a solid foundation for future improvements.
import random
def play_game():
"""
Plays a single round of the number guessing game.
Generates a random number and prompts the user to guess until correct.
Returns the number of guesses made.
"""
secret_num = generate_secret_number()
game_guesses = 0
print("\nI have selected a number between 1 and 9. Can you guess it?")
while True:
guess = get_guess()
game_guesses += 1
if check_guess(secret_num, guess, game_guesses):
return game_guesses
def check_guess(secret_num, guess, game_guesses):
"""
Compares the user's guess to the secret number.
Provides feedback if the guess is too high, too low, or correct.
Returns True if the guess is correct, otherwise False.
"""
if guess == secret_num:
print("Congratulations! You guessed the number in", game_guesses, "guesses.")
return True
elif guess > secret_num:
print("Too high!")
else:
print("Too low!")
return False
def get_guess():
"""
Prompts the user for a guess and validates input.
Ensures the guess is an integer between 1 and 9.
Returns the valid guess.
"""
while True:
try:
guess = int(input("Enter your guess (1-9): "))
if 1 <= guess <= 9:
return guess
else:
print("Please enter a number between 1 and 9.")
except ValueError:
print("Invalid input. Please enter a number.")
def generate_secret_number():
"""
Generates and returns a random integer between 1 and 9.
"""
return random.randint(1, 9)
def main():
"""
Main function to run the number guessing game.
Tracks total games played and calculates average guesses per game.
Offers the option to replay or exit the game.
"""
total_guesses = 0
total_games = 0
while True:
game_guesses = play_game()
total_guesses += game_guesses
total_games += 1
avg_guesses = round(total_guesses / total_games, 1)
print(f"Average guesses per game: {avg_guesses} over {total_games} game(s).")
play_again = input("Do you want to play again? (y/n): ").strip().lower()
if play_again != "y":
print("Thanks for playing!")
break
if __name__ == "__main__":
main()