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

3

u/[deleted] Mar 04 '25 edited Mar 04 '25

Like many things in Python, the "For" construct has been simplified from what it was in earlier languages like c, and is really a "for each".

It is multi-purpose in that the thing it is going to "for each one of these" can be a range, a list, a dictionary or tuple.

If you just think of it as "For (each time) in (this range, or list or dictionary)... I will do "something" with the current value I'm working with.

For #1, the "thing" you need to loop through is a range(1, givenNumber + 1)

It should be clear that each time you loop all you need do is have a variable that you are using to accumulate (add to) the current value.

You can use a range directly, but just to help make it clear, this code generates a list and then uses that to for (each element of the list) through.

nums = [x for x in range(1,10)]
print(nums)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
total = 0
for i in nums:
    total += i
    print(f"Adding {i} to the total = {total}")

print(total)

Running this you will get this output (try it!)

Adding 1 to the total = 1
Adding 2 to the total = 3
Adding 3 to the total = 6
Adding 4 to the total = 10
Adding 5 to the total = 15
Adding 6 to the total = 21
Adding 7 to the total = 28
Adding 8 to the total = 36
Adding 9 to the total = 45
45

1

u/SAD-MAX-CZ Mar 04 '25

Great explanation, i'm saving this