Practice: Dice Statistics

Practice: Dice Statistics

This exercise combines random, a loop, and a counter.

Exercise

  1. Define a function named count_sixes with one parameter, rolls — how many times to roll.
  2. It rolls a die rolls times using random.randint(1, 6) and returns how many rolls came up 6.

As in the random lesson, the checks seed the generator, so the rolls must come from the random module.

Run your code to see the output, then press Submit.

Hints

  • One loop with range(rolls), one counter, one if.
  • Roll inside the loop — one randint call per pass.

Tests

import random
import unittest


class TestCountSixes(unittest.TestCase):
    def test_count_is_between_zero_and_rolls(self):
        random.seed(7)
        result = count_sixes(60)
        self.assertGreaterEqual(result, 0)
        self.assertLessEqual(result, 60)

    def test_zero_rolls_gives_zero_sixes(self):
        self.assertEqual(count_sixes(0), 0)

    def test_same_seed_gives_the_same_count(self):
        random.seed(42)
        first = count_sixes(200)
        random.seed(42)
        second = count_sixes(200)
        self.assertEqual(first, second)

    def test_a_long_run_contains_at_least_one_six(self):
        random.seed(1)
        self.assertGreater(count_sixes(1000), 0)
import random


def count_sixes(rolls):
    sixes = 0
    for _ in range(rolls):
        if random.randint(1, 6) == 6:
            sixes += 1
    return sixes


print(count_sixes(100))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.