Table of Contents
Learning Python and looking for a fun, hands-on project? Look no further! Building a number guessing game is a fantastic way to solidify your understanding of basic programming concepts like variables, loops, conditional statements, and user input. Plus, it’s a great way to introduce others to the world of coding!
In this blog post, we’ll walk you through creating a simple number guessing game in Python.
The Game
The computer will generate a random number within a specified range (e.g., 1 to 100). The player has to guess the number. The computer will provide feedback, telling the player if their guess is too high or too low. The player continues guessing until they correctly identify the number.
The Code
import random
def number_guessing_game():
print("Welcome to the Number Guessing Game!")
print("I've chosen a secret number between 1 and 100.")
secret_number = random.randint(1, 100)
guesses_taken = 0
while True:
try:
guess = int(input("Take a guess: "))
guesses_taken += 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print(f"Congratulations! You guessed the number in {guesses_taken} tries.")
break
except ValueError:
print("Invalid input. Please enter a number.")
if __name__ == "__main__":
number_guessing_game()
Explanation
- Import
random
: This line imports therandom
module, which allows us to generate random numbers. number_guessing_game()
function: This function contains the core logic of the game.- Welcome message: We print a welcome message to the player.
secret_number
generation:random.randint(1, 100)
generates a random integer between 1 and 100 (inclusive) and stores it in thesecret_number
variable.guesses_taken
variable: This variable keeps track of the number of guesses the player has made.while True
loop: This loop continues indefinitely until the player guesses the correct number.try-except
block: This handles potential errors if the player enters non-numeric input. TheValueError
exception is caught if the user inputs something that can’t be converted to an integer.input()
function: This prompts the player to enter their guess.int()
converts the input to an integer.- Conditional statements (
if
,elif
,else
): These statements compare the player’s guess to thesecret_number
and provide feedback. - Winning condition: If the player’s guess matches the
secret_number
, the loop breaks, and a congratulatory message is printed. if __name__ == "__main__":
block: This ensures that thenumber_guessing_game()
function is called only when the script is executed directly (not when it’s imported as a module).
How to Run the Code
- Save the code as a Python file (e.g.,
guessing_game.py
). - Open a terminal or command prompt.
- Navigate to the directory where you saved the file.
- Run the script using the command:
python guessing_game.py
Enhancements
- Difficulty levels: You could introduce difficulty levels by changing the range of numbers.
- Limited guesses: You could limit the number of guesses the player can take.
- High score: You could store high scores in a file and display them to the player.
- User interface: For a more polished experience, you could create a graphical user interface (GUI) using libraries like Tkinter or PyQt.