Guessing Game: Guess the Number with Python

2023

In this project, we will discuss a Python code snippet that allows you to play a guessing game. The computer will choose a random number between 1 and 100, and you have to guess the correct number. We'll explain each step of the code and provide the final working code at the end.


Setting Up the Game

To begin, we need to import the random module to generate a random number:

import random

This module will allow us to choose a random number for the computer's selection.

Next, we generate a random number between 0 and 100 using the randrange() function and store it in a variable called computer_number:

computer_number = random.randrange(1, 101)

The randrange() function returns a randomly selected number from the specified range.

Playing the Game

We use a while loop to repeatedly prompt the player to enter a guess until they guess the correct number:

while True:
    guess = int(input("Guess the number between 1 and 100: "))

    if guess == computer_number:
        print("Correct! You guessed the right number.")
        break
    elif guess < computer_number:
        print("Higher! Guess a larger number.")
    else:
        print("Lower! Guess a smaller number.")

In this code, the player is asked to enter a number using the input() function, and the input is converted to an integer using int(). The program then compares the player's guess to the computer's number.

If the guess is correct (guess == computer_number), the program prints "Correct! You guessed the right number" and the break statement exits the loop, ending the game.

If the guess is lower than the computer's number (guess < computer_number), the program prints "Higher! Guess a larger number" to indicate that the player should guess a larger number in their next attempt.

If the guess is higher than the computer's number, the program prints "Lower! Guess a smaller number" to indicate that the player should guess a smaller number in their next attempt.

The loop continues until the player guesses the correct number.


Final Code

Here's the complete Python code for the guessing game:

import random

computer_number = random.randrange(1, 101)

while True:
    guess = int(input("Guess the number between 1 and 100: "))

    if guess == computer_number:
        print("Correct! You guessed the right number.")
        break
    elif guess < computer_number:
        print("Higher! Guess a larger number.")
    else:
        print("Lower! Guess a smaller number.")

That's it! You now have a Python code snippet that allows you to play a guessing game where you have to guess a number chosen by the computer. Feel free to modify the code or use it as a starting point for your own projects. Have fun playing the game!

Back