Skip to content

Project: Guessing Game

This is your first real project. The computer picks a secret number between 1 and 100. You guess. It says “too small” or “too big” until you get it right, and then it tells you how many tries you needed.

It’s a small program, but it pulls together a lot of what you’ve learned: variables, if/elif/else, while loops, break and continue, try/except, reading input and random numbers. We’ll build it one step at a time, and every step is a complete program you can run.

Here’s a real game, played on our machine:

Guess the number! (1 to 100)
Your guess: 50
Too small!
Your guess: hello
That's not a whole number. Try again!
Your guess: 75
Too big!
Your guess: 62
Too big!
Your guess: 56
You got it in 4 attempts!

Two friendly details: when the player types hello, the game doesn’t crash, it asks again. And that bad input doesn’t count as an attempt.

Make a folder for the project and a file called guess.mojo in it. If you set up Mojo with uv as in Mojo Get Started, work inside that project folder so the mojo command is available. Run the file any time with:

Terminal window
mojo run guess.mojo

Each step below replaces the whole file. Copy it in, run it, read the explanation, then move on.

input() prints a prompt, waits for the player to type a line and press Enter, and gives you that line as a String:

def main():
try:
var guess = input("Please type your guess: ")
print(t"You guessed: {guess}")
except e:
print(t"Could not read a guess: {e}")

This program waits for you, so run it yourself and type something:

Terminal window
mojo run guess.mojo

For example:

Please type your guess: 50
You guessed: 50

Two things to know about input():

  • The line you get back doesn’t include the Enter key, so there’s no \n at the end to clean up. (Python’s input() works the same way.)
  • input() can raise. If there’s nothing left to read, for example when the player presses Ctrl+D, it raises an error that says EOF (“end of file”). That’s why the call sits in a try block: press Ctrl+D instead of typing and you’ll see Could not read a guess: EOF.

The player typed text, but we want a number we can compare. Int(text) converts a String to an Int, and it raises if the text isn’t a whole number. So we wrap it in try/except.

To test this without typing, here’s a list of lines a player might type:

def main():
var inputs: List[String] = ["42", " 7 ", "seven", "-3", "", "3.5"]
for text in inputs:
try:
var n = Int(text.strip())
print(t"'{text}' -> the number {n}")
except e:
print(t"'{text}' -> not a whole number ({e})")

Output:

'42' -> the number 42
' 7 ' -> the number 7
'seven' -> not a whole number (String is not convertible to integer with base 10: 'seven')
'-3' -> the number -3
'' -> not a whole number (String is not convertible to integer with base 10: '')
'3.5' -> not a whole number (String is not convertible to integer with base 10: '3.5')

.strip() removes spaces at both ends, so a sloppy 7 still works. Empty text and 3.5 are rejected, which is what we want: the secret is a whole number. Notice that -3 gets through. It’s a valid Int, just a silly guess. You’ll fix that in the Practice section.

In Python you’d write int(text) and catch ValueError. In Mojo it’s Int(text) and a plain except, because the error is a general Error with a message. The Mojo Type Conversion lesson has more on this.

An if/elif/else chain covers all three cases:

def main():
var secret = 42
var guesses: List[Int] = [10, 42, 99]
for guess in guesses:
if guess < secret:
print(t"{guess}: Too small!")
elif guess > secret:
print(t"{guess}: Too big!")
else:
print(t"{guess}: You win!")

Output:

10: Too small!
42: You win!
99: Too big!

The else branch only runs when the guess is neither smaller nor bigger, which means it’s equal. Nothing fancy, and that’s fine: plain code is easy to read and hard to get wrong.

Step 5: Keep asking until the guess is right

Section titled “Step 5: Keep asking until the guess is right”

Now we loop. We also keep a counter, attempts, and add 1 only when the guess was a real number. To keep this step testable, the “typed” lines come from a list again, and the secret is fixed:

def main():
var secret = 37
# Pretend the player typed these, one per line.
var inputs: List[String] = ["50", "hello", "25", "37"]
var attempts = 0
print("Guess the number! (1 to 100)")
for text in inputs:
print(t"> {text}")
var guess: Int
try:
guess = Int(text.strip())
except:
print("That's not a whole number. Try again!")
continue
attempts += 1
if guess < secret:
print("Too small!")
elif guess > secret:
print("Too big!")
else:
print(t"You got it in {attempts} attempts!")
break
else:
print(t"No more guesses. The number was {secret}.")

