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

  • Nested for loops, break, continue, and pass in for loops

    break, continue, and pass in for loops with simple examples. These statements allow you to control the flow of execution within a loop. 1. break Statement The break statement is used to terminate the loop entirely. When break is encountered, the loop immediately stops, and execution continues with the statement immediately following the loop. Example:…

  • Function Returns Multiple Values in Python

    Function Returns Multiple Values in Python In Python, functions can return multiple values by separating them with commas. These values are returned as a tuple, but they can be unpacked into individual variables. Basic Syntax python def function_name(): return value1, value2, value3 # Calling and unpacking var1, var2, var3 = function_name() Simple Examples Example 1:…

  • Β index(),Β count(),Β reverse(),Β sort()

    Python List Methods: index(), count(), reverse(), sort() Let’s explore these essential list methods with multiple examples for each. 1. index() Method Returns the index of the first occurrence of a value. Examples: python # Example 1: Basic usage fruits = [‘apple’, ‘banana’, ‘cherry’, ‘banana’] print(fruits.index(‘banana’)) # Output: 1 # Example 2: With start parameter print(fruits.index(‘banana’, 2)) # Output: 3 (starts searching…

  • re.subn()

    Python re.subn() Method Explained The re.subn() method is similar to re.sub() but with one key difference: it returns a tuple containing both the modified string and the number of substitutions made. This is useful when you need to know how many replacements occurred. Syntax python re.subn(pattern, repl, string, count=0, flags=0) Returns: (modified_string, number_of_substitutions) Example 1: Basic Usage with Count Tracking python import re…

  • Date/Time Objects

    Creating and Manipulating Date/Time Objects in Python 1. Creating Date and Time Objects Creating Date Objects python from datetime import date, time, datetime # Create date objects date1 = date(2023, 12, 25) # Christmas 2023 date2 = date(2024, 1, 1) # New Year 2024 date3 = date(2023, 6, 15) # Random date print(“Date Objects:”) print(f”Christmas:…

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

Leave a Reply

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