This activity has been adapted from an activity by Al Sweigart from http://inventwithpython.com
We are going to make a game where the computer thinks of a number between 1 and 20, and the player gets up to 6 tries to guess the number. This is what we want it to do:

Here is the code for a number guessing game. Type it out carefully, save it and run it:

Let's look at some of the sections of code to see how this program works.
| # This is a guess the number game. | This line is a comment. Python will ignore everything after the # sign. This just reminds us what this program does. |
| import random | This is an import statement. While Python includes many built-in functions, some functions exist in separate programs called modules. Modules are Python programs that contain additional functions. We use the functions of these modules by bringing them into our programs with the import statement. In this case, we're importing the module random, so that we can use random numbers. |
| number=random.randint(1,20) | This generates a random integer between 1 and 20 (including both 1 and 20). We store the integer in a variable (storage location) called number. Whenever we want to add randomness to our games, we can use the randint() function. And we use randomness in most games. |
| while guessesTaken<6 | Sets up a loop to give the user 6 guesses |
| guessesTaken=guessesTaken + 1 | Keeps count of guesses. Adds 1 after the user has had a guess. |
if guess == number
|
Breaks out of the while loop if the user guesses the right number |
| if guess == number | means the user guessed the number |
| if guess != number | means the user didn't guess the number |
![]() |
|


