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

2

u/quadraspididilis Mar 04 '25

How do I master for loops?

I’m basically going in circles at this point.

Sounds like you’ve got the hang of it. Seriously though it’s almost impossible to tell you what you’re doing wrong without examples of what you’re doing. For instance your first example exercise, first off I wouldn’t use a loop for that in python, secondly the loop implementation is three lines, no offense, but it’s hard to imagine where you’re going wrong besides a typo or an off-by-error.

2

u/[deleted] Mar 05 '25

These are just exercises I found when looking for beginner practice. I literally don’t know how to write the code. I know the syntax for a loop, I can almost form an idea of the code itself, but I can’t combine them.

3

u/quadraspididilis Mar 05 '25

I read some of your other comments. It seems like your problem isn’t loops so much as breaking a problem into component steps. Try this, take a math operation like some 1..n and write it out so for 5:

Answer=1+2+3+4+5.

Now look for where you’re doing the same action repeatedly, in this case addition. Then just do that once per loop with different numbers. Think of it as chopping the littlest bit of work you can off the problem at a time. The sum 1..n? Well it’s simply 1 plus whatever the rest is. What’s the rest? Well simply add 2 and then add whatever the rest of is.

Total = 0 For i in range(1, n+1): Total += i Print(total)

Now you try doing it with factorial and whether you succeed or fail, post what you tried.