In this python tutorial, we will explore how to make a simple Guess The Number game using Python.

The Code

import random

def guess_the_number():
# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

attempts = 0

print("Welcome to Guess the Number!")
print("I have selected a number between 1 and 100. Try to guess it.")

while True:
user_guess = int(input("Enter your guess: "))
attempts += 1

if user_guess == secret_number:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
elif user_guess < secret_number:
print("Too low. Try again.")
else:
print("Too high. Try again.")

if __name__ == "__main__":
guess_the_number()

Explanation

Part One: The Setup

  • import random: Imports the random module for generating random numbers.
  • secret_number = random.randint(1, 100): Generates a random integer between 1 and 100 (inclusive) and assigns it to secret_number.
  • attempts = 0: Initializes the variable attempts to 0, which will be used to count the number of attempts.

Part Two: Welcome Message

Prints a welcome message to the user, informing them about the game and the range of numbers they need to guess.

Part Three: Guess Loop

  • while True:: Initiates an infinite loop. The game will continue until a break statement is encountered.
  • user_guess = int(input("Enter your guess: ")): Takes user input, converts it to an integer, and assigns it to user_guess.
  • attempts += 1: Increments the attempts counter.

Part Four: Guess Comparison

  • Compares user_guess with secret_number to determine whether the guess is correct.
  • Prints appropriate messages based on the comparison.
  • If the guess is correct, it prints a congratulatory message with the number of attempts and breaks out of the loop.

Part Five: Execution

  • if __name__ == "__main__":: Checks whether the script is being run as the main program.
  • Calls the guess_the_number() function if the script is the main program

Leave a comment