Editor

Roll Any Die

Beginner · Write the code · from Random Values and Simulations: RANDOM(a, b) in Python

From the lesson: Random Values and Simulations: RANDOM(a, b) in Python

A random value is a number a program cannot predict ahead of time, and simulations use random values to copy the uncertainty of the real world, from a coin toss to the way a rumor travels through a school. Games use them to shuffle cards, and weather apps use them to try out thousands of possible tomorrows.

Read the lesson

Write roll(sides) that returns a random whole number from 1 to sides, including both, like RANDOM(1, sides) on the exam. Use random.randint.

roll(6)   ->  any of 1, 2, 3, 4, 5, 6
roll(1)   ->  1
import random
def roll(sides):
# Return a random whole number from 1 to sides
pass

What Check runs

Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.

RunsExpected output
print(roll(1))1
values = set() for _ in range(500): values.add(roll(4)) print(sorted(values))[1, 2, 3, 4]

More Simulation exercises

All Python exercises · 50 practice problems