Lesson goal: Guess a number

Previous: Mouse clicks | Home | Next: I'll guess your number

One of the classic (and early) games to write on a computer is a "guess my number game." The computer chooses a random number from 1 to 100, and your job is to try and guess the number in as few tries as possible.

Continuing your learning of how while loops work, notice we again define a variable called done, which initially starts out as false. The number to guess is also selected and stored in a variable called n. Input is read from the keyboard (which is the player's guess) into variable g. Notice the if g == n statement. If this is true, its body sets done = true, which will terminate the while-loop.

Now you try. Play the game a few times and see if you can understand how it works.

Type your code here:

See your results here:

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.