Python, Concept by Concept › Randomness: Dice, Simulations, and a Wandering Turtle
Exercises: Randomness: Dice, Simulations, and a Wandering Turtle
Core: Exercises 1–10 are the main path. More Practice: Exercises 11–17 add simulations, games, and turtle drawings. Challenges: Exercises 18–20 are optional stretch work; no core exercise depends on them.
For function exercises, define the named function and return its result. Seeded functions begin with import random and call random.seed(4) before their first choice, so the samples repeat. Use only random.seed, random.randint, and random.choice on a range or string. Keep input() out of the function; a Real version is a separate program that reads the values.
Exercise 1: Dice Total
A tabletop game needs the total of several six-sided dice rolls.
Specification: Define roll_total(rolls). Seed with 4, start total at 0, and repeat rolls times. Each trip adds random.randint(1, 6) to the running total. Return total. Assume rolls is a positive integer.
Worked sample calls:
roll_total(4) → 12
roll_total(7) → 22
roll_total(10) → 25
Real program
The real program reads the number of rolls with input().
How this is checked: Checked by tests that run your function roll_total.
Exercise 2: Heads Counter
A science exhibit represents tails with 0 and heads with 1.
Specification: Define count_heads(flips). Seed with 4, then perform flips trials using random.choice(range(2)). Add 1 to total only when the choice equals 1. Return the count.
Worked sample calls:
count_heads(6) → 3
count_heads(14) → 6
count_heads(20) → 8
Real program
The real program reads the number of flips with input().
How this is checked: Checked by tests that run your function count_heads.
Exercise 3: Bonus-Round Score
A game adds a strong roll to the score but charges one point for a smaller roll.
Specification: Define bonus_score(rounds). Seed with 4 and start score at 0. In each round, choose roll = random.randint(1, 6). If roll >= 4, add the roll to the cumulative score. Otherwise subtract 1. Return the final score.
Worked sample calls:
bonus_score(5) → 7
bonus_score(8) → 9
bonus_score(12) → 16
Real program
The real program reads the number of rounds with input().
How this is checked: Checked by tests that run your function bonus_score.
Exercise 4: Target Roll Counter
A game designer wants to know how often one chosen die value appears.
Specification: Define count_targets(trials, target). Seed with 4. Roll with random.randint(1, 6) exactly trials times. Add 1 to total only when the roll equals target, then return total. Assume target is from 1 through 6.
Worked sample calls:
count_targets(12, 3) → 1
count_targets(30, 6) → 2
count_targets(50, 1) → 10
Real program
The real program reads the trial count and target face on separate lines with input().
How this is checked: Checked by tests that run your function count_targets.
Exercise 5: Even-Roll Percentage
A booth report needs a percentage, not just a count.
Specification: Define even_percent(trials). Seed with 4 and count rolls from random.randint(1, 6) that are divisible by 2. Return round(100 * total / max(trials, 1), 1).
Worked sample calls:
even_percent(10) → 50.0
even_percent(25) → 40.0
even_percent(100) → 47.0
Real program
The real program reads the trial count with input().
How this is checked: Checked by tests that run your function even_percent.
Exercise 6: Quarter-Circle Estimate
Use random integer points in the square from 0 through 1000 on each axis to estimate π. Each axis has 1001 possible integer values.
Specification: Define estimate_pi(trials). Seed with 4. For every trial, choose x = random.randint(0, 1000) and y = random.randint(0, 1000). Count the point when x*x + y*y <= 1000*1000. Return round(4 * inside / max(trials, 1), 2). The factor 4 changes the quarter-circle fraction, about π/4, into an estimate of π.
Worked sample calls:
estimate_pi(20) → 3.4
estimate_pi(200) → 3.14
estimate_pi(2000) → 3.08
These are estimates close to π, not exact values of π.
Real program
The real program reads the trial count with input().
How this is checked: Checked by tests that run your function estimate_pi.
Exercise 7: Rescue-Robot Random Walk
A rescue robot travels a fixed distance, then randomly turns left or right.
Specification: Complete assets/ex7_random_walk.py. Keep module-level import turtle and import random, with random.seed(4) before the first random choice. Replace the closed placeholder with a 20-move open walk. Set step = 31, move_count = 20, the pen color to "seagreen", and the pen size to 3. In each trip, move forward by step, choose turn = random.randint(0, 1), turn left 90 degrees for 0, and turn right 90 degrees otherwise. Keep one turtle.done() at the end.
Run it with:
assets/ex7_random_walk.py
Check yourself: The final program makes 20 pen-down moves, repeats the same seeded route on every run, and is intentionally open.
Real program
The real program reads the step length, the number of moves, and the colour with input(), then draws the same picture.
How this is checked: You check this one yourself, against the list below. The turtle drawing is checked from the moves your program makes.
The site cannot check this one. Run your program, then tick each item below when your work does it.
Exercise 8: Die Face Art
A board game needs an exact three-row drawing for every die face.
Specification: Define die_face(n) for faces 1 through 6. Return one string with three rows separated by "\n"; never leave a space at a row end. Use an if/elif chain on n to choose these rows: 1: ... / .o. / ...; 2: o.. / ... / ..o; 3: o.. / .o. / ..o; 4: o.o / ... / o.o; 5: o.o / .o. / o.o; 6: o.o / o.o / o.o. Add a purpose comment above the chain.
Worked sample calls:
die_face(1) -> "...\n.o.\n..."
die_face(5) -> "o.o\n.o.\no.o"
die_face(6) -> "o.o\no.o\no.o"
Real program
The real program reads a die face with input().
How this is checked: Checked by tests that run your function die_face.
Exercise 9: Roll Until Six
A game keeps rolling until its target face appears.
Specification: Define rolls_until(target). Inside the function, call random.seed(4) before a choice. Roll random.randint(1, 6) repeatedly with a while loop, count every roll including the target roll, and return the count. Assume target is 1 through 6. Add a purpose comment explaining the counter. The real program prints Rolls: <count>.
Worked sample calls:
rolls_until(6) -> 4
print("Rolls:", rolls_until(6)) -> Rolls: 4
Real program
The real program reads the target face with input().
How this is checked: Checked by tests that run your function rolls_until.
Exercise 10: Longest Heads Streak
A coin game rewards the longest uninterrupted run of heads.
Specification: Define longest_heads(flips). Seed 4, then choose random.choice("HT") exactly flips times. Keep a current heads streak and the longest one; tails reset the current streak. Add a purpose comment for the two counters. Return the longest streak. The real program prints Longest streak: <result>.
Worked sample calls:
longest_heads(20) -> 4
print("Longest streak:", longest_heads(20)) -> Longest streak: 4
Real program
The real program reads the flip count with input().
How this is checked: Checked by tests that run your function longest_heads.
Exercise 11: More Practice: Two-Dice Histogram
A booth wants a bar for each possible total of two dice.
Specification: Define two_dice_histogram(pairs). For each target total from 2 through 12, call random.seed(4), roll pairs pairs with two random.randint(1, 6) calls per pair, and count matches. Reseeding for each total replays the same sample for every bar. Make label = str(total) and add one leading space when total < 10. Build each row as label + ":" + "#" * count; join rows with "\n" and return the string. No format-width specification. The real program prints the returned string.
Worked sample calls:
two_dice_histogram(36) -> " 2:##\n 3:##\n 4:######\n 5:#####\n 6:####\n 7:###\n 8:#####\n 9:#######\n10:#\n11:#\n12:"
Real program
The real program reads the number of dice pairs with input().
How this is checked: Checked by tests that run your function two_dice_histogram.
Exercise 12: More Practice: Pig Turn
In Pig, a 1 ends the turn and loses its points.
Specification: Define pig_turn(goal). Seed 4; keep rolling random.randint(1, 6) until the running turn total reaches goal or a 1 appears. After each roll, add it to the total, then test: use if roll == 1: to set the score to 0 and stop; use elif total >= goal: to stop with that score. Return the score. The real program prints Turn score: <score>.
Worked sample calls:
pig_turn(20) -> 0
print("Turn score:", pig_turn(20)) -> Turn score: 0
Real program
The real program reads the turn goal with input().
How this is checked: Checked by tests that run your function pig_turn.
Exercise 13: More Practice: Nim Winner
Two players take turns removing 1, 2, or 3 stones; the player taking the last stone wins.
Specification: Define first_player_wins(stones). Return the Boolean result of stones % 4 != 0. The first player loses when the starting pile is a multiple of 4. The real program prints First player wins: <result>.
Worked sample calls:
first_player_wins(12) -> False
first_player_wins(13) -> True
print("First player wins:", first_player_wins(12)) -> First player wins: False
Real program
The real program reads the stone count with input().
How this is checked: Checked by tests that run your function first_player_wins.
Exercise 14: More Practice: Three Heads in a Row
Keep flipping until a specified heads streak has appeared.
Specification: Define flips_to_streak(length). Seed 4, then repeatedly choose random.choice("HT") until the current run of heads reaches length. Count every flip; reset the streak after T. Return the flip count. The real program prints Flips: <count>.
Worked sample calls:
flips_to_streak(3) -> 8
print("Flips:", flips_to_streak(3)) -> Flips: 8
Real program
The real program reads the required heads streak length with input().
How this is checked: Checked by tests that run your function flips_to_streak.
Exercise 15: More Practice: Average Roll
A game analyst wants the mean of several die rolls.
Specification: Define average_roll(rolls). Seed 4, roll random.randint(1, 6) exactly rolls times, add to a running total, and return total / rolls. Assume rolls is positive. The real program prints Average: <result>.
Worked sample calls:
average_roll(10) -> 2.5
print("Average:", average_roll(10)) -> Average: 2.5
Real program
The real program reads the number of rolls with input().
How this is checked: Checked by tests that run your function average_roll.
Exercise 16: More Practice: Random Polygon
A random choice sets the number of sides for a closed turtle shape.
Specification: Complete assets/ex16_random_polygon.py. Keep module-level import turtle and import random; call random.seed(4) before choosing sides = random.randint(3, 8) (seed 4 gives 4). Set length = 70 and angle = 360 / sides. With the pen down, repeat turtle.forward(length) and turtle.right(angle) once per side. Keep one turtle.done() at the end. Run assets/ex16_random_polygon.py.
Worked sample calls:
random.seed(4); sides = random.randint(3, 8) -> 4
drawing -> 4 pen-down moves; angle = 90.0; closed path
Real program
The real program reads the edge length with input(), then draws the same picture.
How this is checked: You check this one yourself, against the list below. The turtle drawing is checked from the moves your program makes.
The site cannot check this one. Run your program, then tick each item below when your work does it.
Exercise 17: More Practice: Random Color Row
A tile artist draws four colored squares in one row.
Specification: Complete assets/ex17_random_color_row.py. Keep module-level turtle/random imports and call random.seed(4) before the first color choice. For each of four side-30 squares, choose a code with random.choice("rgb"); use if/elif/else to map r to red, g to green, and b to blue using turtle.pencolor. Draw all four sides with turtle.forward(30) and turtle.right(90), then lift the pen, move forward(30), and lower it. After all four, lift the pen and move backward(120) to the start. Keep one turtle.done() at the end. Run assets/ex17_random_color_row.py.
Worked sample calls:
random.seed(4); four choices from "rgb" -> r, g, r, b
drawing -> red, green, red, blue; 16 pen-down moves; closed path
Real program
The real program reads the side length and the number of squares with input(), then draws the same picture.
How this is checked: You check this one yourself, against the list below. The turtle drawing is checked from the moves your program makes.
The site cannot check this one. Run your program, then tick each item below when your work does it.
Exercise 18: Highest Twenty-Sided Roll
A fantasy game wants the highest result seen so far without storing all the rolls.
Specification: Define highest_roll(trials). Seed with 4 and start high at 0. Repeat trials times, choose random.randint(1, 20), and update high with max(high, roll). Return high.
Worked sample calls:
highest_roll(3) → 10
highest_roll(10) → 16
highest_roll(30) → 18
Real program
The real program reads the trial count with input().
How this is checked: Checked by tests that run your function highest_roll.
Exercise 19: Multiples in a Random Range
A number carnival draws values from 1 through 20 and counts multiples of a chosen number.
Specification: Define count_multiples(trials, n). Seed with 4. Each trial chooses random.choice(range(1, 21)). Add 1 to total when the chosen value is divisible by n, then return total.
Worked sample calls:
count_multiples(10, 4) → 3
count_multiples(25, 5) → 3
count_multiples(40, 3) → 15
Real program
The real program reads the trial count and divisor on separate lines with input().
How this is checked: Checked by tests that run your function count_multiples.
Exercise 20: Random Password
A game generates a repeatable practice password from an allowed alphabet.
Specification: Define random_password(length). Seed 4 and make length choices from "abcdefghijkmnpqrstuvwxyz23456789", adding each chosen character to a string. Return the password. The real program prints it.
Worked sample calls:
random_password(6) -> "rvg38j"
Real program
The real program reads the password length with input().
How this is checked: Checked by tests that run your function random_password.
Back to Randomness: Dice, Simulations, and a Wandering Turtle