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

16

u/Agitated_Snow1434 Mar 04 '25

I don’t really know what exactly you’re stuck on. Could you possibly give a description?

2

u/[deleted] Mar 04 '25

“Find the sum of a series up to n terms”

10

u/crazy_cookie123 Mar 04 '25

Think about what data needs to be retained between iterations, what needs to be done each iteration, and how many times you need to iterate.

1

u/jongscx Mar 04 '25

Can you post how you solved it and what you think is wrong/why you think it didn't work?

1

u/[deleted] Mar 05 '25

I never solved it. I ended up looking at the answer and studying how it worked, but I’ve never solved one.

2

u/jongscx Mar 05 '25

So can you solve it now, after studying that example?

-2

u/__SlimeQ__ Mar 04 '25

you just make a variable before your for loop and set it to zero. then add each item to it.

you can also just use sum(my_list)

2

u/Buttleston Mar 04 '25

Yeah, it might help to see a sample of something you're asked to write, that you can't wrap your head around

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.

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.

2

u/crashfrog04 Mar 04 '25

You’re not writing enough code

2

u/[deleted] Mar 05 '25

I was writing pretty frequently until 2 months ago but I see what you mean. It’s hard to get a grasp on where to start. I’ve tried copying others codes and breaking them down to understand how they work. I tried a few failed projects here and there too. I’m hitting a wall here.

3

u/crashfrog04 Mar 05 '25

You have to write code even against the wall.

2

u/obviouslyzebra Mar 05 '25

If you want to, maybe we can find the place where you're stuck.

Can you guess what the output of this is?

for x in [1, 2, 3]:
    print(x)

