Skip to content

Number guessing game

Pip Hey! So we've got a 14-hour cargo run to the outer belt next week and I need something to survive it. Can you build me a little number guessing game? Computer picks a random number, I guess, it tells me if I'm too high or too low, I keep going until I get it. Nothing fancy. Just something to keep my brain from melting 🙏

What you're building

Guess a number between 1 and 100: 50
Too high. Try again.
Guess a number between 1 and 100: 25
Too low. Try again.
Guess a number between 1 and 100: 37
Too low. Try again.
Guess a number between 1 and 100: 43
You got it in 4 guesses!

What you'll need

Hints

The random number. The random module has a function that returns a random integer within a range you specify. Check the modules chapter. It's one line.

The loop. You need something that keeps asking for a guess until the player gets it right. Think about what condition makes it stop, not just what keeps it going.

The types. input() always returns a string. You're comparing it against a number. That comparison won't work the way you expect. Convert before you compare.

Going further

Once the core script works, here are some ways to push it further:

  • Count the guesses. Track how many attempts the player took and show it at the end.
  • Difficulty modes. Let the player choose a range at the start: 1 to 20, 1 to 100, or 1 to 500.
  • Limited attempts. Give the player a fixed number of guesses. Tell them how many they have left each round. If they run out, reveal the answer.
  • Play again. After the game ends, ask if they want another round. Keep a running tally of wins and losses.