Guess the number

The computer thinks of a number and says higher or lower. Teaches random numbers, the while loop and counting guesses.

Open in Tokbit Level: Intermediate. Free in the browser, nothing to install, no account needed.

Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.

Flowchart

Flowchart of the Guess the number example

Python program

The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.

"""Guess a number from 1 to 100 with more/less hints. Teaches a while loop."""
from random import randint

secret: int = randint(1, 100)
guess: int = 0
tries: int = 0
print("I'm thinking of a number from 1 to 100.")
# Repeats until the guess is right; we do not know how many rounds.
while guess != secret:
    guess = int(input("Your guess:"))
    tries = tries + 1
    if guess < secret:
        print("Higher.")
    else:
        if guess > secret:
            print("Lower.")
print("You got it! Guesses:", tries)

Follow-up tasks

Tasks in which you change the example (with a model solution):

All examples