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 lessonWrite 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) -> 1import 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.
| Runs | Expected 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
- A Chance of RainIntermediate
- Board Game TurnsAdvanced