How to Start Coding – Part 6: Number Guessing Game

Prologue:

Welcome back! Last time, you learned variables, if/else, and loops in Python. Today we’re using them to build your very first Python game: a number guessing game.

Here’s how it works. The computer picks a secret number between 1 and 20. You try to guess it, and the computer tells you if your guess is too high or too low. Keep guessing until you get it!

Let’s begin!

    Chapter 1: The code!

    Open IDLE, click File > New File, and save it as guessing_game.py. Then type this in:

    import random
    
    secret = random.randint(1, 20)
    guess = 0
    
    print("I'm thinking of a number between 1 and 20...")
    
    while guess != secret:
        guess = int(input("Take a guess: "))
    
        if guess < secret:
            print("Too low!")
        elif guess > secret:
            print("Too high!")
        else:
            print("You got it! The number was " + str(secret) + "!")

    Press F5 to play. Since the number is random, your game will be different every time. Here’s an example:

    I'm thinking of a number between 1 and 20...
    Take a guess: 10
    Too high!
    Take a guess: 5
    Too low!
    Take a guess: 8
    You got it! The number was 8!

    Chapter 2: How it works!

    There are three new things in this game.

    1. Random numbers

    import random gives your program a toolbox of random tools. Then random.randint(1, 20) picks a random whole number from 1 to 20. This is just like the pick random (1) to (20) block in Scratch!

    2. The while loop

    while guess != secret: means “keep repeating while the guess is not equal to the secret number.” The != sign means “not equal.” Once you guess right, the loop stops. In Scratch, this is the repeat until <> block.

    3. elif

    elif is short for “else if.” It lets you check more than two options. Our game has three: too low, too high, or just right.

     

    One more small thing: str(secret) turns the number back into text so we can glue it into our message with +. It’s the opposite of int() from last time.

     

    IMPORTANT NOTE

    If you type a word like banana instead of a number, the game will crash with a ValueError. That’s because int() doesn’t know how to turn “banana” into a number. Just run the game again and stick to numbers!

    Chapter 3: Future Steps

    Congrats, you just made your first Python game! In Part 7, we’ll build a Magic 8-Ball that answers your yes-or-no questions, and you’ll learn about lists.

    CHALLENGE

    Make the game count how many guesses it took you. Hint: make a variable called tries that starts at 0, and add 1 to it every time the loop runs.

    If you get stuck or have any questions, feel free to contact me! And leave a comment with how many tries it took you to win!

    Subscribe

    Leave a Comment

    Your email address will not be published. Required fields are marked *

    ×