Random

Random

The random module produces random values.

random.randint(a, b) returns a whole number from a to b, both included:

import random

print(random.randint(1, 6))
print(random.randint(1, 6))

Output (varies per run):

4
1

random.choice(items) picks one element from a list:

print(random.choice(["red", "green", "blue"]))

Output (varies per run):

green

Random output makes programs hard to test and debug, so the module offers a switch: random.seed(n) fixes the starting point, making every following random call reproducible — the same seed gives the same sequence. The checks for this lesson's exercise use a seed, so your function must produce its values with the random module rather than hardcoding them.

Exercise

  1. Define a function named roll_dice with one parameter, count.
  2. It returns a list of count die rolls — each a random whole number from 1 to 6.

roll_dice(5) returns a list like [3, 1, 6, 6, 2].

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

Tests

import random
import unittest


class TestRollDice(unittest.TestCase):
    def test_returns_the_requested_number_of_rolls(self):
        self.assertEqual(len(roll_dice(5)), 5)

    def test_every_roll_is_between_1_and_6(self):
        random.seed(1)
        for roll in roll_dice(100):
            self.assertGreaterEqual(roll, 1)
            self.assertLessEqual(roll, 6)

    def test_same_seed_gives_the_same_rolls(self):
        random.seed(42)
        first = roll_dice(10)
        random.seed(42)
        second = roll_dice(10)
        self.assertEqual(first, second)

    def test_rolls_vary_without_a_fixed_seed(self):
        random.seed(1)
        first = roll_dice(20)
        second = roll_dice(20)
        self.assertNotEqual(first, second)
import random


def roll_dice(count):
    rolls = []
    for _ in range(count):
        rolls.append(random.randint(1, 6))
    return rolls


print(roll_dice(5))
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.