Special Commands
Last updated
Last updated
Python has some special commands, break
, continue
, and pass
, that give you more control over your loops and blocks.
The break
command allows you to exit a loop prematurely.
You would obviously want to place the break command inside of a conditional statement like the loop above. One thing you might notice is that we could avoid using the break command in the example loop by simply setting a likes_broccoli
variable and then placing the last print
in an else statement.
We can often avoid the break
command with some careful structuring but it is sometimes really handy to use which is why we are learning about it.
The continue
command allows you to continue the next iteration without covering the rest of the block. The following example prints all of the numbers from 1 to 20 except those that are multiples of 3. It uses the modulus operator to find out which ones are multiples of 3.
We could restructure this example just like we did with the break
example so that we wouldn't have to use the continue
command by putting the if statement around the print.
Again, you should often be able to avoid using the command but it can come in handy.
The pass
command is what we call a noop (pronounced NO-op and means that there is no operation). You might be wondering why you would want something that does nothing in your code. What the pass
command allows you to do is stub your code out. There are times where you know that you are going to use an if statement but don't know what to do in the block.
If we didn't put pass
in the if statement above, the program would not be able to run. The pass
simply allows us to write a program that compiles.
Try writing some loops that break out early and continue based on some of your own conditions!