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

Show parent comments

2

u/[deleted] Mar 05 '25

Output:

1

2

3

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!!