1

Let's say I wrote a piece of code :

for i in range(10):
    print(i)
    i=11

Why doesn't the loop terminate now ?

Even when I do this :

n=10
for i in range(n):
    print(i)
    n=0

It doesn't effect the loop ?

I'm just wondering how python is managing loop variables ?

Jab
  • 26,853
  • 21
  • 75
  • 114
ashukid
  • 353
  • 3
  • 18

4 Answers4

6

Python for loops are based on iteration, not a condition. They are stopped when StopIteration is reached, not when a certain Boolean condition evaluates to False.

range creates a temporary range object that cannot be changed during iteration. After range(10) or range(n) or whatever is called, this object is completely independent of what was used to create it.

You were probably expecting something like this to happen (C code):

for (int i = 0; i < 10; ++i) {
    printf("%d ", i);
    i = 11;
}

This is not how a for loop works in Python. It is more similar to this:

int range[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int count = 0; count < 10; ++count) {
    int i = range[count];
    printf("%d ", i);
    i = 11;
}
iz_
  • 15,923
  • 3
  • 25
  • 40
3

the range() function returns a list that you're iterating over Example for i in range(5) is equivalent to for i in [1,2,3,4,5] The for loop stops when it receives a StopIteration

Now, in your first block,

for i in range(10):
    print(i)
    i=11

i is assigned to 11 after printing, but after the assignment, the iteration finishes and i is reassigned to the next list element.

Moving the assignment before works as you'd expect

for i in range(10):
    i=11
    print i

Output:

11
11
11
11
11
11
11
11
11
11

In your second block:

n=10
for i in range(n):
    print(i)
    n=0

n is updated after range() has already generated it's list [1...10] so updating n has no effect

pixie999
  • 468
  • 5
  • 11
2

The range() function generates the integer numbers between the given start integer to the stop integer, which is generally used to iterate over with for Loop.

i is returned output not the assignment.

Docs: https://docs.python.org/3/library/functions.html#func-range

Debendra
  • 1,132
  • 11
  • 22
0

The whatever code we give inside the for loop is taken as a single block and will execute 10 times from i=0 to 9.

Even if you assign i=11 or any other variable x=1 inside the for loop , it will print the value that we assigned 10 times.

Please find the attachments.

enter image description here

enter image description here

Lakshmi - Intel
  • 581
  • 3
  • 10