Parapa
Parapa

Reputation: 87

"If" nested inside a "for" only enters once

Having problems with an IF inside a for.

print (frames_min)
print (frames_max)

for f in range(frames_min, frames_max):
    if ((f >= 96) and (f < 144)):
        f += 3
    print("A",f)

Result:

Output

Why not 100, 103, 106, 109 ??

Upvotes: 1

Views: 86

Answers (2)

H. U.
H. U.

Reputation: 637

You need to use while loop, instead of for loop.

 frames_min=97
 frames_max=144

 print (frames_min)
 print (frames_max)

 f=97
 while f >=frames_min and f<= frames_max:
    f = f + 3
 print("A",f)

Upvotes: 0

Knells
Knells

Reputation: 837

In Python for iterates through each variable, rather than by indices:

print (frames_min)
print (frames_max)

for f in range(frames_min, frames_max):
    if ((f >= 96) and (f < 144)):
        f += 3
    print("A",f)

Here you are increasing the value of f by 3, but f represents the actual number being stored there rather than an index. If this isn't desired you can use while

print (frames_min)
print (frames_max)
i = frames_min
while i < frames_max:
    print(i)
    i += 3

Alternatively you can use the 'step' parameter of the range command to make it give every 3rd number:

print (frames_min)
print (frames_max)

for f in range(frames_min, frames_max, 3):
    print("A",f)

Will do what I think is your desired result.

Upvotes: 2

Related Questions