Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of python variable in for loop

Here's the Python code I'm having problems with:

for i in range (0,10):     if i==5:         i+=3     print i 

I expected the output to be:

0 1 2 3 4 8 9 

However, the interpreter spits out:

0 1 2 3 4 8 6 7 8 9 

I know that a for loop creates a new scope for a variable in C, but have no idea about Python. Why does the value of i not change in the for loop in Python, and what's the remedy to it to get the expected output?

like image 618
firecast Avatar asked Mar 12 '13 13:03

firecast


People also ask

What is the scope of variable in for loop?

The variable is within the scope of the loop. I.e. you need to be within the loop to access it. It's the same as if you declared a variable within a function, only things in the function have access to it.

What is the variable in a for loop Python?

A Python for loop has two components: A container, sequence, or generator that contains or yields the elements to be looped over. In general, any object that supports Python's iterator protocol can be used in a for loop. A variable that holds each element from the container/sequence/generator.

Can we pass variable in for loop in Python?

Python's for loop simply loops over the provided sequence of values — think of it as "foreach". For this reason, modifying the variable has no effect on loop execution. This is well described in the tutorial.

How is the scope of a variable determined by Python?

What is Variable Scope in Python? In programming languages, variables need to be defined before using them. These variables can only be accessed in the area where they are defined, this is called scope. You can think of this as a block where you can access variables.


1 Answers

The for loop iterates over all the numbers in range(10), that is, [0,1,2,3,4,5,6,7,8,9].
That you change the current value of i has no effect on the next value in the range.

You can get the desired behavior with a while loop.

i = 0 while i < 10:     # do stuff and manipulate `i` as much as you like            if i==5:         i+=3      print i      # don't forget to increment `i` manually     i += 1 
like image 128
Junuxx Avatar answered Oct 04 '22 04:10

Junuxx