top of page

Pythons Project for beginners - Post 15: Number Guesser (Computer's Turn)

ree

Let's build a Number Guessing Game where the Computer Guesses. This project is a fantastic twist on the classic game and is a perfect way to learn about a simple but powerful algorithm called binary search.

First, here is the explanation of how the project is built.


How the "Number Guesser (Computer's Turn)" is Made


  1. The Core Idea: The goal is to create a game where the user thinks of a secret number within a range (e.g., 1 to 100), and the computer has to guess it. The user will provide feedback ("high", "low", or "correct") to guide the computer to the right answer.

  2. The Strategy: Binary Search: Instead of guessing randomly, the computer will use a very efficient strategy. It will always guess the number exactly in the middle of the current possible range.

    • It starts with a range of 1 to 100. The first guess will be 50.

    • If the user says "low", the computer knows the secret number must be between 1 and 49. Its new range is now 1-49.

    • If the user says "high", the computer knows the number must be between 51 and 100. Its new range becomes 51-100. This process of cutting the search range in half with each guess is called a binary search, and it's incredibly fast.

  3. Keeping Track of the Range: We need two variables to manage the computer's search range: low (which starts at 1) and high (which starts at 100). The computer's guess is always calculated as (low + high) // 2. The //ensures we get a whole number.

  4. The Main Game Loop: We'll use a while True loop to keep the game running. On each turn inside the loop, the computer will make a guess and ask for feedback. The loop will only end when the user tells the computer its guess was correct.

  5. Getting and Validating User Feedback: We use the input() function to ask the user for feedback. To make the program robust, we'll check the user's input. If they type something other than "high", "low", or "correct", we'll ask them to enter valid feedback.

  6. Adjusting the Range: This is the core of the algorithm.

    • If the user says "high", it means the computer's guess was too low. So, we update the low end of our range to be guess + 1.

    • If the user says "low", the guess was too high. We update the high end of the range to be guess - 1.

    • If the user says "correct", we print a success message and use the break keyword to exit the loop and end the game.



Comments


bottom of page