Number Guessing Game (code) in python

← Back to Projects

About this project: This project is a simple number guessing game and is suitable for beginners who are learning python programming. In this game one has to guess a random number which is selected by the application.

If the number user guess is less than the selected number , it will prompt, The number is less else if the number is larger than the selected one, It will prompt, the number user guess is greater until it found the exact match from the guess with the selected number.

Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps:

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)


import random

print("πŸŽ‰ Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
print("Can you guess what is the number? πŸ€”")

secret_number = random.randint(1, 100)
attempts = 0

while True:
    guess = input("Enter your guess: ")
    
    if not guess.isdigit():
        print("❌ Please enter a valid number.")
        continue

    guess = int(guess)
    attempts += 1

    if guess > secret_number:
        print("It's low! You should try a higher number. πŸ”Ό")
    elif guess > secret_number:
        print("Oh! It's too high! Try a smaller number. πŸ”½")
    else:
        print(f"🎯 Congratulations! You guessed it right in {attempts} tries.")
        break

print("Thanks for playing! 😊")