Number Guessing Game

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/gr
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/gw
πŸ’‘*Course Content:*
https://www.vlrt.in/ai
▢️ *Demo Videos:*
https://www.vlrt.in/gv

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09:00 AM IST
πŸ“*Register Now!:*
https://www.vlrt.in/vr
πŸ‘₯ *Join Community:*
https://www.vlrt.in/cw
πŸ’‘ *Course Content:*
https://www.vlrt.in/vc
▢️ *Demo Videos:*
https://www.vlrt.in/Vm

Here is the code for the “Number Guessing Game” mini-project. It combines a while loop, the break statement, and basic if-elif-else conditions.

Python

import random

print("Welcome to The Number Guessing Game!")
print("I have picked a random number between 1 and 50.")

# The computer picks a random number between 1 and 50
secret_number = random.randint(1, 50)

# Keep track of how many guesses the player makes
attempts = 0

# Start an infinite loop that allows continuous guessing
while True:
    try:
        # Ask the player for their guess
        guess = int(input("Enter your guess: "))
        attempts += 1
        
        # Give hints based on the guess
        if guess < secret_number:
            print("Higher! Try again.")
        elif guess > secret_number:
            print("Lower! Try again.")
        else:
            # The guess matches the secret number
            print(f"Congratulations! You guessed the number {secret_number} correctly!")
            print(f"It took you {attempts} attempts.")
            break  # Exit the loop since the game is won
            
    except ValueError:
        # Handles the error if the user types a letter instead of a number
        print("Invalid input. Please enter a whole number.")

How It Works:

  1. import random: This brings in Python’s built-in random module so the computer can use random.randint(1, 50) to generate the secret number.
  2. while True:: This creates an infinite loop. The game will keep asking for guesses over and over again until it is explicitly told to stop.
  3. try...except ValueError: This ensures the program doesn’t crash if the player accidentally types a letter (like “A”) instead of a number.
  4. if/elif/else: This compares the player’s guess to the secret number and provides the “higher” or “lower” feedback.
  5. break: Once the player’s guess equals the secret number, the else block runs, prints the victory message, and hits the break statement to terminate the game loop.

Similar Posts

  • Python Variables: A Complete Guide with Interview Q&A

    Here’s a detailed set of notes on Python variables that you can use to explain the concept to your students. These notes are structured to make it easy for beginners to understand. Python Variables: Notes for Students 1. What is a Variable? 2. Rules for Naming Variables Python has specific rules for naming variables: 3….

  • Create a User-Defined Exception

    A user-defined exception in Python is a custom error class that you create to handle specific error conditions within your code. Instead of relying on built-in exceptions like ValueError, you define your own to make your code more readable and to provide more specific error messages. You create a user-defined exception by defining a new…

  • String Validation Methods

    Complete List of Python String Validation Methods Python provides several built-in string methods to check if a string meets certain criteria. These methods return True or False and are useful for input validation, data cleaning, and text processing. 1. Case Checking Methods Method Description Example isupper() Checks if all characters are uppercase “HELLO”.isupper() β†’ True islower() Checks if all…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

  • Anchors (Position Matchers)

    Anchors (Position Matchers) in Python Regular Expressions – Detailed Explanation Basic Anchors 1. ^ – Start of String/Line Anchor Description: Matches the start of a string, or start of any line when re.MULTILINE flag is used Example 1: Match at start of string python import re text = “Python is great\nPython is powerful” result = re.findall(r’^Python’, text) print(result) #…

  • Python Course content for kids

    Module 1: The Basics (Getting the Computer to Talk) Goal: Understand how to communicate with the computer and store information. Module 2: Making Decisions (Teaching the Computer to Think) Goal: Learn how to use logic to control the flow of a program. Module 3: Loops (Working Smarter, Not Harder) Goal: Understand how to automate repetitive…

Leave a Reply

Your email address will not be published. Required fields are marked *