🎲 Build a Number Guessing Game

πŸ“Œ Mini project✍️ Written by Mark SullivanπŸ“… Reviewed 2026-04-25⏱ ~45 min read

Classic higher/lower game with attempts counter. Practices: conditionals, loops, I/O, debugging mindset.

What You'll Build

The computer picks a secret number between 1 and 100. The player guesses; you tell them "higher" or "lower" until they get it.

Step 1 β€” Pick a Number

javascript
const secret = Math.floor(Math.random() * 100) + 1;

Step 2 β€” the Guess Loop (Node.Js)

javascript
const readline = require("readline").createInterface({ input: process.stdin, output: process.stdout });

let attempts = 0;
function ask() {
  readline.question("Your guess: ", (input) => {
    attempts++;
    const guess = Number(input);
    if (guess === secret) {
      console.log(`Got it in ${attempts} attempts!`);
      readline.close();
    } else if (guess < secret) {
      console.log("Higher");
      ask();
    } else {
      console.log("Lower");
      ask();
    }
  });
}
ask();

Step 3 β€” Python Version

python
import random
secret = random.randint(1, 100)
attempts = 0

while True:
    guess = int(input("Your guess: "))
    attempts += 1
    if guess == secret:
        print(f"Got it in {attempts} attempts!")
        break
    print("Higher" if guess < secret else "Lower")

Stretch Goals

  • Limit to 7 guesses (binary search territory).
  • Reject non-numeric input.
  • Make the bot version: write a function that always wins in ≀7.

Concepts You Just Used

M
Mark Sullivan
Lead writer Β· 8 yrs full-stack

Mark started coding in 2017 after switching from financial analysis. She's built production systems in Python (Django) and JavaScript (Node + React) at two startups, and has taught intro programming at his local community college since 2022. He owns the curriculum for variables, functions, conditionals, and loops on this site. More about Mark β†’