Blog Post #45: Part 2 Recap & Project: The Number Guessing Game

Welcome to the grand finale of Part 2! We’ve journeyed through the core of what makes programs “smart”: logic and control flow. You now have the tools to make your programs make decisions, repeat actions, and follow different paths based on various conditions.

As with our last section, we’ll first briefly recap the powerful concepts you’ve learned in Part 2. Then, we’ll combine them all to build a fun, interactive, and complete game from scratch: the classic Number Guessing Game.

Part 2 Recap: Logic and Control Flow

In this section, we moved beyond simple, linear scripts and learned how to direct the flow of our programs.

  • Decision Making: We started with the foundation of all logic: boolean values (True/False), Boolean Expressions (Post #21), and the Pythonic concept of Truthy and Falsy values (Post #24). We then learned how to use comparison operators (Post #22) and logical operators (and, or, not) (Post #23) to build the conditions for our decision-making blocks: if (Post #25), if-else (Post #26), and the powerful if-elif-else chain (Post #27).
  • Repetition (Loops): We explored the two main ways to repeat code. We learned the while loop for indefinite iteration (Post #31) and the for loop for definite iteration over sequences (Post #34), often paired with the handy range() function (Post #35). We also learned how to choose the right loop for the job (Post #36).
  • Fine-Tuning Control: We gained precise control over our loops with the break (Post #38) and continue (Post #39) statements, and even learned about Python’s unique loop else block (Post #40).
  • Combining Structures: Finally, we saw how the real power emerges when we combine these concepts, such as nesting loops (Post #41) or placing if statements inside for loops (Post #44).

Project: The Number Guessing Game

It’s time to build a game! The computer will think of a secret number between 1 and 100, and our job is to guess it. The program will give us hints of “Too high!” or “Too low!” until we guess the number correctly.

Step 1: Generating a Secret Number

To make the game replayable, the secret number needs to be different every time. We can achieve this by using Python’s built-in random module, which contains tools for generating random numbers.

At the very top of your new guessing_game.py file, you need to import the module. Then, you can use random.randint(a, b) to get a random integer between a and b (inclusive).

import random

# Generate a random integer between 1 and 100
secret_number = random.randint(1, 100)

Step 2: The Main Game Loop

We don’t know how many guesses the player will need, so this is a perfect use case for an indefinite loop. As we saw in Post #38, a while True: loop that we exit with break is a great pattern for this kind of game.

# Game introduction
print("--- Welcome to the Number Guessing Game! ---")
print("I'm thinking of a number between 1 and 100.")

while True:
    # Game logic will go here

Step 3: Getting and Checking the Guess

Inside our loop, we need to ask the player for their guess, convert it to an integer, and then use an if-elif-else chain to compare it to the secret_number.

  1. If the guess is too low, we print a hint.
  2. If the guess is too high, we print a different hint.
  3. If the guess is correct, we print a success message and break out of the loop to end the game.

This logic will go inside our while True: loop.

    # Get the player's guess as a string
    guess_str = input("Make a guess: ")
    # Convert the string to an integer
    guess = int(guess_str)

    # Compare the guess to the secret number and give hints
    if guess < secret_number:
        print("Too low! Try again.")
    elif guess > secret_number:
        print("Too high! Try again.")
    else:
        print(f"You got it! The number was {secret_number}.")
        break # Exit the loop because the game is over

The Complete Code

Putting it all together, our complete, functional game looks like this.

import random # Import the random module

# Generate a random integer between 1 and 100 (inclusive)
secret_number = random.randint(1, 100)

# Game introduction
print("--- Welcome to the Number Guessing Game! ---")
print("I'm thinking of a number between 1 and 100.")

# The main game loop
while True:
    # Get the player's guess as a string
    guess_str = input("Make a guess: ")
    # Convert the string to an integer
    guess = int(guess_str)

    # Compare the guess to the secret number and give hints
    if guess < secret_number:
        print("Too low! Try again.")
    elif guess > secret_number:
        print("Too high! Try again.")
    else:
        print(f"You got it! The number was {secret_number}.")
        break # Exit the loop because the game is over

Congratulations and What’s Next for Part 3

Fantastic work! You’ve built a complete, interactive game that uses conditional logic, loops, user input, and type casting. You now have a solid command of the fundamental control flow structures in Python.

In Parts 1 and 2, we worked with simple data types like numbers and strings. To build more complex and powerful applications, we need ways to store and organize collections of data. In Part 3: Core Data Structures, we will dive into the workhorses of Python data management: lists, tuples, dictionaries, and sets.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment