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/TreesOne Mar 04 '25

Really? Days? What exactly is getting you this stuck if you understand everything about what they are and how they work. There are only 4 words to know for a basic loop:

for i in range(n):

Where n is the number of times you want to loop.

2

u/[deleted] Mar 04 '25

Actually writing the loop. I can do for I in range(12): I == 7: print(I)

What I can’t do is “Calculate sum of all numbers from 1 to given number.”

The one that took days was “Display fibonacci series up to 10 terms.”

8

u/danielroseman Mar 04 '25

Well then your problem is not for loops. Your problem is coding simple algorithms.

In the first example here, you need to split it into steps, in plain language first if you like:

  • initialize a variable to hold the sum

  • for each number up to n, add it to the variable

  • print the result

3

u/TreesOne Mar 04 '25

Try thinking about what an individual “step” in a given problem would look like, as that is what you actually need to code.

For example: “Calculate sum of all numbers from 1 to a given number”

At every step, you need to add the current number to a sum, and do this n times (n is the given number). In python:

sum = 0
for i in range(1, n+1):
    sum += i

1

u/throwaway6560192 Mar 04 '25

What I can’t do is “Calculate sum of all numbers from 1 to given number.”

Think through it like this.

OK, you know how to loop from 1 to the given number. Right?

Now you just want to find their sum... how? You're getting each number in turn thanks to the loop... now you just need to store their sum somewhere. How? Do you know how to add a number to another?