Puzzle 2 – create an AI bot to guess a number

Step 2 – set up the loop

Here's the second part of the Scratch program. This sets up a loop that keeps going until the player tells the computer that it has guessed the answer right.

Scratch code image

A loop is an example of using repetition in code. It repeats the code until the answer (the guess) is the same as the number.

There's one major thing that needs to happen different in Python here.

  1. Python doesn't have a Repeat – Until loop. So we need to use a While loop instead. This works a bit differently: we have to say "repeat this while the answer (the guess) does not equal the number. To say "does not equal" in Python we use != which is a bit odd.
  2. Add the while line, but use the variable name from your program, not thing1

    IMPORTANT: you need to indent the next line of code

  3. Then add a line to ask the player if the AI's guess is right. This is quite complex. You can change anything in green, but be really careful about the rest of the code
  4. Then you need to add one to each of your variables which keep track of numbers – look at the Scratch code to see what to change

    The .upper() bit at the end of the line converts whatever the user types into UPPER CASE. Which makes checking things easier

  5. Save your program
  6. Run your program – you can "kill" the program by closing the running window down if you need to

Code helper image

That's the loop set up. This just leaves the last line of code.