ashukid
ashukid

Reputation: 353

Python why loop behaviour doesn't change if I change the value inside loop

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 ?

Upvotes: 1

Views: 1510

Answers (4)

Debendra
Debendra

Reputation: 1152

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

Upvotes: 2

Lakshmi - Intel
Lakshmi - Intel

Reputation: 601

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

Upvotes: 0

iz_
iz_

Reputation: 16633

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;
}

Upvotes: 6

pixie999
pixie999

Reputation: 498

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

Upvotes: 4

Related Questions