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.
What you’ll build
Section titled “What you’ll build”Here’s a real game, played on our machine:
Guess the number! (1 to 100)Your guess: 50Too small!Your guess: helloThat's not a whole number. Try again!Your guess: 75Too big!Your guess: 62Too big!Your guess: 56You 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.
Step 1: Make a file
Section titled “Step 1: Make a file”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:
mojo run guess.mojoEach step below replaces the whole file. Copy it in, run it, read the explanation, then move on.
Step 2: Read a guess from the keyboard
Section titled “Step 2: Read a guess from the keyboard”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:
mojo run guess.mojoFor example:
Please type your guess: 50You guessed: 50Two things to know about input():
- The line you get back doesn’t include the Enter key, so there’s no
\nat the end to clean up. (Python’sinput()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 saysEOF(“end of file”). That’s why the call sits in atryblock: press Ctrl+D instead of typing and you’ll seeCould not read a guess: EOF.
Step 3: Turn the text into a number
Section titled “Step 3: Turn the text into a number”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.
Step 4: Compare the guess with the secret
Section titled “Step 4: Compare the guess with the secret”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)> 50Too big!> helloThat's not a whole number. Try again!> 25Too small!> 37You got it in 3 attempts!A few things are new here:
var guess: Intdeclares the variable without a value. Thetryblock gives it one. IfInt()fails, wecontinuebeforeguessis ever used, and the compiler can see that, so it’s happy.continuejumps straight to the next line of input. The attempt counter isn’t touched, sohellodoesn’t count.breakends the loop when the player wins.for ... else: theelseblock runs only if the loop finished without abreak, so it’s the “ran out of guesses” message. Take"37"out of the list and run it again to see it.
Step 6: Pick a random secret number
Section titled “Step 6: Pick a random secret number”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 44You 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? TrueWe 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.
Step 7: The complete game
Section titled “Step 7: The complete game”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!") breakmojo run guess.mojoYou’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: 40Too small!Your guess:No more input. The number was 45. Bye!Common mistakes
Section titled “Common mistakes”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 moduleThe 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 heredef __lt__(self, rhs: Self) -> Bool # note - synthetic signature^mojo: error: failed to parse the provided Mojo source moduleConvert 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.
Ideas to extend it
Section titled “Ideas to extend it”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) -> Stringand write tests for it.
Practice
Section titled “Practice”Both exercises use a fixed secret and a list of “typed” lines, like Step 5, so you can check your output against ours.
1. Check the range
Section titled “1. Check the range”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!") breakOutput:
> 0Please pick a number from 1 to 100.> 150Please pick a number from 1 to 100.> 50Too big!> 37You 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).
2. Limit the attempts
Section titled “2. Limit the attempts”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}.") breakOutput:
> 50Too big!> 20Too small!> 30Too 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 withtry.Int(text.strip())turns text into a number and raises on bad input. Catching it lets the game ask again instead of crashing.continueskips to the next guess,breakends the loop, andfor ... elseruns only when the loop wasn’t broken.random_si64(1, 100)includes both ends and returns anInt64; wrap it inInt(...).- 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- input: Mojo std library: the function that reads a line, and what it does at the end of input.
- random_si64: Mojo std library: the range is
[min, max], both included. - seed: Mojo std library: seeding with the time or with a fixed number for repeatable runs.
- Errors and exceptions: Mojo manual: how
raises,tryandexceptwork in Mojo.