yeah
yeah

Reputation: 31

Unexpected results from nested for loops

So I'm taking a course on edx and doing an exercise on nested loops and I'm having a really difficult time trying to understand how I'm getting the wrong answer.

Here is the exercise

m = 0
for x in range (1,3):
    k = 0
    for y in range (-2,0):
        k = k + y
        m = m + k
print (m)

I know when there's a nested loop the first for loop will iterate once then proceed to the second for loop and that will iterate to completion so with that knowledge I began to do the math:

0+-2      k=-2
0+-2      m=-2

-2+-1     k=-3
-2+-3     m=-5

-3+-2     k=-5
-5+-2     m=-7

0+-1      k=-1
-7+-1     m=-16

I end up with -16

Upvotes: 0

Views: 60

Answers (1)

jpp
jpp

Reputation: 164673

You are resetting k to 0 for each iteration of x. Your calculations assume that k is not reset.

You can see this by printing out intermediary values for k and m:

m = 0
for x in range (1,3):
    k = 0
    for y in range (-2,0):
        k = k + y
        m = m + k
        print(k, m)

# -2 -2
# -3 -5
# -2 -7
# -3 -10

Upvotes: 3

Related Questions