(if you continue, I'll keep asking questions, each time a bit harder)

2

u/[deleted] Mar 05 '25

Output:

1

2

3

2

u/ninhaomah Mar 05 '25

Great!

2

u/[deleted] Mar 05 '25

I’ve dissected enough of these to know how to read them, I just can’t write them. /h

2

u/ninhaomah Mar 05 '25

Why ? Try writing one and show us the code.

1

u/obviouslyzebra Mar 05 '25 edited Mar 05 '25

Good!

Based on your other answers, you believe you already can understand loops with ease. So, let's do a few at a time. Later on we can move on to writing those loops ourselves.

Program 1 (this will aid us afterwards). Feel free to try running it yourself if you don't know the answer.

x = 1
print(f"x is equal to {x}")
y = 2
print(f"x={x} y={y}")

Program 2.

s = 0
for x in [1, 2, 3]:
    print(f"x={x} s={s}")

Program 3.

s = 0
for x in [1, 2, 3]:
    print(f"x={x} s={s}")
    s = s + x
    print(f"x={x} s={s}")
print(f"s={s}")

Please do no take more than 10 minutes on each exercise.

It's okay if you don't know something.

Good luck!

Edit: I edited some prints, hope you didn't see the message meanwhile, if so, sorry for the confusion.

1

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

Explanation 1: f marks everything after as a string to be printed, the brackets make sure that the variables are input/recognized within the string. So the output should be:

x is equal to 1
x = 1 y = 2

Explanation 2: x is equal to the list and s = 0 so if I hit run then the program will run through the list to define x, but s stays 0. So the output is:

x = 1 s = 0

x = 2 s =0

x = 3 s = 0

Explanation 3: This one caught me. That it would be x = 1 s = 0 but I didn’t realize it would cut there and then go to x = 1 s = 1 immediately after, I expected it to continue through the list for x before it moved on to the addition. But, I think it’s because, before completing the cycle, s + x was input. 1. Set the variables , 2. Update s based on the last bit, 3. print the next x and s, then print the final product of s.

x = 1 s = 1

x = 1 s = 1

x = 2 s = 1

x = 2 s = 3

x = 3 s = 3

x = 3 s = 6

s = 6

So it printed s and x, added s to x, updated s, and then added it again.
s = 6 because that is the final output of s

1

u/obviouslyzebra Mar 06 '25 edited Mar 06 '25

Great that you found a mistake on #3 :)

I'll give an explanation of this, and then some other exercises, just to make sure that we've got this right. Later on we can move to writing these loops.

Python, when it runs a for loop, iterates (goes over) each element of its "list" (in our case [1, 2, 3]) once, and, runs everything that's indented to the right at each of these iterations.

For example, at Program 3 above, here's the order that the program is executed at:

s = 0 (s initial value)

Iteration 1: (x=1)
    print(x=1, s=0)
    s = s + x -> s = 0 + 1 -> s = 1
    print(x=1, s=1)
    # note that s=1 at the end of iteration 1

Iteration 2: (x=2)
    print(x=2, s=1)
    s = s + x -> s = 1 + 2 -> s = 3
    print(x=2, s=3)

Iteration 3: (x=3)
    print(x=3, s=3)
    s = s + x -> s = 3 + 3 -> s = 6
    print(x=3, s=6)

After loop ends:
    print(s=6)

Some new exercises:

Exercise 4:

There's a problem in the program below. It wants to compute the sum of the numbers 1, 2 and 3. Can you spot the mistake and fix it?

s = 0
for x in [1, 2, 3]:
    print(f"x={x} s={s}")
s = s + x
print(f"Final s={s}")

Exercise 5:

Explain each step the computer takes when running this. Similarly to the explanation for Program 3 above that had Iteration 1: (x=1)....

x = 0
for i in [5, 10]:
    x = x + i
    print(f"i={i}, x={x}")

Good luck!

1

u/[deleted] Mar 09 '25

Q 1: All I noticed is that s = s+x wasn’t indented so it’s not recognized as part of the loop. It printed (1, 0), (2, 0), (3, 0) with final s being 3. When I corrected the indention it printed (x,s)-> (1, 0) (2, 1), (3, 3) Final s being 6.

Q 2: x = 0 -> define x for i in [5,10] -> i represents 5 and 10 x = x + i -> this is saying to add each iteration of i to x so x = 0, i = 5, 0 + 5 =5 x is now 5, i = 10, 5 + 10 =15 print (f”i={i} x ={x}”) -> this is saying to print to the ouptut Output: (i, x) -> (5,5) (10, 15)

Sorry about the spacey replies, I’m in class all week so it’s hard to find time for practice.

1

u/obviouslyzebra Mar 10 '25 edited Mar 10 '25

About spaced replies, it's all good...

I think that you understood the thing from the previous comment. So now, let's move on to write loops.

I'll come up with some exercises. Again, do not take more than 10 minutes on each of them. If you get stuck on something feel free to reply on it.

The objective here is to both see where you'd get stuck, and also to grow you a bit more accostumed to writing these for loops.

If you do get stuck on something, we can slow down a bit and explore the example a bit more closely.

Exercise 6:

Print all fruits from the list ["apple", "banana", "cherry"] using a for loop

Example output:

apple
banana
cherry

Exercise 7:

Print all numbers from 2 to 6 using a for loop and the range() function

Tip: range(1, 11) behaves the same as the list [1, 2, ..., 9 ,10] in a for loop. Note that we specified 11 instead of 10 in the end of range(), because the right end is not included.

Example output:

2
3
4
5
6

Exercise 8:

Print all numbers from 0 to 9 and whether they are even or odd using a for loop and range

Tip: You will probably have to write an if-else inside the loop. If you don't know how to determine if a number is even or odd, you can search for that on the internet.

Example output:

0 is even
1 is odd
2 is even
...
8 is even
9 is odd

Good luck

1

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

First: for i in [“apples”, “bananas”, “oranges”]: print(i) Output: Apples Bananas Oranges

Second: for i in range(1, 11): print(i) Output: 1 2 3 4 … 10

Third: I couldn’t get this one for i in range(9): if i / 2 ==0: print(f”The number {i} is even”) else: print(f”The number {i} is odd”) Output: 0 is odd 1 is even 2 is even 3 is even … 8 is even

I got similar results when using a range of (1, 10), !=, or switched the script from “is even” to “is odd”. When I messed around with the nesting I got an error that the nesting was invalid.

My mistake was using / rather than % / returns the result and using it was asking if i divided by 2 was equal to 0. Only 0 would ever satisfy that, everything else returned non zero. % returns the remainder. Using it was asking what was left over after dividing by 2. Ex: 4/2=2 with a remainder of 0 or 2.0, 5/2=2 with a remainder of 1 or 2.5. Switching the operators completely changed the question.

1

u/obviouslyzebra Mar 23 '25

Ok, you were able to write the loops and find the error when you didn't get it right at the first time! We will do 2 exercises next, I expect those to be a bit harder, but don't be afraid, I will give some tips for them, and if you don't manage to write them directly, we can focus on those later, it's all okay!

Exercise 9:

FizzBuzz from 1 to 15

Go through each number from 1 to 15 and:

  • Print "Fizz" if the number is divisible by 3

  • Print "Buzz" if the number is divisible by 5

  • Print "FizzBuzz" if the number is divisible by both 3 and 5

  • Just print the number, otherwise

Example output:

1
2
Fizz
4
Buzz
Fizz
...
14
FizzBuzz

Tips:

  • To check divisibility by 3, for example, you can write (i % 3 == 0)

  • Using if/elif/else fits well here

  • If you have some code, but don't understand what's happening, you can add prints to help you. Alternatively, if you're on a computer, you try to visit this website and put the code there

Exercise 10:

Check if a list is sorted in increasing order

Checking if a list is sorted: means that each number is at least as big as the number before it.

For example:

  • [1, 2, 3, 4, 5] is sorted because each next number is equal or greater than the previous.

  • [1, 3, 2, 4, 5] is NOT sorted because 2 is smaller than the number before it (3).

Here are the steps you can follow to do the exercise:

  1. First, create the list of numbers. Example: numbers = [1, 2, 3, 4, 5]. (Later, you can change this list to test different cases!)

  2. Make a variable to keep track if the list is sorted. We start "assuming" it's sorted (we haven't found any problems yet!): is_sorted = True

  3. Now, go through your list to check if it's sorted. You have two ways to choose from:

  • Option A (Using a previous number): Use this if you prefer looking directly at the numbers (not using positions).

    • Start by remembering the first number.

    • Then, go one by one from second number to last (for number in numbers[1:]), checking if the current number is smaller than the previous one. (If the current number is smaller, the list isn't sorted anymore!)

    • After each step, update the "previous number" to the current one, so it's ready for the next comparison.

  • Option B (Using numbers' positions/indexes): Use this if you're comfortable with looking at individual positions like numbers[1] and numbers[2].

    • Check each number (from position 0) against the next number (at position 1, and so on).

    • If you ever find a number bigger than the next one, the list is not sorted.

  1. At the end, after you've gone through all the numbers, just show a simple message on screen based on your variable from step #2: if is_sorted: print("List is sorted!") else: print("List is not sorted!")

  2. Check if your program works by trying different lists! (Here's one not sorted to test: [1, 3, 2, 4])

Tips:

  • Drawing things on paper can help (for example, understand how you'd check if a list is sorted on paper or on your head)

  • I'd say don't spend more than 25 minutes trying to solve it. If you do get stuck, it can be helpful to rest and do something else, then come later with a fresh head

  • Printing stuff and the pythontutor website (linked earlier) can also be helpful here (if you have some code)

Good luck!!

18

u/I-cant_even Mar 04 '25 edited Mar 04 '25

Can you calculate the sum of 1 to 2 without a loop?

Can you calculate the sum of 1 to 3 without a loop?

Now do the sum of 1 to 3 using 1 variable and only adding one number per operation.

Now do the sum of 1 to 5.

In the sum of 1 to 5 using 1 variable and only adding one number per operation what are the operations being repeated? Is there a way to make these repeated operations as part of a loop?

Edit: Coded examples

x = 1 + 2
print(x) # outputs 3

x = 1 + 2 + 3
print(x) # outputs 6

x = 1
x += 2 # or x = x + 2
x += 3 
print(x) # Outputs 6

x = 0 # We need to initialize x before we use x += num (equivalent to x = x + num)
for num in [1,2,3]:
  x += num
print(x) # outputs 6

x = 0
for num in [1,2,3,4,5]:
  x += num
print(x) # outputs 15

# Bonus, using range:
x = 0
for num in range(3):
  x += (num + 1) # Note: range(3) returns an iterable of [0,1,2]
                 #       adding 1 turns num into 1,2,3 through the loop
                 #       respectively

u/designated_weirdo Which of those steps is confusing?

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?

4

u/Some-Passenger4219 Mar 04 '25

Practice and mimicry. That's about it.

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

1

u/CptPicard Mar 04 '25

I actually disagree that python's for is a simplification from C. It's actually quite abstracted in comparison as it works on a generalised iterable instead of "initialisation, condition, increment".

2

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

I don't consider "simplification" to be a knock on Python, or at least that was not my intention. It's an elegant implementation, that can be used to do the same types of things people use "for loops" for in other languages, but also is based on iteration through a collection type, whereas for loops that borrow from c are typically independent language constructs, with the variables you mentioned. I considered presenting a c style for loop, but I didn't think that would add anything useful to this thread. At the point that someone starts combining Python with javascript, they will likely note that existence of the c style for loop in javascript (albeit with javascripts block scoping).

1

u/CptPicard Mar 05 '25

I did not take it as such. "Iterating over a collection type" is just way more complex in a sense than (typically) increasing an index variable.

2

u/[deleted] Mar 05 '25

Yes, and if this leads to people looking further into the idea of iterators, and then perhaps to how they can make some of their own classes iterable, that would be very cool.

2

u/Equal-Purple-4247 Mar 04 '25

I don't know what's the difference between 1 and 2. Here's how to do 1 & 3:

# Calculate sum of all numbers from 1 to a given number
n = 10
sumval = 0
for i in range(1, n+1):
    sumval += i
print(sumval) # <--- outside


# Print all prime numbers within a range
n = 10
for i in range(n+1):
    if is_prime(i): # You need to define your own is_prime function
        print(i) # <--- inside

There's no "mastering" loops, it just clicks when you get it. Some things to note:

  • In the first example, you want to return the result after the loop, so your return statement (or print statement for this case) is outside the loop

  • In the second example, you want to return a result for every iteration, so your print statement is inside the loop

4

u/maestro-5838 Mar 04 '25

Remember and write down this

For variable in interable

And

While condition

1

u/exxonmobilcfo Mar 04 '25

for is basically going through each item in an iterable and allowing you to define some process for it:

example: for x in range(10) This will iterate through each item in the iterable of the range object. The range object

The for loop basically creates an iterator and calls next on it till it terminates.

to create an iterator from an iterable do x = iter(range(10)), and you can call next(x) on it.