Reputation: 67
Can someone explain why this causes an infinite loop even tho the continue from what I have been reading should "skip" the iteration
x = 0
while x < 50:
if x == 33:
print("I hit 33")
continue
else:
pass
print(x)
x+=1
Upvotes: 0
Views: 312
Reputation: 160
I'm guessing the code you're trying to get at is as follows, which will print out each integer from 0 - 50 (exclusive), except it will print "I hit 33" for the integer 33.
x = 0
while x < 50:
if x == 33:
print("I hit 33")
else:
print(x)
x += 1
You really don't need the continue
or pass
in this instance. continue
continues with the next cycle of the nearest enclosing loop. pass
is usually only used as a placeholder when a block is expecting a statement but you're not ready to use the statement.
Upvotes: -1
Reputation: 100
You are skipping the increment that happens at the end of the while
loop when you call continue
. The following will automatically increment if you want to keep the continue
statement:
for x in range(50):
if x == 33:
print("I hit 33")
continue
else:
print(x)
Otherwise, delete the continue
.
Upvotes: 2
Reputation: 12156
continue
goes to the next iteration. You want break
which exits the loop. See:
for i in range(10):
if i == 5:
continue
if i == 8:
break
print(i)
outputs:
0
1
2
3
4
6
7
Upvotes: 1
Reputation: 818
I think you are confusing break and continue.
continue
will skip to next iteration in innermost loopbreak
will leave innermost loopUpvotes: 1
Reputation: 223082
The continue
command restarts the innermost loop at the condition.
That means after x
reaches 33
, x += 1
will never execute because you will be hitting the continue
and going back to the while
line without running the rest of the code block.
x
will forever be 33
so you will have a infinite loop.
Upvotes: 4