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:
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:
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.