Building a dice game is one of the best first projects for anyone learning Python. It combines randomness, loops, conditionals, and user input into a single script you can run from your terminal in under 30 lines of code. This tutorial walks through every line, from importing the random module to printing a final winner.
A dice game makes an excellent starter project because it reinforces several core Python skills at once. You will practice importing modules, generating random numbers, writing while loops, reading user input with the input() function, and using if/elif/else branches to control program flow. By the end of this tutorial, you will have a working player-vs-computer dice game with score tracking and a replay option.
What You Need Before You Start
This tutorial assumes you have Python 3 installed on your machine. You do not need any third-party packages. The only module used here, random, ships with every standard Python installation. Any text editor or IDE will work, whether that is VS Code, IDLE, or even a plain terminal with nano.
If you can open a terminal and type python3 --version (or python --version on Windows) and see a version number starting with 3, you are ready to go. Create a new file called dice_game.py and follow along.
Every code block in this tutorial is self-contained. You can copy any block, paste it into a .py file, and run it independently to see what it does before combining everything into the final game.
Understanding the random Module
Python's random module provides functions for generating pseudo-random numbers. The word "pseudo" matters here: the numbers are produced by a deterministic algorithm called the Mersenne Twister, not by a truly random physical process. For games and simulations, this is perfectly fine. For security-critical applications, you would use the secrets module instead.
The function we care about is random.randint(a, b). It returns a random integer N such that a <= N <= b. Both endpoints are included. That makes it a natural fit for simulating a standard six-sided die, where the valid outcomes are 1, 2, 3, 4, 5, and 6.
import random
# Simulate rolling a six-sided die
roll = random.randint(1, 6)
print("You rolled:", roll)
Run this a few times and you will see a different number each time. The import random line loads the module into memory, and random.randint(1, 6) does the work of picking one number from the range 1 through 6.
If you want reproducible results for testing, call random.seed(42) before generating numbers. This forces the same sequence every time. Remove the seed call when you want true randomness again.
Comparing Random Functions
Python's random module offers several functions for generating numbers. Here is how the three you are likely to encounter as a beginner compare to each other.
- Returns
- A random integer between a and b, inclusive on both ends.
- Best for
- Simulating dice rolls, picking a random number in a closed range. This is the function used throughout this tutorial.
- Returns
- A random integer from the range, excluding the stop value. Supports an optional step argument.
- Best for
- Generating random even numbers, random multiples of 5, or any range where you need a step. Internally, randint(a, b) is equivalent to randrange(a, b + 1).
- Returns
- A single random element from a non-empty sequence like a list, tuple, or string.
- Best for
- Picking a random item from a collection, such as selecting a random card from a deck or a random word from a list.
Build the statement that generates a random dice roll between 1 and 6:
Writing the Game Logic Step by Step
Now that you understand how randint() works, it is time to combine it with loops, input, and conditionals to build the full game. The goal: the player and the computer each roll a die every round. Whoever rolls higher earns a point. The first to reach 3 points wins.
The Basic Game Loop
A while loop is ideal here because you do not know in advance how many rounds the game will take. The loop keeps running until one player's score hits the target.
import random
player_score = 0
computer_score = 0
target = 3
while player_score < target and computer_score < target:
input("Press Enter to roll the dice...")
player_roll = random.randint(1, 6)
computer_roll = random.randint(1, 6)
print(f"You rolled: {player_roll}")
print(f"Computer rolled: {computer_roll}")
if player_roll > computer_roll:
player_score += 1
print("You win this round!")
elif computer_roll > player_roll:
computer_score += 1
print("Computer wins this round!")
else:
print("It's a tie! No points awarded.")
print(f"Score — You: {player_score} | Computer: {computer_score}\n")
if player_score == target:
print("Congratulations! You won the game!")
else:
print("Game over. The computer won.")
Walk through what happens here. The two score variables start at zero. The while condition checks that neither player has reached 3 yet. Inside the loop, input() pauses execution until the player presses Enter, giving them a sense of control. Both rolls happen via randint(1, 6), and the if/elif/else chain determines who scores. After the loop exits, a simple check reveals the winner.
Do not use or instead of and in the while condition. Writing while player_score < 3 or computer_score < 3 would keep the game running even after one player has already won, because the other player's score is still below 3.
Adding a Play Again Feature
Wrapping the entire game in an outer loop lets you offer a replay without restarting the script.
import random
def play_game():
player_score = 0
computer_score = 0
target = 3
round_num = 1
print("\n--- Dice Game: First to 3 wins! ---\n")
while player_score < target and computer_score < target:
input(f"Round {round_num} — Press Enter to roll...")
player_roll = random.randint(1, 6)
computer_roll = random.randint(1, 6)
print(f" You rolled: {player_roll}")
print(f" Computer rolled: {computer_roll}")
if player_roll > computer_roll:
player_score += 1
print(" You win this round!")
elif computer_roll > player_roll:
computer_score += 1
print(" Computer wins this round!")
else:
print(" It's a tie! No points awarded.")
print(f" Score — You: {player_score} | Computer: {computer_score}\n")
round_num += 1
if player_score == target:
print("Congratulations! You won the game!")
else:
print("Game over. The computer won.")
# Main loop with replay
while True:
play_game()
again = input("\nPlay again? (y/n): ").strip().lower()
if again != "y":
print("Thanks for playing!")
break
The play_game() function encapsulates all the game logic, making it easy to reset everything by calling it again. The outer while True loop asks for a replay after each game. Calling .strip().lower() on the input handles cases where the player types " Y " or "Yes" with trailing spaces or mixed case.
This dice game loop has one bug that causes it to run forever, even after someone wins. Find the broken line.
or to and on line 4. With or, the loop keeps running as long as either score is below the target, meaning the game continues even after one player has already won. Using and ensures the loop stops the moment either player reaches the target.
How to Build a Dice Game in Python
Follow these four steps to go from an empty file to a working dice game with replay support.
-
Import the random module
At the top of your Python file, write
import random. This gives you access to therandint()function, which generates a random integer between two values you specify, including both endpoints. -
Set up scores and the game loop
Create two variables to hold the scores for the player and computer, both starting at 0. Then create a
whileloop that continues running as long as neither player has reached the winning score of 3. -
Roll dice and compare results
Inside the loop, use
input()to let the player trigger a roll, then callrandom.randint(1, 6)for both the player and the computer. Compare the two values and award a point to whoever rolled higher. Print the results and the updated score each round. -
Announce the winner and add replay
After the
whileloop ends, check which score reached 3 first and print a congratulations or game over message. Wrap everything in an outerwhile Trueloop and useinput()to ask if the player wants to play again.
"Simple is better than complex." — The Zen of Python
Python Learning Summary Points
random.randint(a, b)returns a random integer betweenaandb, inclusive on both ends, making it a direct fit for simulating standard dice.- A
whileloop with compound conditions usingandis the right structure when the game should stop as soon as any one condition becomes false. - The
input()function pauses the program and waits for the user to press Enter, giving the player agency in each round without requiring complex event handling. - Wrapping game logic in a function and calling it from a
while Trueloop is a clean pattern for offering replay without duplicating code. - Chaining
.strip().lower()on user input normalizes whitespace and case, preventing the program from breaking on minor input variations.
This dice game covers the foundational patterns you will reuse in larger projects: importing modules, looping until a condition is met, reading and sanitizing user input, and branching with conditionals. From here, you could extend the game with multiple dice, weighted scoring, or even a graphical interface using a library like tkinter. The core logic stays the same.
Frequently Asked Questions
You need the random module, which is part of Python's standard library. Import it with import random at the top of your script, then use random.randint(1, 6) to simulate a six-sided die roll.
random.randint(a, b) returns a random integer N where a is less than or equal to N, and N is less than or equal to b. Both endpoints are included in the possible results, making it ideal for simulating dice rolls.
Yes. You can call random.randint(1, 6) once for each player per round, compare the results, and award a point to whoever rolled higher. A while loop keeps the game running until a player reaches the target score.
If you called random.seed() with a fixed value, the random number generator will produce the same sequence every time. Remove the seed call or use random.seed() with no arguments to get different results on each run.
Wrap your entire game logic inside a while True loop. At the end of each game, use input() to ask the player if they want to play again. If they type anything other than "y", use break to exit the outer loop.
No. Python's random module uses the Mersenne Twister algorithm, which is deterministic and not suitable for security applications. For cryptographic randomness, use the secrets module instead.
randint(a, b) includes both endpoints, so it can return a or b. randrange(a, b) excludes the stop value, so it will never return b. Internally, randint(a, b) is equivalent to randrange(a, b + 1).
Declare score variables before your game loop starts, such as player_score = 0 and computer_score = 0. Inside the loop, increment the appropriate variable with += 1 each time a player wins a round.