[Copy-Paste Ready!] Beginner's Guide to Creating a Number Guessing Game in Python: A Novice's Journey with AI
Hello! Welcome to the world of programming.
Just a few months ago, I was exactly like youβI had absolutely zero programming knowledge. I didn't know where to start and would get frustrated every time an error popped up. But with the help of AI, I went through a lot of trial and error, and now I've managed to single-handedly launch two websites (buyonjapan.com, copicode.com).
On this site, I explain the things I "really wanted to know," the "stumbling blocks I actually faced," and "how I solved them," all from the perspective of a fellow beginner, using as little jargon as possible.
This time, we'll create a "Number Guessing Game" in Python, a very popular first step in learning to program. The goal of this article is simple: "To provide code that works perfectly just by copying and pasting, so you can experience the joy of making something that 'just works.'"
Let's experience the fun of programming together!
First, Try the Final Product! The Complete, Ready-to-Run Code
Seeing is believing. First, let me show you the complete code for the number guessing game we'll be building together. Copy all the code below and run it in your environment (like VSCode or Google Colaboratory). The best way to understand the game is to play it first!
import random
def number_guessing_game():
while True:
print("\n--- Number Guessing Game ---")
print("Choose a difficulty level:")
print("1: Easy (1-10)")
print("2: Normal (1-100)")
print("3: Hard (1-1000)")
level = input("Enter difficulty (1, 2, 3): ")
if level == '1':
min_num, max_num = 1, 10
elif level == '2':
min_num, max_num = 1, 100
elif level == '3':
min_num, max_num = 1, 1000
else:
print("Invalid choice. Please enter '1', '2', or '3'.")
continue
answer = random.randint(min_num, max_num)
count = 0
print(f"\nGuess the number between {min_num} and {max_num}!")
while True:
try:
guess_str = input(f"Your guess (Attempts: Unlimited): ")
guess = int(guess_str)
count += 1
if guess < min_num or guess > max_num:
print(f"Out of range! Please enter a number between {min_num} and {max_num}.")
elif guess < answer:
print(f"Too bad! The number is larger. (Attempts: {count})")
elif guess > answer:
print(f"Too bad! The number is smaller. (Attempts: {count})")
else:
print(f"\nπππ Correct! Congratulations! πππ")
print(f"The correct number was {answer}.")
print(f"It took you {count} attempts to guess it.")
break
except ValueError:
print("Error: Please enter a number. Letters and symbols are not allowed.")
while True:
replay = input("\nPlay again? (yes / no): ").lower()
if replay in ["yes", "no"]:
break
else:
print("Invalid input. Please enter 'yes' or 'no'.")
if replay == "no":
print("Thanks for playing! See you next time!")
break
# Start the game
number_guessing_game()
How was it? It was a simple game where you guess a number thought up by the computer. From the next section, we'll break this code down into individual parts and build it from scratch.
Step 1: Building the Game's Skeleton (Minimal Version)
No matter how complex a program seems, it's just a combination of simple commands. First, let's build the essential "skeleton" of this game.
Required Tool: What is the `random` module?
To create a number guessing game, you first need the computer to pick a random number. For that, we use Python's standard feature, the "`random` module."
The word "module" might sound difficult, but just think of it as a "toolbox full of handy functions." The `random` module contains functions for creating random numbers, shuffling list elements, and more.
This time, we'll use a function called `random.randint(a, b)`. This command creates a single random integer that is between `a` and `b`, inclusive. For example, if you write `random.randint(1, 100)`, a random number between 1 and 100 will be chosen.
For more details, you can check the official Python documentation, but for now, it's enough to just know that such a function exists.
The First Code: It Works With Just This!
Now, let's create the heart of the game. We need the following four steps:
- Enable the `random` module (`import`)
- Generate a random answer number between 1 and 100
- Ask the player for their guess (`input`)
- Compare the answer and the guess, then display the result (`if/else`)
When converted to code, it looks like this:
# 1. Import the random module
import random
# 2. Generate a random integer from 1 to 100 and store it in the 'answer' variable
answer = random.randint(1, 100)
print("Guess the number between 1 and 100!")
# 3. Get input from the player
guess_str = input("Your guess: ")
# Convert the string from input() to a number (integer) for calculation
guess = int(guess_str)
# 4. Compare the guess and the answer and display the result
if guess == answer:
print("π Correct! Congratulations!")
else:
print(f"Too bad! The correct answer was {answer}.")
When you run this code, you can make a guess just once. It correctly determines if you're right or wrong. This is the starting point for our game.
Key Point: The value received from `input()` is always treated as a "string," even if you type a number. Therefore, before you can compare or calculate it as a number, you need to convert it to an "integer" using `int()`. This is called "type casting."
Step 2: Making the Game Repeatable (The `while` Loop)
With the current code, the game ends after just one guess. That's not much of a game, is it? Let's improve it so you can keep guessing until you get it right.
Why Do We Need a Loop?
When you want to repeat the same process multiple times, you use a construct in programming called a "loop." Python has `for` loops and `while` loops, but this time we'll use a `while` loop, which is suitable for "repeating until a certain condition is met."
Improving with a `while` Loop!
The condition "until you get it right" can be rephrased as "keep repeating as long as it's not correct." Using a `while` loop for this makes it feel more like a game.
We'll use the `while True:` syntax. This means "repeat forever," but don't worry. You can exit the loop at any time using a command called `break`.
import random
answer = random.randint(1, 100)
print("Guess the number between 1 and 100!")
# Start an infinite loop
while True:
guess_str = input("Your guess: ")
guess = int(guess_str)
if guess == answer:
print("π Correct! Congratulations!")
break # Exit the loop if correct
else:
print("Too bad! Try again.")
How's that? When you run it, you can now guess as many times as you need until you get it right. Without `break`, the program would never end, even if you guessed correctly. Remember to use `while True:` and `break` as a pair.
Step 3: Making the Game Friendlier (The Hints Feature)
Right now, all it says is "Too bad!", giving you no clue what to guess next. Let's add hints to make the game more enjoyable for the player.
Hints for "Higher" or "Lower"
If the guess is wrong, telling the player whether their number is "higher" or "lower" than the answer will make the game much more interesting. This can be easily implemented by adding `elif` (short for else if) to the `if` statement.
Let's Count the Attempts
Furthermore, keeping a record of how many attempts it took to guess correctly and displaying it at the end creates a sense of accomplishment. To do this, we'll set up a counter variable like `count = 0` before the loop starts, and increment it by one with `count += 1` each time a guess is made.
import random
answer = random.randint(1, 100)
count = 0 # Initialize a variable to count attempts
print("Guess the number between 1 and 100!")
while True:
guess_str = input("Your guess: ")
guess = int(guess_str)
count += 1 # Increment the counter with each guess
if guess < answer:
print(f"Too bad! The number is larger. (Attempts: {count})")
elif guess > answer:
print(f"Too bad! The number is smaller. (Attempts: {count})")
else: # if guess == answer
print(f"\nπ Correct! Congratulations!")
print(f"The correct number was {answer}.")
print(f"You guessed it in {count} attempts!")
break
With hints and the attempt count displayed, it's starting to feel a lot more like a real game! Using Python's `f-string` (prefixing a string with `f`) is convenient because it lets you easily embed variable values within the string, like `{variable_name}`.
Step 4: Towards an Error-Proof Program (The Most Important & Differentiating Point)
Now, this is the most important part of this article. Our current code has a hidden "weakness." It's that when the player enters something other than a number, the program crashes.
The `ValueError` Trap That Every Beginner Falls Into
Try running the previous code and, when it's time to guess a number, enter text like "abc" or "hello."
`ValueError: invalid literal for int() with base 10: 'abc'`
You should have seen a red error message like this, and the program stopped. This happens because the `int()` function is for "converting a string to an integer," but it was given characters it couldn't convert (like 'abc').
This was a wall I hit many times as a beginner. A program that "works fine on my PC, but crashes immediately when someone else uses it..." is, unfortunately, not what you'd call a "good program." Let's aim for a "robust" program that doesn't easily crash, even if the user makes a mistake.
Catching Errors with `try-except`!
The magic syntax that solves this `ValueError` is `try-except`.
- `try:` block: You put the code that might cause an error inside this block. Think of it as, "Just try this out!"
- `except ErrorType:` block: If the specified type of error occurs inside the `try` block, this block of code is executed. Think of it as, "If an error happens, do this instead."
By using this syntax to wrap the `int()` conversion process in a `try` block and writing the handling for a `ValueError` in an `except` block, we can prevent the program from crashing due to an error.
import random
answer = random.randint(1, 100)
count = 0
print("Guess the number between 1 and 100!")
while True:
guess_str = input("Your guess: ")
try:
# Code that might cause an error
guess = int(guess_str)
count += 1
if guess < answer:
print(f"Too bad! The number is larger. (Attempts: {count})")
elif guess > answer:
print(f"Too bad! The number is smaller. (Attempts: {count})")
else:
print(f"\nπ Correct! Congratulations!")
print(f"The correct number was {answer}.")
print(f"You guessed it in {count} attempts!")
break
except ValueError:
# Code to run if a ValueError occurs
print("Error: Please enter a number. Letters and symbols are not allowed.")
Run this code and try entering "abc" again. This time, instead of crashing with an error, it should display the message "Error: Please enter a number." and prompt you for input again.
Mastering `try-except` is a huge step in moving beyond the beginner stage!
[Column] How to Ask an AI for Help with Errors
When I was learning to program, AI was my biggest helper. When I got an error like `ValueError`, I would copy the error message verbatim and ask an AI (in my case, Gemini or ChatGPT) like this:
"I'm practicing programming with Python. My program stopped with the following error message. What is the cause of this error? Also, how can I modify the code so the program doesn't stop even if this error occurs? Please explain it in a way a beginner can understand."
`ValueError: invalid literal for int() with base 10: 'abc'`
Almost without fail, the AI would suggest a solution using `try-except`. Don't be afraid of error messages; using them as "questions" for an AI is the best trick to accelerate your self-learning.
Step 5: Making It More Fun! (Advanced Features)
Now that we have the basic functionality and error handling implemented, let's add a few more features to create a more polished game. This part explains the content included in the complete code from the beginning of the article.
Let's Add Difficulty Levels
Guessing from 1 to 100 every time might get boring. Allowing the player to choose a range at the start of the game, like "Easy (1-10)," "Normal (1-100)," or "Hard (1-1000)," will make them want to play again and again.
This can be implemented by adding a loop to select the difficulty before the main game loop. Depending on the player's input, you just need to change the minimum (`min_num`) and maximum (`max_num`) values passed to `random.randint()`.
Let's Make It Replayable
It's a bit of a hassle to have to re-run the program every time a game ends. After a correct guess, let's ask, "Play again? (yes / no)," and if they say "yes," restart the whole game from the beginning, and if "no," end it.
The easiest way to achieve this is to wrap the entire game logic we've built so far in an even larger `while` loop. Then, after the game ends, confirm their intention to replay, and if the input is "no," `break` the large loop to completely terminate the program.
The "complete code" introduced at the beginning of this article is what you get when you incorporate all of these features. Please take another look at the code and see if you can identify which part corresponds to which feature.
Conclusion: Experience the Joy of Making Something That Works!
Great job! This time, you've experienced the process of building a simple number guessing game from scratch using Python.
Through this article, you've been introduced to the following important basic elements of Python:
- `import`: Loading modules
- `random.randint()`: Generating random integers
- `input()`: Receiving keyboard input from the user
- `int()`: Type casting from string to integer
- `print()` (f-string): Displaying results and messages on the screen
- `if/elif/else`: Branching processes based on conditions
- `while` loop (`break`): Repeating and exiting a process
- `try-except`: Error handling
When it comes to learning programming, trying to build something that actually "works" is the best shortcut to improvement, much better than just memorizing grammar. Small successes become great motivation for your next learning step.
It would be interesting to try modifying the code we made, for example, by "adding a limit to the number of attempts" or "making the hints more detailed," to create your own original game. Please use this article as the first step in your programming journey.
To the Next Step
Once you get used to basic programming, why not try image processing next? Using Python's library "Pillow," you can easily create useful tools, like one that resizes many images in an instant.
β‘οΈ Next Article: Let's Build a Bulk Image Resizing Tool with Python (Pillow)
[Summary] Regarding the Complete, Ready-to-Run HTML Example
This section is an HTML sample that you can copy and paste when publishing content like this blog post on your own website.
The code below contains all the content of this article (headings, text, code blocks, etc.). However, the Python code itself is intended to be run in the reader's Python execution environment on their PC (such as a terminal or command prompt).
Note: The HTML code within the code block below has its special characters escaped (e.g., `<` is converted to `<`) to ensure it displays correctly on a web page.
<article>
<h1 style="color: #669df6;">[Copy-Paste Ready!] Beginner's Guide to Creating a Number Guessing Game in Python: A Novice's Journey with AI</h1>
<p>
Hello! Welcome to the world of programming.
</p>
<p>
Just a few months ago, I was exactly like youβI had absolutely zero programming knowledge. I didn't know where to start and would get frustrated every time an error popped up. But with the help of AI, I went through a lot of trial and error, and now I've managed to single-handedly launch two websites (<a href="https://buyonjapan.com" target="_blank" rel="noopener noreferrer" style="color: #8ab4f8;">buyonjapan.com</a>, <a href="https://copicode.com" target="_blank" rel="noopener noreferrer" style="color: #8ab4f8;">copicode.com</a>).
</p>
<p>
On this site, I explain the things I "really wanted to know," the "stumbling blocks I actually faced," and "how I solved them," all from the perspective of a fellow beginner, using as little jargon as possible.
</p>
<p>
This time, we'll create a "<strong>Number Guessing Game</strong>" in Python, a very popular first step in learning to program. The goal of this article is simple: "<strong>To provide code that works perfectly just by copying and pasting, so you can experience the joy of making something that 'just works.'</strong>"
</p>
<p>
Let's experience the fun of programming together!
</p>
<hr style="margin: 4rem 0;">
<h2 style="color: #669df6;">First, Try the Final Product! The Complete, Ready-to-Run Code</h2>
<p>
Seeing is believing. First, let me show you the complete code for the number guessing game we'll be building together. Copy all the code below and run it in your environment (like VSCode or Google Colaboratory). The best way to understand the game is to play it first!
</p>
<div class="code-wrapper">
<button class="copy-btn" data-target="code-block-1">π Copy</button>
<pre><code id="code-block-1">
import random
def number_guessing_game():
while True:
print("\n--- Number Guessing Game ---")
print("Choose a difficulty level:")
print("1: Easy (1-10)")
print("2: Normal (1-100)")
print("3: Hard (1-1000)")
level = input("Enter difficulty (1, 2, 3): ")
if level == '1':
min_num, max_num = 1, 10
elif level == '2':
min_num, max_num = 1, 100
elif level == '3':
min_num, max_num = 1, 1000
else:
print("Invalid choice. Please enter '1', '2', or '3'.")
continue
answer = random.randint(min_num, max_num)
count = 0
print(f"\nGuess the number between {min_num} and {max_num}!")
while True:
try:
guess_str = input(f"Your guess (Attempts: Unlimited): ")
guess = int(guess_str)
count += 1
if guess < min_num or guess > max_num:
print(f"Out of range! Please enter a number between {min_num} and {max_num}.")
elif guess < answer:
print(f"Too bad! The number is larger. (Attempts: {count})")
elif guess > answer:
print(f"Too bad! The number is smaller. (Attempts: {count})")
else:
print(f"\nπππ Correct! Congratulations! πππ")
print(f"The correct number was {answer}.")
print(f"It took you {count} attempts to guess it.")
break
except ValueError:
print("Error: Please enter a number. Letters and symbols are not allowed.")
while True:
replay = input("\nPlay again? (yes / no): ").lower()
if replay in ["yes", "no"]:
break
else:
print("Invalid input. Please enter 'yes' or 'no'.")
if replay == "no":
print("Thanks for playing! See you next time!")
break
# Start the game
number_guessing_game()
</code></pre>
</div>
<p>
How was it? It was a simple game where you guess a number thought up by the computer. From the next section, we'll break this code down into individual parts and build it from scratch.
</p>
<!-- Each section continues similarly -->
</article>