Both novice coders and experienced developers alike seek to challenge themselves through a diverse array of projects, aiming to enrich their skill sets and broaden their perspectives on multifaceted aspects of programming and innovative problem-solving. Among the endeavors frequently undertaken is the development of a ‘Guess the Number Python’ game—a project that often ranks high on the priority list. This undertaking solely relies on a single Python module to accomplish its objectives.
So, in “Guess the Number Python” we first have to import the random module from Python’s inbuilt libraries.
#Import Random Module
import random
JavaScriptThis module will be used in selecting a number between a defined set or range. We now need to select a range between which the user is to guess a number. To do this, the user inputs a number; a Higher Range and a Lower Range. Define a function for the game.
# Define a function for the game
def guess_the_number():
# Generate a random number between 1 and 100
target_number = random.randint(1, 100)
attempts = 0 # Initialize the number of attempts
JavaScriptAfter getting a Higher Range and a Lower Range within which a random number will be selected, we pick a random number using a function from the random module.
# Display a welcome message
print("Welcome to Guess the Number Python Game!")
print("I'm thinking of a number between 1 and 100. Can you guess it?")
JavaScriptThe user is then assigned a number of chances to guess a number which will be a counter for a loop. We use a while loop since the user can get the right guess at any trial. The whole case will check if the user has guessed the right number and if so, exits the loop. If not the number of chances decreases by one until the user has no more chances and the random number is revealed to him.
To ensure that the program runs continuously and doesn’t close the program window, we add a true statement and print a line to separate the blocks.
# Start a loop for the game
while True:
try:
# Get the player's guess as an integer
guess = int(input("Enter your guess: "))
attempts += 1 # Increment the attempts counter
# Compare the player's guess with the target number
if guess < target_number:
print("Too low! Try again.")
elif guess > target_number:
print("Too high! Try again.")
else:
# Congratulate the player and display the number of attempts
print(f"Congratulations! You've guessed the number {target_number} in {attempts} attempts.")
break # Exit the loop as the game is over
except ValueError:
print("Invalid input. Please enter a valid number.")
JavaScript# Import the random module to generate random numbers
import random
# Define a function for the game
def guess_the_number():
# Generate a random number between 1 and 100
target_number = random.randint(1, 100)
attempts = 0 # Initialize the number of attempts
# Display a welcome message
print("Welcome to Guess the Number Python Game!")
print("I'm thinking of a number between 1 and 100. Can you guess it?")
# Start a loop for the game
while True:
try:
# Get the player's guess as an integer
guess = int(input("Enter your guess: "))
attempts += 1 # Increment the attempts counter
# Compare the player's guess with the target number
if guess < target_number:
print("Too low! Try again.")
elif guess > target_number:
print("Too high! Try again.")
else:
# Congratulate the player and display the number of attempts
print(f"Congratulations! You've guessed the number {target_number} in {attempts} attempts.")
break # Exit the loop as the game is over
except ValueError:
print("Invalid input. Please enter a valid number.")
# Ask if the player wants to play again
play_again = input("Do you want to play again? (yes/no): ")
if play_again.lower() == "yes":
guess_the_number() # Restart the game
else:
print("Thank you for playing!")
# Start the game by calling the function
guess_the_number()
JavaScriptThanks for reading through Our article. Keep updated for new articles.