Python, known for its simplicity and readability, is an excellent choice for beginners who want to learn how to code. One fun way to start your coding journey is by creating a simple game. In this article, we will walk through the process of creating a basic game in Python using just 20 lines of code. This game will be a simple guessing game where the player tries to guess a number chosen by the computer.
Step 1: Import Necessary Modules
First, we need to import the random
module to generate a random number for the player to guess.
pythonCopy Codeimport random
Step 2: Generate a Random Number
Next, we generate a random number between 1 and 100. This will be the number the player tries to guess.
pythonCopy Codenumber_to_guess = random.randint(1, 100)
Step 3: Ask the Player for Their Guess
We use an infinite loop to keep asking the player for their guess until they guess correctly.
pythonCopy Codewhile True:
player_guess = int(input("Guess a number between 1 and 100: "))
Step 4: Check the Player’s Guess
Inside the loop, we check if the player’s guess is equal to the number generated by the computer. If it is, we congratulate the player and break the loop. If not, we give them a hint.
pythonCopy Code if player_guess == number_to_guess:
print("Congratulations! You guessed the number correctly.")
break
elif player_guess < number_to_guess:
print("Your guess is too low.")
else:
print("Your guess is too high.")
Full Code
Here is the full code for our simple guessing game:
pythonCopy Codeimport random
number_to_guess = random.randint(1, 100)
while True:
player_guess = int(input("Guess a number between 1 and 100: "))
if player_guess == number_to_guess:
print("Congratulations! You guessed the number correctly.")
break
elif player_guess < number_to_guess:
print("Your guess is too low.")
else:
print("Your guess is too high.")
Conclusion
Creating a simple game like this in Python is a great way to learn basic programming concepts such as loops, conditionals, and user input. As you become more comfortable with Python, you can start adding more features to your games, such as scoring or multiple levels. Happy coding!
[tags]
Python, beginner, coding, simple game, guessing game, tutorial