Output:

Guess the number! (1 to 100)
> 50
Too big!
> hello
That's not a whole number. Try again!
> 25
Too small!
> 37
You got it in 3 attempts!

A few things are new here:

  • var guess: Int declares the variable without a value. The try block gives it one. If Int() fails, we continue before guess is ever used, and the compiler can see that, so it’s happy.
  • continue jumps straight to the next line of input. The attempt counter isn’t touched, so hello doesn’t count.
  • break ends the loop when the player wins.
  • for ... else: the else block runs only if the loop finished without a break, so it’s the “ran out of guesses” message. Take "37" out of the list and run it again to see it.

A game with the same secret every time isn’t much fun. Mojo’s std.random module has random_si64(min, max), which returns a random Int64 from min to max, both included. The random_si64 reference has the details. There’s one surprise, though. Run this twice:

from std.random import random_si64
def main():
for _ in range(3):
print(random_si64(1, 100), end=" ")
print()

Output:

90 69 44

You get the same three numbers every time. The random number generator starts from the same seed on every run, which is handy for testing and useless for a game. Call seed() first and it starts from a value based on the current time instead:

from std.random import random_si64, seed
def main():
seed()
var secret = Int(random_si64(1, 100))
print("Is it between 1 and 100?", 1 <= secret <= 100)

Output:

Is it between 1 and 100? True

We only print whether it’s in range, so the output is the same every time. Add print(secret) if you want to peek; you’ll see a different number on each run.

Int(...) around the call turns the Int64 into a normal Int. Without it, var secret: Int = random_si64(1, 100) fails with “cannot implicitly convert ‘Int64’ value to ‘Int’”. Mojo doesn’t quietly convert between number types, even when they’re the same size. The Mojo Random Numbers lesson covers the rest of the module.

Here’s everything together. Put it in guess.mojo and play.

from std.random import random_si64, seed
def main():
seed()
var secret = Int(random_si64(1, 100))
var attempts = 0
print("Guess the number! (1 to 100)")
while True:
var text: String
try:
text = input("Your guess: ")
except:
# End of input (Ctrl+D, or a piped file ran out).
print()
print(t"No more input. The number was {secret}. Bye!")
break
var guess: Int
try:
guess = Int(text.strip())
except:
print("That's not a whole number. Try again!")
continue
attempts += 1
if guess < secret:
print("Too small!")
elif guess > secret:
print("Too big!")
else:
print(t"You got it in {attempts} attempts!")
break
Terminal window
mojo run guess.mojo

You’ll see a game like the one at the top of this page. Your secret will be different.

The new part is the first try. main is no longer marked raises, so every call that can raise must be handled. When input() raises because there’s no more input, we say goodbye and break. Without that, pressing Ctrl+D would end the game with an “Unhandled exception” message. Here’s what the friendly version does when we typed 40 and then pressed Ctrl+D:

Guess the number! (1 to 100)
Your guess: 40
Too small!
Your guess:
No more input. The number was 45. Bye!

Calling input() or Int() without handling the error. Both can raise. In a def main(): without raises and without try, the program doesn’t compile:

def main():
var text = input("Your guess: ")
var guess = Int(text)
print(guess)
guess.mojo:2:21: error: cannot call function that may raise in a context that cannot raise
var text = input("Your guess: ")
~~~~~^~~~~~~~~~~~~~~~
guess.mojo:2:21: note: try surrounding the call in a 'try' block
var text = input("Your guess: ")
^
guess.mojo:1:5: note: or mark surrounding function as 'raises'
def main():
^
mojo: error: failed to parse the provided Mojo source module

The notes give you both fixes. For a game, try is the better one: you decide what happens instead of the program stopping.

Comparing the text instead of the number. If you forget to convert, you’re comparing a String with an Int, and Mojo won’t guess what you meant:

