Number Guessing game in python

Aviral Srivastava Avatar

Are you ready to embark on a thrilling adventure of code and numbers? Look no further, because today we’re diving into the world of Python programming with a fun and interactive guessing game!

Introduction

In this blog post, we’ll guide you through the creation of a simple yet exciting number-guessing game using the Python programming language. Whether you’re a beginner eager to learn or an experienced coder looking for a nostalgic challenge, this journey is for you.

Getting Started

To begin our journey, let’s set up our development environment. All you need is a working Python interpreter installed on your computer. Once you have that ready, open up your favourite text editor or integrated development environment (IDE), and let’s start coding!

The Code

read comments (#comments) to understand working…

import random

# Taking input for lower and upper bounds
lower = int(input("Enter Lower bound, 00 to exit:- "))
upper = int(input("Enter Upper bound, 00 to exit:- "))

# Generating a random number between the lower and upper bounds
x = random.randint(lower, upper)

# Initializing variables for counting guesses and keeping score
count = 0
score = 0

# Main loop for the guessing game
while True:
    guess = int(input("Guess the number,00 to exit:"))  # Taking input from the user for their guess
    
    # Checking if the user wants to exit
    if lower == 00 or upper == 00 or guess == 00:
        print("Your score is", score)  # Displaying the final score
        break  # Exiting the loop if the user wants to exit
    
    # If the guess is correct
    elif guess == x:
        print("Yahoo you did it!!!")
        x = random.randint(lower, upper)  # Generating a new random number for the next round
        
        # Checking if the user took more than 10 guesses
        if count > 10:
            print("But actually you lost because you made", count, "number of guesses, and your score will not be counted")
        else:
            print("And you win this round with", count, "number of guesses, and you get +1")
            score += 1  # Incrementing the score
            print("And your overall score is", score)  # Displaying the updated score
    
    # If the guess is smaller than the actual number
    elif guess < x:
        print("Your guess is smaller than the actual number")
        count += 1  # Incrementing the guess count
    
    # If the guess is bigger than the actual number
    elif guess > x:
        print("Your guess is bigger than the actual number")
        count += 1  # Incrementing the guess count

Conclusion

Congratulations! You’ve just completed your first Python guessing game. With just a few lines of code, you’ve created an entertaining experience that challenges users to test their intuition and luck.

Keep exploring & keep coding!

Contact me : sriaviralnarain@gmail.com


Leave a comment

Design a site like this with WordPress.com
Get started