Anatomy of a Python Loop

https://news.ycombinator.com/rss Hits: 2
Summary

Last time, when we built our little dice-rolling function, we learned how to package up logic into reusable blocks. One die roll at a time was cool… but any tabletop nerd knows the real action starts when you need to roll lots of dice.3d6 for ability scores.8d6 for a fireball spell.Or the cruel 10d10 your DM makes you roll when things go really sideways.So how do we tell Python: “Hey, repeat this action multiple times”?That’s where loops come in.What Is a Loop in Python?A loop is Python’s way of saying: “Do this again… and again… and again… until I say stop.”There are two main flavors:for loops: great for going through a sequence (like rolling N dice).while loops: keep going while a condition is true (like rolling until you finally get a natural 20).For Loops (Rolling Multiple Dice)Let’s roll 3d6 for a strength score.import random def roll_3d6(): rolls = [] for _ in range(3): rolls.append(random.randint(1, 6)) return sum(rolls) print(roll_3d6()) # e.g. 12What’s happening:for _ in range(3): → repeat the block three times.Each time, roll a d6 and add it to the list.Finally, sum them up.That’s your 3d6 strength roll in one clean function.While Loops (Rolling Until You Crit)Now let’s simulate rolling a d20 until we finally hit that sweet, sweet 20.def roll_until_crit(): attempts = 0 while True: attempts += 1 result = random.randint(1, 20) if result == 20: return attemptsThis loop keeps running until it hits the condition we want: a natural 20. Sometimes you’ll get it on the first try. Sometimes Python will make you sweat.What Does continue Do in Python?Here’s the keyword that confuses a lot of beginners.The continue statement says: “Skip the rest of this loop iteration and jump straight to the next one.”Let’s say you’re rolling a handful of dice but you want to ignore 1s (they don’t count toward the total).def roll_ignore_ones(num_rolls=5): total = 0 for _ in range(num_rolls): result = random.randint(1, 6) if result == 1: continue # Skip 1s completely total += result re...

First seen: 2025-08-30 03:38

Last seen: 2025-08-30 04:38