Create a Number Guessing Game with Python – A mini project for beginners

When starting to learn programming, completing a mini-project by yourself will help you master the syntax, practice logical thinking, and gain more motivation to keep going. In this article, I will build a very familiar game with you Number Guessing Game.


Game idea

How it work

  • The computer will randomly choose a number between 1 to 10.
  • The player enters their guess.
  • If the guess is wrong, the program will suggest:
    • “Too low” if the guessed number is smaller than the answer.
    • “Too high” if the guessed number is larger than the answer.
  • When guessed correctly, the game will announce: “You guessed it right!!”.

With this project, you will practice:

  • Import and using library random in Python
  • Dùng Using while loops..
  • Applying if/elif/else statements.

Game code

Below is the simplest version of the Number Guessing Game:

import random

# Máy chọn ngẫu nhiên một số trong khoảng 1 đến 10
n = random.randrange(1, 10)

# Người chơi nhập số dự đoán
guess = int(input("Enter any number: "))

# Lặp cho đến khi người chơi đoán đúng
while n != guess:
    if guess < n:
        print("Too low")
    elif guess > n:
        print("Too high!")
    # Cho người chơi nhập lại
    guess = int(input("Enter number again: "))

print("You guessed it right!!")

Example

When running the program, the screen will display as follows:"

Enter any number: 2
Too low
Enter number again: 5
Too low
Enter number again: 8
You guessed it right!!

In the example above:

  • Người chơi đoán 2, chương trình báo “Too low”.
  • Đoán tiếp 5, vẫn thấp hơn đáp án → “Too low”.
  • Đoán 8, matches the random number chosen by the computer → the program prints: “You guessed it right!!”

Expand

This is just a basic version. You can upgrade this game with many more interesting features:

  • Limit the number of guesses (e.g., only 5 guesses allowed).
  • Allow players to choose their own number range (e.g., from 1 → 100).
  • Add a replay mode after guessing correctly or running out of turns.
Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *