Using Python programming language to build Number guessing game - Hive programers.

avatar
(Edited)

Hello to my favourite science community online, SteamSocial.

Today we are going to build a number guessing game using Python programming language.

Image from www.studytonight.com/python-projects/number-guessing-game-in-python

Let get started on using Python to build guessing game.
First you neeed to install Python to your computer, however go to Python.org add download it your PC whether Python for Windows or mac.
Now, when you're creating a new project from scratch, it can seen a little bit intimidating starting at a blank screen.
Also install Python IDE or you can also use visual studio code to achieve this guess game.
I will be using Visual studio code for this guessing game using Python programming language

Hint 1: Import the random module

Image taken from dev.to

Let's start by importing the built-in random module or even better yet from the random module, Import the randint function.
Now inside our code, we can simply just use randint
The random module has functions we can use to generate a random secret number within the specified range:

Remember that the random module also gives pseudo-random numbers—and not truly random numbers.

Hint 2 - Set up the range and the maximum number of attempts for the user playing the amazing guessing game.

Hence, we also need to decide on the range for the secret number and the maximum number of attempts allowed for the player. let's set the lower bound and upper bound to 1 and 50, respectively. The next easier thing in this is to figure out a way of letting the user guess a number, and Also, set the maximum attempts allowed max_attempts to 10.

Let use the code below on the step 2

lower_bound = 1
upper_bound = 50
max_attempts = 10

Hint 3 - Generate a random number to the user.

Remember that, we need to generate a random number within the specified range using the random.randint() function. This allow the user to generate a random number
This is the also secret number that the user needs to guess in the game.

Here is the code for the step 3

secret_number = random.randint(lower_bound, upper_bound)

Hint 4 - Read in the user's input

let's now create a function called get_guess(). Hence, the user can enter an invalid input: a number outside the range.

Here is the code for this step

def get_guess():
while True:
try:
guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: "))
if lower_bound <= guess <= upper_bound:
return guess
else:
print("Invalid input. Please enter a number within the specified range.")
except ValueError:
print("Invalid input. Please enter a valid number.")

However, we use a while loop to prompt the user for a valid input until they enter an integer between lower_bound and upper_bound in this Python guessing game.

Step 5: Validate the user's guess
let's check out the code on how to validate the user's guess.

def get_guess():
while True:
try:
guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: "))
if lower_bound <= guess <= upper_bound:
return guess
else:
print("Invalid input. Please enter a number within the specified range.")
except ValueError:
print("Invalid input. Please enter a valid number.")

Remember to check your indentation on your visual studio code so as to avoid errors on the output when you hint the play button on the left side corner of your screen.

Hint 6 - Track the number of attempts and detect end of game conditions.
Here is where the play_game() function also needed.

This is where we write a code to track the number of attempts and detect end of game conditions

Here is the code to achieve this step

def play_game():
attempts = 0
won = False

while attempts < max_attempts:
    attempts += 1
    guess = get_guess()
    result = check_guess(guess, secret_number)

    if result == "Correct":
        print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
        won = True
        break
    else:
        print(f"{result}. Try again!")

if not won:
    print(f"Sorry, you ran out of attempts! The secret number is {secret_number}.")

Reemember that you can now call the play_game() function every time the Python.

Now are now in the final stage of this guessing game using Python programming language.

Let us put the code together to achieve this guessing game.

import random

define range and max_attempts

lower_bound = 1
upper_bound = 50
max_attempts = 10

generate the secret number

secret_number = random.randint(lower_bound, upper_bound)

Get the user's guess

def get_guess():
while True:
try:
guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: "))
if lower_bound <= guess <= upper_bound:
return guess
else:
print("Invalid input. Please enter a number within the specified range.")
except ValueError:
print("Invalid input. Please enter a valid number.")

Validate guess

def check_guess(guess, secret_number):
if guess == secret_number:
return "Correct"
elif guess < secret_number:
return "Too low"
else:
return "Too high"

track the number of attempts, detect if the game is over

def play_game():
attempts = 0
won = False
while attempts < max_attempts:
attempts += 1
guess = get_guess()
result = check_guess(guess, secret_number)

    if result == "Correct":
        print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
        won = True
        break
    else:
        print(f"{result}. Try again!")

if not won:
print(f"Sorry, you ran out of attempts! The secret number is {secret_number}.")

if name == "main":
print("Welcome to the Number Guessing Game!")
play_game()

Now that we've done all of this hard work, let's run our code and let try it out.

Welcome to the Number Guessing Game!
Guess a number between 1 and 50: 30
Too low. Try again!
Guess a number between 1 and 50: 200
Too high. Try again!
Guess a number between 1 and 50: 20
Too low. Try again!
Guess a number between 1 and 50: 10
Too low. Try again!
Guess a number between 1 and 50: 25
Too low. Try again!
Guess a number between 1 and 50: 35
Congratulations! You guessed the secret number 35 in 6 attempts.

Thank you all for Following this tutorial on how to use Python to build guessing game.



0
0
0.000
1 comments