w3resource

Python Guess the Number Game Project: Solutions and Explanations


Guess the Number Game:

Make a game where the computer generates a random number, and the player has to guess it.

Input and Output values:

Input values:
Player guesses the randomly generated number.

Output value:
Feedback on whether the guess is correct, too high, or too low. Repeat until the correct number is guessed.

Example:

Input values:

Enter your guess: 7

Output value:

Too low! Try again.

Input values:

Enter your guess: 12

Output value:

Too high! Try again.

Input values:

Enter your guess: 10

Output value:

Correct! You guessed the number.

Here are two different solutions for the "Guess the Number" game in Python. Both solutions will have the computer generate a random number, and the player will attempt to guess it until they are correct, with feedback provided for each guess.

Solution 1: Basic Approach using a While loop

Code:

# Solution 1: Basic Approach Using a While Loop

# Import the 'random' module to generate a random number
import random

# Generate a random number between 1 and 100 (inclusive)
secret_number = random.randint(1, 100)

# Initialize a variable to store the player's guess
guess = None

# Start a loop that continues until the correct guess is made
while guess != secret_number:
    # Get the player's guess and convert it to an integer
    guess = int(input("Enter your guess: "))

    # Check if the guess is less than the secret number
    if guess < secret_number:
        print("Too low! Try again.")
    # Check if the guess is greater than the secret number
    elif guess > secret_number:
        print("Too high! Try again.")
    # If the guess is correct, congratulate the player
    else:
        print("Correct! You guessed the number.")

Output:

Enter your guess: 12
Too low! Try again.
Enter your guess: 19
Too low! Try again.
Enter your guess: 50
Too high! Try again.
Enter your guess: 35
Too low! Try again.
Enter your guess: 45
Too high! Try again.
Enter your guess: 40
Too low! Try again.
Enter your guess: 42
Too low! Try again.
Enter your guess: 43
Too low! Try again.
Enter your guess: 44
Correct! You guessed the number.

Explanation:

  • Uses a while loop to repeatedly prompt the player for their guess until they guess correctly.
  • The random.randint(1, 100) function generates a random number between 1 and 100.
  • After each guess, the program checks if the guess is too low, too high, or correct and provides appropriate feedback.
  • This approach is simple and effective, using a loop for repeated guesses.

Solution 2: Using a Function and Recursion

Code:

# Solution 2: Using a Function and Recursion

# Import the 'random' module to generate a random number
import random

# Generate a random number between 1 and 100 (inclusive)
secret_number = random.randint(1, 100)

# Define a function to handle the guessing logic
def guess_number():
    """Recursive function to guess the number."""
    # Get the player's guess and convert it to an integer
    guess = int(input("Enter your guess: "))

    # Check if the guess is less than the secret number
    if guess < secret_number:
        print("Too low! Try again.")
        # Call the function recursively to ask for another guess
        guess_number()
    # Check if the guess is greater than the secret number
    elif guess > secret_number:
        print("Too high! Try again.")
        # Call the function recursively to ask for another guess
        guess_number()
    # If the guess is correct, congratulate the player
    else:
        print("Correct! You guessed the number.")

# Start the guessing game by calling the function
guess_number()

Output:

Enter your guess: 20
Too low! Try again.
Enter your guess: 30
Too high! Try again.
Enter your guess: 25
Too high! Try again.
Enter your guess: 22
Too high! Try again.
Enter your guess: 21
Correct! You guessed the number.

Explanation:

  • Uses a recursive function guess_number() to handle the guessing logic.
  • The function calls itself recursively after each guess if the guess is incorrect (either too low or too high).
  • If the guess is correct, the function prints a congratulatory message and stops further recursion.
  • This approach demonstrates the use of recursion to achieve the same outcome, providing a different way to handle repeated prompts.

Note:
Both solutions achieve the desired outcome of a "Guess the Number" game, with Solution 1 using a loop-based approach and Solution 2 using recursion to repeatedly ask for the player's guess. The recursive approach may be less efficient for large numbers of guesses due to potential stack overflow. However, it demonstrates a different way of structuring program logic.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/projects/python/python-guess-the-number-game-project.php