DEV Community

Cover image for The Classic Number Guessing Game πŸ”’: A Perfect Python Starter Project 🎯
Bilal Aslam
Bilal Aslam

Posted on

The Classic Number Guessing Game πŸ”’: A Perfect Python Starter Project 🎯

🎯 Project Goal: Learn Python Basics, Loops, and File I/O

The number guessing game is a rite of passage for every new programmer. It touches on fundamental concepts like variable assignment, conditional logic ($\\text{if}/\\text{elif}/\\text{else}$), loops ($\\text{while}$), and (in this advanced version) file handling to save a high score.

This post will break down the core logic of a Python script for a simple number guessing game that challenges the player to guess a random number between 1 and 100 in the fewest attempts possible.

➑️ You can find the complete, runnable code, including setup instructions for the $\\text{Hi-score.txt}$ file, in the accompanying:
https://github.com/bilal-dev-0x/Number-guessing-game.git


πŸ’‘ Code Breakdown: Key Concepts

Let's explore the essential pieces of the game's logic.

1. Game Setup: Randomness and Initialization

The game begins by selecting a random integer and setting up our counter.

import random
n = random.randint(1, 100)
guesses = 0
Enter fullscreen mode Exit fullscreen mode
  • import random: We use this statement to bring in Python's built-in $\\text{random}$ library.
  • random.randint(1, 100): This line selects the secret number ($\\text{n}$) between 1 and 100, inclusive.
  • guesses = 0: We initialize our attempt counter. This variable will be the final metric for the player's performance and the number we save to the high score file.

2. The Core Logic: The Infinite Loop

The game loop is the heart of the application. We use a $\\text{while True}$ *loop, which runs indefinitely until a *$\\text{break}$ statement is explicitly encountered.

while True:
    guesses += 1
    a = int(input("Guess the number : "))

    if a == n:
        # Success and game over!
        print(f"You guessed correct number in {guesses} attempts.")
        break 

    elif a < n:
        # Clue for the player
        print("Higher number....Please.")

    else:
        # The other clue
        print("Lower number....Please.")
Enter fullscreen mode Exit fullscreen mode
  • while True:: Creates the infinite game loop.
  • guesses += 1: Increments the counter with every single guess.
  • $\\text{if}/\\text{elif}/\\text{else}$: This is the conditional logic that provides the critical feedback loop. If the guess ($\\text{a}$) is correct, we print the result and use break to exit the loop. Otherwise, the player gets a hint to go $\\text{Higher}$ or $\\text{Lower}$.

3. Performance Review: Conditional Messaging

After the player wins and breaks out of the main loop, we evaluate their score based on a few simple tiers. This is another great use of $\\text{if}/\\text{elif}/\\text{else}$ to provide personalized feedback.

if guesses <= 10:
    print("You have done it in some attempts....this is incredible.")

elif 10 < guesses < 20:
    print("You are doing good....improve it more.")

else:
    print("Too much attempts .... try to lower the attempts count.")
Enter fullscreen mode Exit fullscreen mode

4. High Score Management: Reading and Writing to a File

This is the most powerful feature of this script, introducing File I/O. It allows the program to remember the best score even after it's closed and re-opened.

# ... first, read the old high score ...
with open("Hi-score.txt","r") as f:
    content = f.read()

# ... then compare and potentially overwrite ...
if int(content) > guesses:
    with open("Hi-score.txt", "w") as f:
        f.write(str(guesses))
        print(f"High score is {guesses}")
Enter fullscreen mode Exit fullscreen mode
  • Reading ($\\text{"r"}$ mode): We open the $\\text{Hi-score.txt}$ file in read mode to fetch the existing record. The $\\text{with open(...) as f:}$ structure is best practice as it ensures the file is always closed automatically.
  • Comparison: if int(content) > guesses: is the core logic. Since lower is better in this game, we check if the old score ($\\text{content}$) is a higher number (worse score) than our current score ($\\text{guesses}$).
  • Writing ($\\text{"w"}$ mode): If we beat the record, we open the file in write mode ($\\text{"w"}$), which overwrites the old contents with our new, lower score. We must convert the integer $\\text{guesses}$ back to a string using str(guesses) before writing it to the text file.

This simple game covers core programming pillars and offers a great foundation for building more _complex projects_!

Go ahead and fork the repository, run the code, and try to break your own_ high score_!

➑️ Find the full Python script and setup instructions here: [https://github.com/bilal-dev-0x/Number-guessing-game.git]

Top comments (0)