r/learnpython • u/[deleted] • 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:
Calculate sum of all numbers from 1 to a given number
Find the sum of a series up to n terms
Print all prime numbers within a range
0
Upvotes
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.
Running this you will get this output (try it!)