user1454326
user1454326

Reputation: 65

Python: If in a For Loop

I'm creating a list of files with coordinates and id numbers.
a is just an arbitrary value to space out points. f is a file opened earlier and closed later. I'm using the code listed below. It should generate 511 points, skipping one point that would've originally been the 293rd point. Instead it is skipping 169 points and I cannot figure out why. Any help on this would be greatly appreciated.

id=1

for i in range(0,8,1):
    for j in range(0,8,1):
        for k in range(0,8,1):
            x1=i*a
            y1=j*a
            z1=k*a
            if ((i!=4) & (j!=4) & (k!=4)):
                f.write("%4.d  1  4  %4.3f  %4.3f  %4.3f\n"%(id, x1, y1, z1))
                id=id+1

Upvotes: 2

Views: 469

Answers (2)

Pavel Strakhov
Pavel Strakhov

Reputation: 40492

Your condition is wrong, there should be 'or' instead of 'and'. Also, your code can be simplified a bit, it should look like this:

for i in range(8):
    for j in range(8):
        for k in range(8):
            x1 = i * a
            y1 = j * a
            z1 = k * a
            if i != 4 or j != 4 or k != 4:
                print("%4.d  1  4  %4.3f  %4.3f  %4.3f\n" % (id, x1, y1, z1))
                id += 1

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601529

Since you require that i must be different from 4 AND j must be different from 4 AND k must be different from 4, you are skipping all points where ANY of these is 4. Use

if i != 4 or j != 4 or k != 4:

instead. Equivalently, but probably easier to grasp, you could write

if not (i == 4 and j == 4 and k == 4):

or even better

if i, j, k != 4, 4, 4:

Edit: Here's a completely rewritten version of your code:

points = itertools.product(range(0, 8 * a, a), repeat=3)
points = (p for p in points if p != (4 * a, 4 * a, 4 * a))
with open("filename", "w") as f:
    for id_p in enumerate(points, 1):
        f.write("%4.d  1  4  %4.3f  %4.3f  %4.3f\n" % id_p)

Upvotes: 5

Related Questions