educative.io

Why i+1 and not just i?

n = 10

x = 4

found = False  # This bool will become true once x in found

for i in range(0, n):

  if x == i:

      found = True

      print("Number found")

      break

else:

    print("Number not found")

What is the i+1 for? Just why the i+1? why not just “i”?


Type your question above this line.

Course: https://www.educative.io/collection/10370001/5473789393502208
Lesson: https://www.educative.io/collection/page/10370001/5473789393502208/4640037261541376

Dear @Arseniy_Filippov,
range(0, n) means the loop will run from 0 to n - 1 times. In this case, it is range(0, 10) . Hence, the loop will run from 0 to 9 . In order to compensate for that, we are using i+1 instead of i . There are ten natural numbers in the box but the loop is running from 0 to 9 . Hence we are adding i+1 to compensate for this. x will be compared with 0+1 , 1+1 , 2+1 , and so on.
I hope it helps!

I agree with @Arseniy_Filippov. The paragraph above the code example says that the loop should be looking for the number 4; with i+1 the loop would return at the number 3. If the goal was to check whether x is in the range, shouldn’t the if statement be comparing the values directly?