← All video projects

Free video project · Beginner

Trick or treat simulator 🎃

Thirty houses, random sweets, the odd trick and a dictionary that counts the haul, with a bar chart and a fair way to share it out.

The video is out Friday 30 October at 6pm.

The code from the video

# Halloween: trick-or-treat simulator
import random
random.seed(31)

SWEETS = ["chocolate bar", "lollipop", "jelly snakes", "toffee", "eyeball gum"]
bag = {}
tricks = 0

for house in range(1, 31):
    roll = random.random()
    if roll < 0.2:
        continue                      # nobody home
    if roll < 0.3:
        tricks += 1                   # a trick instead!
        continue
    for _ in range(random.randint(1, 3)):
        sweet = random.choice(SWEETS)
        bag[sweet] = bag.get(sweet, 0) + 1

total = sum(bag.values())
print("Houses visited: 30")
print("Tricks played on us:", tricks)
print("Sweets collected:", total)
for sweet, count in sorted(bag.items(), key=lambda s: s[1], reverse=True):
    print(f"  {sweet:<14}{'#' * count} {count}")

kids = 3
print(f"Each kid gets {total // kids}, and {total % kids} left over for the grown-up")

Run it in your browser with nothing to install, right here on this page.

Make it your own

  1. Simulate 1,000 Halloween nights and find the average haul.
  2. Give some houses a full-size chocolate bar worth five sweets.
  3. Stop early when the bag is full at 40 sweets and say which house filled it.

Skills: random, dictionaries, continue, sorting

Start the free lessons More video projects