Jaimen Perez
Jaimen Perez

Reputation: 55

understanding for loops w/ ranges in python

I don't understand loops w/ranges..

...in light of the answer to problem 1, problem 2 is confusing...

Problem 1: What is the value of j at the end of the following code segment?

j = 0
for i in range(0, 4):
   j = j + i

Problem 2:

j = 0
for i in range(1, 10):
   if j < 10 :
      j = j + i

Problem 1:
Answer: 6
j = (j+1)+(j+2)+(j+3)

Problem 2:
Answer: 10
My answer: ???
Why not j = (j+1)+(j+2)...(j+9)?
(I don't understand what the expression "if j<10" evaluates to here..)

Upvotes: 1

Views: 89

Answers (4)

mauve
mauve

Reputation: 2763

j = 0
for i in range(1, 10):
   if j < 10 :
      j = j + i

The outer "for" loop executes until it exhausts the range for i. On each outer loop, j is evaluated to see if it's less than 10. If it is, j is incremented up by the value of i on that loop. In the 4th loop, j becomes 10 and remains that value for the rest of the execution.

loop        j    i   j(end)
1           0    1   1
2           1    2   3
3           3    3   6
4           6    4   10
5           10   5   10
6           10   6   10
7           10   7   10
8           10   8   10
9           10   9   10
<end>

Upvotes: 2

RSchneyer
RSchneyer

Reputation: 300

if j < 10 checks the value of j each loop, and runs the following line only if the value of j is less than 10. If the value of j is equal to or greater than 10, j = j + i is not ran, and the value of j is not increased.

Upvotes: 1

griffin_cosgrove
griffin_cosgrove

Reputation: 447

I think you have a misconception about the order of execution. Every iteration of the loop the statement if j < 10 : is evaluated. So after the 4th iteration j does not get increased due to the if statement being false.

Upvotes: 2

AAA
AAA

Reputation: 3670

This is a simple logical question. In Problem 2, j =j + i is only executed if j < 10:


After the first run, we have j = (j+1) = 1 (since j is initially 0)
After the second run, we have j = (j+1) + (j+2) = 3
After the fourth run, we have j = (j+1) + (j+2) + (j+3) + (j+4) = 10


Since j is no longer less than 10, the if condition means that no further i is added to j, at this point.

Upvotes: 1

Related Questions