I need to get the next item of the first loop given certain condition, but the condition is in the inner loop. Is there a shorter way to do it than this? (test code)
ok = 0
for x in range(0,10):
if ok == 1:
ok = 0
continue
for y in range(0,20):
if y == 5:
ok = 1
continue
What about in this situation?
for attribute in object1.__dict__:
object2 = self.getobject()
if object2 is not None:
for attribute2 in object2:
if attribute1 == attribute2:
# Do something
#Need the next item of the outer loop
The second example shows better my current situation. I dont want to post the original code because it's in spanish. object1 and object2 are 2 very different objects, one is of object-relational mapping nature and the other is a webcontrol. But 2 of their attributes have the same values in certain situations, and I need to jump to the next item of the outer loop.
You can use the continue statement if you need to skip the current iteration of a for or while loop and move onto the next iteration.
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement.
Use the continue statement inside the loop to skip to the next iteration in Python. However, you can say it will skip the current iteration, not the next one.
In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.
Replace the continue
in the inner loop with a break
. What you want to do is to actually break out of the inner loop, so a continue
there does the opposite of what you want.
ok = 0
for x in range(0,10):
print "x=",x
if ok == 1:
ok = 0
continue
for y in range(0,20):
print "y=",y
if y == 5:
ok = 1
break
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With