21 Number game in Python
- Nanditha Mahesh
- Jun 11
- 3 min read
Let's create the "21 Number Game" in Python. This is a common game where two players take turns adding 1, 2, or 3 to a running total, with the goal of being the one to reach 21.
We'll make a version where the user plays against the computer. The computer will use a simple strategy to make it a bit challenging.
The "21 Number Game" Rules:
The game starts with a total of 0.
Players take turns.
On each turn, a player can add 1, 2, or 3 to the current total.
The player who makes the total exactly 21 wins.
Python Implementation:
How to Play and Understand:
Explanation of Key Parts:
import random, os, time:
random: For deciding who goes first and for the computer's random moves.
os: Used for os.system() to clear the terminal, making the game interface cleaner per turn.
time: Used for time.sleep() to pause the game briefly, making it more readable as the computer makes its move.
clear_screen():
A helper function to clear the terminal screen, providing a fresh display for each turn.
get_player_move(current_total):
This function handles player input.
It uses a while True loop and a try-except block to ensure the player enters a valid integer (1, 2, or 3).
It prompts the player with the current_total.
get_computer_move(current_total):
This is where the computer's "AI" lies. It's a simple, but effective, strategy.Python Course Training in Bangalore
Winning Strategy (winning_positions): The computer tries to reach numbers like 4, 8, 12, 16, 20. If the total is at one of these "winning positions" (e.g., 17), the computer can add 3 to make it 20, setting itself up for the final move.
The logic iterates through winning_positions and then [1, 2, 3] to see if any move combination leads to one of these strategic numbers.
Fallback (Random but Safe): If no strategic move is immediately available, the computer adds 1, 2, or 3 randomly, but it prioritizes adding 1 to keep the total low if possible, to give itself more flexibility. It also checks current_total + move_val <= 21 to ensure it doesn't go over prematurely.
play_21_number_game() (Main Game Loop):
Initial Setup:
Prints rules and welcome messages.
current_total = 0: Starts the game.
turn = random.choice(["player", "computer"]): Randomly decides who starts first.
while True:: The main game loop continues until a win or lose condition is met.
Display Current Total: Shows the current_total at the beginning of each
Player's Turn: Calls get_player_move(), updates current_total, and checks if the player won or went over.
Computer's Turn: Calls get_computer_move(), updates current_total, and checks if the computer won or went over.
Switch Turns: After each turn, the turn variable is toggled between "player" and "computer".
input(): Waits for the user to press Enter before proceeding to the next turn. This helps control the flow and ensures the player has time to read the screen.
Game End & Play Again:
Once a player wins or loses, the loop breaks.
The game asks if the player wants to play again. If 'yes', it calls play_21_number_game() again, effectively restarting the game.
This game is a good exercise in turn-based logic, strategic thinking (for the computer's simple AI), and robust input handling.
Conclusion
In 2025,Python will be more important than ever for advancing careers across many different industries. As we've seen, there are several exciting career paths you can take with Python , each providing unique ways to work with data and drive impactful decisions., At Nearlearn is the Top Python Training in Bangalore we understand the power of data and are dedicated to providing top-notch training solutions that empower professionals to harness this power effectively. One of the most transformative tools we train individuals on is Python.
Comments