Guess the Number Game in Python

0
Guess the Number Game in Python

Python Number Guessing Game

This Python script implements a simple number guessing game. The computer randomly selects a number between 1 and 100, and the user tries to guess the number. The script provides feedback on whether the guess is too high or too low and tracks the number of attempts.

Code Explanation

The script starts by importing the random module, which is used to generate a random number. The guess_number function is defined to handle the main logic of the game:

  • number = random.randint(1, 100): This line generates a random number between 1 and 100.
  • attempts = 0: Initializes a counter for the number of attempts.
  • The while True loop continuously asks the user to input a guess until the correct number is guessed:
    • guess = int(input("Your guess: ")): Reads and converts the user input to an integer.
    • if guess < number: Checks if the guess is too low and prompts the user accordingly.
    • elif guess > number: Checks if the guess is too high and prompts the user accordingly.
    • else: When the guess is correct, it congratulates the user and exits the loop.
    • except ValueError: Handles the case where the input is not a valid number.
  • The if __name__ == "__main__": block ensures that the guess_number function runs when the script is executed directly.

Python Code


import random

def guess_number():
    number = random.randint(1, 100)
    attempts = 0
    print("Guess the number between 1 and 100.")

    while True:
        try:
            guess = int(input("Your guess: "))
            attempts += 1
            if guess < number:
                print("Too low!")
            elif guess > number:
                print("Too high!")
            else:
                print(f"Congratulations! You guessed the number in {attempts} attempts.")
                break
        except ValueError:
            print("Please enter a valid number.")

if __name__ == "__main__":
    guess_number()
        

Watch the Tutorial

Enhance your Python skills by watching our detailed video tutorial. Learn step-by-step how to build this guessing game and more. Click the video below to start learning!

Feel free to copy the code and try it yourself. If you have any questions or need further assistance, leave a comment below!

Post a Comment

0Comments
Post a Comment (0)