Higher-Lower Game with Python

The Higher-Lower game is a classic and entertaining guessing game that challenges players to guess a randomly generated number within a specified range. By implementing this game using Python, beginners can gain valuable coding experience while creating an interactive and enjoyable gaming experience.

In this article, we will explore the step-by-step process of creating a Higher-Lower game with Python, providing detailed explanations and code examples along the way. Whether you're a novice programmer looking to enhance your skills or simply seeking a fun coding project, this guide will help you build a fully functional game.

Understanding the Game Rules

The Higher-Lower game follows simple rules. The game begins by generating a random number within a predefined range, such as between 1 and 100. The player's objective is to guess this randomly generated number. After each guess, the game provides feedback on whether the guessed number is higher or lower than the actual number. The player continues making guesses until they find the correct number.

Setting Up the Game

To build the Higher-Lower game, we first need to set up the basic components. We import the random module to generate random numbers and define our game parameters ?

import random

lower_bound = 1
upper_bound = 100
number_of_guesses = 0

# Generate the random number
random_number = random.randint(lower_bound, upper_bound)
print(f"I'm thinking of a number between {lower_bound} and {upper_bound}...")
I'm thinking of a number between 1 and 100...

Basic Game Implementation

Here's a complete working version of the Higher-Lower game with proper input validation and game loop ?

import random

def higher_lower_game():
    lower_bound = 1
    upper_bound = 100
    number_of_guesses = 0
    
    # Generate random number
    random_number = random.randint(lower_bound, upper_bound)
    
    print(f"Welcome to the Higher-Lower Game!")
    print(f"I'm thinking of a number between {lower_bound} and {upper_bound}")
    
    while True:
        try:
            # Get user input
            guess = int(input("Enter your guess: "))
            
            # Validate input range
            if guess < lower_bound or guess > upper_bound:
                print(f"Please enter a number between {lower_bound} and {upper_bound}")
                continue
            
            number_of_guesses += 1
            
            # Check the guess
            if guess == random_number:
                print(f"Congratulations! You guessed the number correctly!")
                print(f"It took you {number_of_guesses} attempts.")
                break
            elif guess < random_number:
                print("Too low! Try a higher number.")
            else:
                print("Too high! Try a lower number.")
                
        except ValueError:
            print("Invalid input! Please enter a valid number.")

# Run the game
higher_lower_game()
Welcome to the Higher-Lower Game!
I'm thinking of a number between 1 and 100
Enter your guess: 50
Too low! Try a higher number.
Enter your guess: 75
Too high! Try a lower number.
Enter your guess: 63
Congratulations! You guessed the number correctly!
It took you 3 attempts.

Enhanced Version with Features

Let's create an enhanced version with additional features like difficulty levels and play again option ?

import random

def enhanced_higher_lower_game():
    print("=== Enhanced Higher-Lower Game ===")
    
    # Difficulty selection
    difficulty = input("Choose difficulty (easy/medium/hard): ").lower()
    
    if difficulty == "easy":
        lower_bound, upper_bound = 1, 50
    elif difficulty == "medium":
        lower_bound, upper_bound = 1, 100
    elif difficulty == "hard":
        lower_bound, upper_bound = 1, 200
    else:
        print("Invalid difficulty. Using medium (1-100)")
        lower_bound, upper_bound = 1, 100
    
    while True:
        number_of_guesses = 0
        random_number = random.randint(lower_bound, upper_bound)
        
        print(f"\nI'm thinking of a number between {lower_bound} and {upper_bound}")
        
        while True:
            try:
                guess = int(input("Enter your guess: "))
                
                if guess < lower_bound or guess > upper_bound:
                    print(f"Please enter a number between {lower_bound} and {upper_bound}")
                    continue
                
                number_of_guesses += 1
                
                if guess == random_number:
                    print(f"Excellent! You found it in {number_of_guesses} attempts!")
                    break
                elif guess < random_number:
                    print("Higher!")
                else:
                    print("Lower!")
                    
            except ValueError:
                print("Please enter a valid number!")
        
        # Play again option
        play_again = input("Play again? (y/n): ").lower()
        if play_again != 'y':
            print("Thanks for playing!")
            break

# Run enhanced game
enhanced_higher_lower_game()
=== Enhanced Higher-Lower Game ===
Choose difficulty (easy/medium/hard): medium

I'm thinking of a number between 1 and 100
Enter your guess: 50
Higher!
Enter your guess: 75
Lower!
Enter your guess: 62
Excellent! You found it in 3 attempts!
Play again? (y/n): n
Thanks for playing!

Key Programming Concepts

This game demonstrates several important Python concepts:

  • Random number generation using random.randint()
  • User input validation with try-except blocks
  • Control flow using while loops and conditional statements
  • Function organization for better code structure
  • String formatting with f-strings for user-friendly output

Comparison of Approaches

Feature Basic Version Enhanced Version
Difficulty Levels Fixed (1-100) Multiple options
Error Handling Basic Comprehensive
Replay Option No Yes
Code Structure Linear Function-based

Conclusion

Creating a Higher-Lower game with Python is an excellent way to practice fundamental programming concepts while building something interactive and fun. The game demonstrates essential skills like user input handling, conditional logic, loops, and error management that form the foundation of many programming projects.

Updated on: 2026-03-27T09:05:25+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements