Python, as a versatile programming language, allows us to create engaging programs that can entertain users of all ages. One such program is a simple guessing game, where the user tries to guess a randomly generated number. In this article, we’ll explore the code for a basic guessing game and discuss its components.
The Guessing Game Code
Here’s the code for a simple guessing game in Python:
pythonimport random
# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)
# Initialize variables
guess = None
attempts = 0
print("Welcome to the Guessing Game!")
print("I have a secret number between 1 and 100.")
while guess != secret_number:
try:
guess = int(input("Take a guess: "))
attempts += 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
except ValueError:
print("Invalid input. Please enter a whole number.")
print(f"Congratulations! You guessed the number in {attempts} attempts.")
Code Breakdown
-
Importing the random
Module: We import the random
module to generate a random number for the game.
-
Generating the Secret Number: Using the randint()
function from the random
module, we generate a random number between 1 and 100.
-
Initializing Variables: We initialize the guess
variable to None
to indicate that the user hasn’t made a guess yet. We also initialize the attempts
variable to keep track of the number of guesses made.
-
Game Loop: We use a while
loop to repeatedly prompt the user for a guess until they guess the correct number.
- Inside the loop, we use a
try-except
block to handle potential errors, such as when the user enters a non-integer value.
- If the guess is lower than the secret number, we print a “Too low!” message.
- If the guess is higher than the secret number, we print a “Too high!” message.
- If the guess is correct, we exit the loop and display a congratulatory message along with the number of attempts made.
Conclusion
This simple guessing game demonstrates the power of Python in creating engaging and interactive programs. With just a few lines of code, we can create a game that challenges users to guess a randomly generated number. Whether you’re a beginner or an experienced Python programmer, this game is a great way to practice your skills and have some fun along the way.