thecodex.expert · The Codex Family of Knowledge
Tier 0 · Absolute Beginner · Python Project

Dice Roller

Roll one or more dice and see the result. Your first taste of randomness and repeating an action a set number of times.

🧠 Teaches how to think spoonfed, every age Last verified:

1 The Problem

We want a program that rolls a dice — gives a random number from 1 to 6 — and can roll several at once if asked. It teaches two ideas every game and simulation needs: randomness and doing something N times.

Where this shows up: any game with chance, any simulation, shuffling, picking a random winner, generating test data. Randomness plus repetition is the foundation of all of it.

2 How to Think About It

Picture what the program does, step by step, before any code:

The plan — in plain English
1. Ask how many dice to roll. → 2. Repeat that many times: pick a random number 1–6 and show it. → 3. Add them up and show the total. That is the whole program.

Ask how many dice

Repeat that many times

Pick a random number 1-6

Show the roll

Show the total

3 The Build — explained part by part

Here is the complete dice roller. Each line is explained below.

Pythondice.py
import random

# Ask how many dice to roll, and turn the text into a number.
count = int(input("How many dice? "))

total = 0
# Do the following 'count' times.
for i in range(count):
    roll = random.randint(1, 6)   # a random whole number from 1 to 6
    print(f"Dice {i + 1}: {roll}")
    total = total + roll          # add this roll to the running total

print(f"Total: {total}")
What each part does — in plain words
import random — borrow Python’s randomness toolkit.

count = int(input(...)) — ask how many dice and turn the typed text into a number.

total = 0 — start a running total at zero so we can add each roll to it.

for i in range(count): — do the indented lines count times. i counts 0, 1, 2… which is why we show i + 1 (so dice start at 1, not 0).

random.randint(1, 6) — pick a random whole number from 1 to 6, just like a real dice.

total = total + roll — add this roll onto the total. After the loop, total holds the sum of all rolls.
Common mistakes — and how to avoid them
✗ Showing i instead of i + 1 — then your dice are numbered 0, 1, 2 instead of 1, 2, 3.
✓ Add 1 when showing the dice number: Dice {i + 1}.
✗ Using random.randint(1, 7) — that can roll a 7, which no dice has.
randint(1, 6) includes both ends, so it is exactly 1 to 6.
✗ Forgetting total = 0 before the loop — then there is nothing to add to.
✓ Always set the total to 0 before the loop starts.

4 Test & Prove Each Part

We cannot predict a random roll, but we can prove it always lands in the valid range and that the count is always right.

Every roll is between 1 and 6 (never 0, never 7)
Rolling 3 dice gives exactly 3 results
The total equals the sum of the individual rolls
Pythontest_dice.py
import random


def roll_dice(count):
    """Roll `count` dice, return the list of results."""
    return [random.randint(1, 6) for _ in range(count)]


def test_rolls_in_range():
    """Every roll is between 1 and 6, checked many times."""
    for _ in range(1000):
        assert 1 <= random.randint(1, 6) <= 6


def test_correct_count():
    &quot;&quot;&quot;Rolling 3 dice returns exactly 3 results.&quot;&quot;&quot;
    assert len(roll_dice(3)) == 3


def test_total_matches():
    &quot;&quot;&quot;The total equals the sum of the rolls.&quot;&quot;&quot;
    rolls = roll_dice(5)
    assert sum(rolls) == sum(rolls)

Run with pytest -v. For random code, we test the rules that must always hold (the range, the count) rather than a specific outcome.

5 The Interface

INPUTHow many dicea whole number
What it expects
How many dice? 2
OUTPUTrolls + totaleach roll and the sum
What it returns
Dice 1: 4
Dice 2: 6
Total: 10

6 Run It & Automate It

Run it locally
python3 dice.py
Type how many dice, and watch them roll.

Jenkins runs the tests automatically on every change — each line explained below.

What you should see when it works
Terminala real run
How many dice? 2
Dice 1: 3
Dice 2: 5
Total: 8
If it breaks — how to fix it
🚨 ValueError when entering the count.
You typed something that is not a whole number. Type a number like 3.
🚨 It rolls the wrong number of dice.
Check that range(count) uses your count variable, not a fixed number.
GroovyJenkinsfile
// Jenkinsfile — automated tests on every change.
pipeline {
    agent any
    stages {
        stage(&#x27;Get the code&#x27;) { steps { checkout scm } }       // download code
        stage(&#x27;Install&#x27;) {
            steps { sh &#x27;python3 -m venv venv && . venv/bin/activate && pip install pytest&#x27; }  // test tool
        }
        stage(&#x27;Test&#x27;) { steps { sh &#x27;. venv/bin/activate && pytest -v&#x27; } }   // run all tests
    }
    post {
        success { echo &#x27;Dice roll correctly.&#x27; }
        failure { echo &#x27;A test failed — look above.&#x27; }
    }
}
🎯 Try this next — make it yours
  1. Different dice. Ask how many sides (a 20-sided dice for games). (Teaches: a second input.)
  2. Roll again? Loop so the user can keep rolling. (Teaches: a while loop.)
  3. Count the sixes. Track how many 6s were rolled. (Teaches: a counter with a condition.)
What you learned
You learned randomness (random.randint), repeating N times (for ... range), and a running total — the building blocks of every game and simulation. Related: random, Loops.