def main():
var secret = 42
var text = String("50")
if text < secret:
print("Too small!")
guess.mojo:4:15: error: invalid call to '__lt__': value passed to 'rhs' cannot be converted from 'Int' to 'String'
if text < secret:
~~~~~~~^~~~~~
Mojo/stdlib/std/collections/string/string.mojo:1005:1: note: function declared here
def __lt__(self, rhs: Self) -> Bool # note - synthetic signature
^
mojo: error: failed to parse the provided Mojo source module

Convert with Int(text) first, then compare.

Forgetting seed(). This one compiles and runs, but the secret is the same number on every run. If your game always wants the same answer, check that seed() is called before random_si64.

Once your game works, try these on your own:

  • Check the range. If the guess is below 1 or above 100, say so and don’t count it. (Practice 1.)
  • Limit the attempts. Give the player 7 tries, then show the secret. (Practice 2.)
  • Warmer hints. Say “very close!” when the guess is within 3 of the secret. abs(guess - secret) gives the distance.
  • Play again. When the player wins, ask “Play again? (y/n)” and start a new round with a new secret.
  • Keep a best score across rounds and print it at the end.
  • Move the check into a function like def check(guess: Int, secret: Int) -> String and write tests for it.

Both exercises use a fixed secret and a list of “typed” lines, like Step 5, so you can check your output against ours.

Change the Step 5 program so a number below 1 or above 100 prints Please pick a number from 1 to 100. and doesn’t count as an attempt. Use the inputs ["0", "150", "50", "37"] with secret 37.

Hint: after the try, check the range and continue before attempts += 1.

Show solution
def main():
var secret = 37
var inputs: List[String] = ["0", "150", "50", "37"]
var attempts = 0
for text in inputs:
print(t"> {text}")
var guess: Int
try:
guess = Int(text.strip())
except:
print("That's not a whole number. Try again!")
continue
if guess < 1 or guess > 100:
print("Please pick a number from 1 to 100.")
continue
attempts += 1
if guess < secret:
print("Too small!")
elif guess > secret:
print("Too big!")
else:
print(t"You got it in {attempts} attempts!")
break

Output:

> 0
Please pick a number from 1 to 100.
> 150
Please pick a number from 1 to 100.
> 50
Too big!
> 37
You got it in 2 attempts!

The range check sits between the conversion and the counter, so only real, in-range guesses are counted. guess < 1 or guess > 100 could also be written not (1 <= guess <= 100).

Give the player at most 3 attempts. After the third wrong guess, print Out of attempts! The number was 37. and stop. Use the inputs ["50", "20", "30", "37"].

Hint: a comptime MAX_ATTEMPTS = 3 reads well. Check attempts == MAX_ATTEMPTS after a wrong guess.

Show solution
comptime MAX_ATTEMPTS = 3
def main():
var secret = 37
var inputs: List[String] = ["50", "20", "30", "37"]
var attempts = 0
for text in inputs:
print(t"> {text}")
var guess: Int
try:
guess = Int(text.strip())
except:
print("That's not a whole number. Try again!")
continue
attempts += 1
if guess == secret:
print(t"You got it in {attempts} attempts!")
break
print("Too small!" if guess < secret else "Too big!")
if attempts == MAX_ATTEMPTS:
print(t"Out of attempts! The number was {secret}.")
break

Output:

> 50
Too big!
> 20
Too small!
> 30
Too small!
Out of attempts! The number was 37.

The fourth line, 37, is never read, because the loop stops after the third wrong guess. The conditional expression "Too small!" if guess < secret else "Too big!" works just like in Python.

  • input(prompt) reads one line, without the Enter key. It raises at the end of input, so handle it with try.
  • Int(text.strip()) turns text into a number and raises on bad input. Catching it lets the game ask again instead of crashing.
  • continue skips to the next guess, break ends the loop, and for ... else runs only when the loop wasn’t broken.
  • random_si64(1, 100) includes both ends and returns an Int64; wrap it in Int(...).
  • Without seed(), the random numbers are the same on every run.

Next up: Project: Word Counter, where you count the most common words in a text file.

Quick check

1. The player types 42 and presses Enter. What does input() give you?
2. What happens when Int("seven") runs inside a try block?
3. You call random_si64(1, 100) without seed(). What do you get on each run?
4. When does the else block of a for ... else loop run?