1

I'm looping over all lines in a file, splitting each line into tokens based on whitespace. For example, a line: circle 1 2 3 would be split into 4 tokens, circle, 1, 2, 3.

If the line begins with a comment (#) or is empty, my tokenList is also empty. If this is the case, I can't check tokenList[0] etc.

If the size of the list is 0, I want to jump to the next line - the next loop in the for loop:


       for line in self.myFile:
            tokenList = self.getTokens(line)
            if len(tokenList) == 0:
                ## ISSUE HERE
            if tokenList[0] == "shape":
                s = RayTracerShapes.Shape()
                self.scene.addShape(s)

I tried break, but this seems to jump right out of the loop, rather than ending the current iteration. Is there a way to jump out of the loop I'm in, and into the next loop, without jumping right out of the for loop altogether?

simont
  • 68,704
  • 18
  • 117
  • 136
  • Incidentally, You don't need to loop to split by whitespace. [str.split()](http://docs.python.org/library/stdtypes.html#str.split) can do that for you. – acattle Aug 09 '12 at 04:31
  • @acattle The `getTokens(line)` method splits on whitespace, plus does a few checking things (syntactical parsing of the tokens to ensure legal tokens), using the `str.split()` method. Thanks for the tip, though. – simont Aug 09 '12 at 04:43

1 Answers1

5

Use the continue keyword.

When continue is encountered the rest of the statements in the body of the loop are skipped and execution continues from the top of the loop.

This SO question might be helpful: Example use of "continue" statement in Python? and this quick reference has two short examples of its use.

In your case:

   for line in self.myFile:
        tokenList = self.getTokens(line)
        if len(tokenList) == 0:
            continue # skip the rest of the loop, go back to top
        if tokenList[0] == "shape":
            s = RayTracerShapes.Shape()
            self.scene.addShape(s)
Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191