Build Your First Interactive Python Game: Number Guessing

Build Your First Interactive Python Game: Number Guessing CLI

Build Your First Interactive Python Game: Number Guessing CLI

Welcome back to DarchumsTech! Ready to make Python fun and interactive? In this tutorial, we'll build a classic Number Guessing game you can play right in your terminal.

What you’ll learn:

  • Using loops for repeated gameplay
  • Taking and validating user input
  • Conditional logic for feedback
  • Functions to organize code
  • Basic error handling

Step 1: Import the random module

Python's random module lets us generate a random number.

import random

This line imports the module so we can use its functions.

Step 2: Define the game function

We'll wrap our game logic inside a function to keep it organized and reusable.

def guess_number_game():
    print("Welcome to the Number Guessing Game!")
    print("I'm thinking of a number between 1 and 100.")

The print() statements show welcome messages.

Step 3: Generate the secret number

    secret_number = random.randint(1, 100)

This picks a random integer between 1 and 100 (inclusive).

Step 4: Set up a loop for guesses

We allow the player to guess multiple times until they get it right.

    attempts = 0
    while True:

We initialize attempts to count guesses, and use an infinite loop that we break once guessed correctly.

Step 5: Take and validate user input

        try:
            guess = int(input("Make a guess: "))
        except ValueError:
            print("Please enter a valid integer.")
            continue

Here, we try to convert input to an integer, and if it fails, we warn the user and restart the loop.

Step 6: Increase attempt count

        attempts += 1

Every valid guess increments the attempts count.

Step 7: Check the guess and give feedback

        if guess < secret_number:
            print("Too low, try again.")
        elif guess > secret_number:
            print("Too high, try again.")
        else:
            print(f"Congrats! You guessed it in {attempts} tries.")
            break

If the guess is too low or too high, we give feedback. When guessed right, we congratulate and exit the loop.

Step 8: Run the game

Finally, call the function to start playing!

guess_number_game()

Full code snippet for easy copy-paste:

import random

def guess_number_game():
    print("Welcome to the Number Guessing Game!")
    print("I'm thinking of a number between 1 and 100.")
    
    secret_number = random.randint(1, 100)
    attempts = 0

    while True:
        try:
            guess = int(input("Make a guess: "))
        except ValueError:
            print("Please enter a valid integer.")
            continue

        attempts += 1

        if guess < secret_number:
            print("Too low, try again.")
        elif guess > secret_number:
            print("Too high, try again.")
        else:
            print(f"Congrats! You guessed it in {attempts} tries.")
            break

guess_number_game()

What’s next?

  • Try modifying the game to add a maximum number of attempts.
  • Add difficulty levels changing the range of numbers.
  • Build a graphical version using libraries like tkinter.

Subscribe to DarchumsTech to never miss our latest Python tutorials and projects!

Comments