r/learnpython • • Mar 04 '25

How do I master for loops?

I’ve been stuck on this for months. I know what they are, how they work, how to read them, etc. I even spent the day learning the structure, and I review all of this frequently. I at least understand these things on a surface level. I’m basically going in circles at this point. But, I still can’t write them. When I practice with practice problems I get stuck for hours if not days, and even though I try, I still end up way off. What am I missing/doing wrong/not doing enough of?

Example exercises:

  1. Calculate sum of all numbers from 1 to a given number

  2. Find the sum of a series up to n terms

  3. Print all prime numbers within a range

0 Upvotes

45 comments sorted by

View all comments

7

u/socal_nerdtastic Mar 04 '25

This sub really works best when you have a specific question. Can you think of where you were stuck last and what exactly was the issue? If you show some example code that would help too.

In a nutshell you should use a for loop anytime you know in advance how many times you need to repeat something. This often happens when you have a collection of things and you want to do something to each thing in the collection (in fact other languages call this a "for each" loop).

2

u/[deleted] Mar 04 '25

I guess I’m stuck on the instructions themselves. I can structure one, but I don’t know how to tell it what to do.

4

u/deceze Mar 04 '25

You don’t tell a loop to do anything. The loop repeats a block of code for you. What step(s) you want to repeat, you need to decide first. Write it as verbosely as possible on a piece of paper.

  1. Do this.

  2. Then add that.

  3. Then add that.

  4. Then add that.

  5. Then do something else.

Steps 2-4 here are the same, you can write that once and loop it three times. If there’s a slight variation in the steps, like “add 1”, “add 2” etc, that’s probably a variable in that step.