About the
Lab.

Welcome to the HiLo Game Lab. In this session, we'll build a classic interactive guessing game from scratch using Python. You'll master variables, loops, logic controls, and crash protection.

Recommended Learning

Master Python Basics

Understand Python syntax, lists, loops, and custom logic rules in our comprehensive guide.

Start Learning
Terminal - python hilo.py

Welcome to the HiLo Game!

I have chosen a secret number between 1 and 100.

Enter your guess: 50

> Too Low! Try again.

Enter your guess: 75

> Too High! Try again.

Enter your guess: 62

> Congratulations! You guessed it in 3 attempts!

What we are building

We'll build a complete Terminal-Based HiLo Engine in Python. You will learn to use the random library, read console input, convert types, handle invalid user entries with try-except, structure game loops, and modularize logic with functions.

Lab Objectives

  • 1
    Master console inputs and type conversion.
  • 2
    Implement game loops and conditional verdict logic.
  • 3
    Harden programs against crashes using exception validation.

The Setup

Before writing Python code, we need a local runtime interpreter and a code editor to write scripts.

Python 3

The core interpreted programming runtime.

Download →

VS Code

The lightweight modern text editor.

Get Code →

The Action Plan

  • Install Python 3 on your workstation. Make sure to check the box: "Add Python to PATH" during installation.
  • Create a new folder on your computer named hilo_game and open it inside VS Code.
  • Create a new file named hilo.py inside that folder. This is where we will build the game.
Why Python?

Python is high-level, human-readable, and batteries-included. This makes it perfect for rapid logic development, allowing us to build fully functioning scripts without boilerplate overhead.

The Secret Seed

Every game needs unpredictability. We will use Python's built-in random module to generate a secret number that changes every time we play.

hilo.py
import random

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

print("I have chosen a secret number between 1 and 100!")
Why random.randint?

The random module belongs to Python's standard library. The randint(a, b) function takes two arguments and returns a random integer N such that a ≤ N ≤ b.

Player's Voice

To capture input from players, we use Python's built-in input() function. Since inputs are read as text (strings), we must convert them to integers for numerical comparisons.

hilo.py
import random

secret_number = random.randint(1, 100)
print("I have chosen a secret number between 1 and 100!")

# Read guess from keyboard
guess_str = input("Enter your guess: ")

# Type cast string into an integer
guess = int(guess_str)

print(f"You guessed: {guess}")
Why int() casting?

Computers treat text and numbers differently. Typing `50` yields a string "50". We cannot perform mathematical checks like "50" > 25 directly without triggering a TypeError. Casting with int() parses the text into a real integer.

The Verdict

Let's compare the player's guess with our secret seed using conditional if, elif, and else statements.

hilo.py
# Compare guess to the secret number
if guess < secret_number:
    print("Too Low! Try again.")
elif guess > secret_number:
    print("Too High! Try again.")
else:
    print("Congratulations! You guessed the secret number!")
Python Indentation Rules

Unlike languages that use curly braces {} to group blocks, Python uses indentation spaces (usually 4 spaces). Standard indentation blocks define the execution context under each conditional clause.

Continuous Play

Right now, the game ends after a single guess. We will wrap our input and comparison code in a while True loop so players can guess repeatedly until they find the secret number.

hilo.py
import random

secret_number = random.randint(1, 100)
print("Guess a number between 1 and 100!")

while True:
    guess_str = input("Enter your guess: ")
    guess = int(guess_str)

    if guess < secret_number:
        print("Too Low! Try again.")
    elif guess > secret_number:
        print("Too High! Try again.")
    else:
        print("Congratulations! You guessed the secret number!")
        break  # Exits the game loop
Why while True?

A while True loop creates an infinite cycle because its condition is always met. The break statement provides the exit hatch, terminating the loop immediately when the correct number is guessed.

The Attempt Ledger

Let's make the game competitive by counting how many attempts it takes the player to find the correct number.

hilo.py
import random

secret_number = random.randint(1, 100)
print("Guess a number between 1 and 100!")

# Initialize counter
attempts = 0

while True:
    guess_str = input("Enter your guess: ")
    guess = int(guess_str)
    
    # Increment count on every guess
    attempts += 1

    if guess < secret_number:
        print("Too Low! Try again.")
    elif guess > secret_number:
        print("Too High! Try again.")
    else:
        print(f"Congratulations! You guessed it in {attempts} attempts!")
        break
Why attempts += 1?

The operator += is a shorthand statement for incrementing a variable. attempts += 1 evaluates to attempts = attempts + 1, updating the state of the attempts score.

Crash Protection

Right now, if the user enters a word like "hello" instead of a number, int("hello") throws a ValueError and crashes the program. We will build a try-except guardrail to catch this error.

hilo.py
while True:
    guess_str = input("Enter your guess (or 'quit' to exit): ")
    
    # Exit handler
    if guess_str.strip().lower() == 'quit':
        print(f"Goodbye! The secret number was {secret_number}.")
        break
        
    # Exception guardrail
    try:
        guess = int(guess_str)
    except ValueError:
        print("Invalid entry. Please type a valid integer number.")
        continue  # Return to top of loop
Why Try-Except?

The try block wraps statements that might fail. If a ValueError occurs, Python interrupts the execution and jumps straight to the except block. Instead of crashing, the script gracefully reports the error and continues looping.

Replayability

Let's encapsulate the entire game logic in a custom function named play_game(). This makes it easy to add an outer loop so players can start new games without restarting the script.

hilo.py
import random

def play_game():
    secret_number = random.randint(1, 100)
    attempts = 0
    print("I have chosen a secret number between 1 and 100!")

    while True:
        guess_str = input("Enter your guess (or 'quit'): ")
        if guess_str.strip().lower() == 'quit':
            break
            
        try:
            guess = int(guess_str)
        except ValueError:
            print("Enter a valid number.")
            continue
            
        attempts += 1
        if guess < secret_number:
            print("Too Low!")
        elif guess > secret_number:
            print("Too High!")
        else:
            print(f"Correct! Guess count: {attempts}.")
            break

# Outer Replay Loop
while True:
    play_game()
    play_again = input("Play again? (y/n): ").strip().lower()
    if play_again != 'y' and play_again != 'yes':
        print("Goodbye!")
        break

System Online

Congratulations! Below is your complete, clean game. Save it and execute it.

hilo.py
import random

def play_game():
    secret_number = random.randint(1, 100)
    attempts = 0
    print("I have chosen a secret number between 1 and 100. Try to guess it!")

    while True:
        guess_str = input("Enter your guess (or 'quit' to exit): ")
        
        if guess_str.strip().lower() == 'quit':
            print(f"The secret number was: {secret_number}.")
            break
            
        try:
            guess = int(guess_str)
        except ValueError:
            print("Invalid input. Please enter a valid integer.")
            continue
            
        attempts += 1

        if guess < 1 or guess > 100:
            print("Please choose a number between 1 and 100.")
            continue

        if guess < secret_number:
            print("Too Low! Try again.")
        elif guess > secret_number:
            print("Too High! Try again.")
        else:
            print(f"Congratulations! You guessed it in {attempts} attempts!")
            break

def main():
    while True:
        play_game()
        play_again = input("Do you want to play again? (y/n): ").strip().lower()
        if play_again != 'y' and play_again != 'yes':
            print("Goodbye! Thanks for playing.")
            break

if __name__ == '__main__':
    main()

How to Run

1. Open your terminal or command prompt.
2. Navigate to your project folder: cd path/to/hilo_game
3. Start the game: python hilo.py