user2628659
user2628659

Reputation: 25

Error i not defined in for loop using python

I have one array 'barray' of size 'bsize' and another 'carray' of size 'csize'. The i loop is for barray and j loop is for carray.

I get an error that i is not defined. I want the loops to go from 0 to bsize - 2 in steps of 3, and 0 to csize - 2 in single steps.

How should I relate the size and array to the for loop?

bsize = 960
csize = 960
barray = bytearray(fi.read())
carray= bytearray(f1.read())



for i in range (bsize-2,i+3):
    for j in range (csize-2,j+1):

Upvotes: 0

Views: 4651

Answers (1)

vroomfondel
vroomfondel

Reputation: 3106

 for i in range (0, bsize - 2, 3): #possibly bsize - 1?
    for j in range (csize - 2): # possibly csize - 1?
        #do your thing

That will loop through the first one incrementing i by 3 every time, and j by 1.

Look at this tutorial or these docs to learn range, it's really useful!

I'm not sure if you want to go through bsize - 2 or just up to it. If through, use size - 1 to get size - 2.

The reason you're getting an error is that you haven't defined the i you're using in the step. As you can see, python's range isn't like a lot of other languages' for constructs. Once you get used to it, though, it's really flexible and easy to use.

Some examples using simple range:

>>> for i in range(0, 14, 3):
...    print i
... 
0
3
6
9
12

>>> for i in range(1, 5):
...     print i
... 
1
2
3
4

>>> for i in range(5):
...     print i
... 
0
1
2
3
4

Upvotes: 4

Related Questions