Python is a popular choice for beginners to learn programming due to its intuitive syntax and readability. One of the best ways to get started with Python is by creating simple and fun games. In this blog post, we’ll explore a basic Python game that can serve as an excellent introduction for beginners.
The game we’ll build is a simple number guessing game. The computer will generate a random number between 1 and 100, and the player will have to guess what it is. Let’s dive into the code:
pythonimport random
def start_game():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
while guess != number_to_guess:
try:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < number_to_guess:
print("Too low, try again.")
elif guess > number_to_guess:
print("Too high, try again.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
print(f"Congratulations! You guessed the number in {attempts} attempts.")
if __name__ == "__main__":
start_game()
Let’s break down the code:
- Imports: We import the
random
module to generate a random number for the game.
- Function Definition: We define a function
start_game()
that encapsulates the game’s logic.
- Initialization: Inside the function, we initialize the
number_to_guess
variable as a random number between 1 and 100. We also initialize guess
to None
and attempts
to 0 to keep track of the player’s guesses and the number of attempts.
- Welcome Message: We print a welcome message and inform the player about the range of numbers.
- Guessing Loop: We use a
while
loop to keep asking the player for guesses until they guess correctly. Inside the loop, we use a try-except
block to handle potential errors.
- Input and Feedback: Inside the loop, we take the player’s input using
input()
and attempt to convert it to an integer using int()
. If the input is not a valid integer, the except
block catches the ValueError
and prompts the player to enter a valid integer. If the input is valid, we update the number of attempts and compare the guess with the number to guess. Based on the comparison, we provide the player with feedback (too low, too high).
- Win Condition: Once the player guesses correctly, the
while
loop terminates, and we print a congratulatory message, informing the player about the number of attempts they took.
- Execution: Finally, we check if the script is being run directly (not imported as a module) and call the
start_game()
function to start the game.
This simple number guessing game serves as an excellent introduction to Python programming for beginners. It covers basic concepts such as variables, functions, loops, conditionals, and error handling. By playing and modifying this game, beginners can gain a solid foundation in Python programming and start building more complex programs.