Pass, Break and Continue in Python 3

Josh Robin
The Startup
Published in
9 min readDec 23, 2019

If you’re new to Python coding, you may have come across pass, break and continue. These words are known as control statements because they are used to perform specific tasks for control flow. In other words, they help tell Python when or for how long to do something, like running a loop, before moving on to something else.

When I first starting coding in Python, I often got confused about these particular keywords (special words that are reserved in Python). Understanding the differences between pass, break and continue can be difficult at first, but it is useful to learn when and how to use them. So without further ado, here is the rundown on pass, break and continue for beginners:

Pass

This is probably the simplest of the three, so it will the best one to start with. Essentially, you use pass when you want to do… nothing.

Sounds weird right? Why would we need to do this? Let’s look at a few examples to help illustrate why this might be useful.

In many cases, pass is really just used as a placeholder for code that will eventually be added later. For example, say you are working on a project, and you know you are going to need a function to do something. Maybe you are working on a different part of your code and you don’t want to get caught up in building out the function right now, but you want to have some kind of reminder that you will need that function later, so you define it like so:

def my_function():

The problem with this is that leaving your function empty will give you an IndentationError because once the function is defined, Python is expecting something to be inside it, so it assumes the next line of code should be indented. To stop this from happening, all you need to do is put pass in the function.

def my_function():
pass

This way, you will have an empty function that does nothing, and you can run your code without getting an error. This enables you to build out the skeleton of your program while still maintaining a workflow that you are comfortable with.

The same thing can be done with a loop if you need it. For example:

for thing in loop:
pass

Again, if you don’t put pass in the loop and try to run code after it, you will get that same IndentationError.

There are some cases where you may want to use pass in a permanent way as well. These can be divided into two main categories:

The first would be to use it in an if or elif statement when you want to do nothing if a certain condition is met, for example:

if type(x) != int:
pass
elif x < 2:
print('Less than 2')
elif x < 7:
pass
else:
print('Greater than 6')

The above code will check if x is an integer and if it isn’t, it will do nothing and avoid the rest of the conditions. This is a handy way of handling unwanted data types. If x was 5, nothing would happen there either, because the third block of code has a pass as well.

The other common way to use pass would be in error handling with try and except blocks. Like the previous example, this would be one instance where pass can be useful even in the final version of your code.

For example, let’s say you have a string of numbers and letters, and you want to print only the numbers. There are several ways to do this, but one easy way would be to loop through the string and then use a try and except block to attempt to convert each character into an integer. When the loop hits a letter, you can use pass to skip over that character and you will be left with only the numbers.

string = 'a1b2c3'for char in string:
try:
print(int(char))
except ValueError:
pass

Output:

1
2
3

Using pass to handle errors in this way can be valuable when you want Python to strategically avoid certain errors. In general, you probably won’t need to use pass very often, but these examples show some areas where it can be useful.

Break

This one is more commonly used and is also a bit more involved. The term break is used when you want to exit or “break” out of a loop. It can only be used within a loop, and it allows you to stop a loop midcourse.

You can use break in either a for loop or a while loop. For an example of how it can be used in a for loop, say I want to print only the first word in a sentence. One way to do this is by looping through each character in the string until the first space, and then using break to stop the loop.

sentence = 'This is a string of words.'for i in range(len(sentence)):
if sentence[i] == ' ':
print(sentence[:i])
break

Output:

This

By adding thebreak to the loop, you are stopping it before it reaches the end of the sentence. The loop could run any number of times, depending on where the first space is. Or, if this was a one-word sentence, the loop would continue all the way to the end of the string. This can be useful when you want a certain condition to stop a loop.

A common way of using break in a while loop would be to keep a program running until the user decides to quit. To do this, you can set up a loop that starts with while True: and use break when you want the program to end. For example:

while True:    print('Press Enter to keep this program running')    choice = input('or type anything to quit: ')    if choice == '':
print('\nStill running...\n')
else:
print('\nYou typed', choice)
print('Quitting program...')
break

This is a very basic (and boring) program just to demonstrate a concept. Because the loop begins with while True, the user can press Enter as many times as they want and the program will keep repeating the same prompt over and over again. When the user decides to type something, the program hits the break and shuts down. In theory, this loop could run ad infinitum, which should serve as a warning to anyone trying to use this in a script. If you use while True and you don’t have a break somewhere in your code, your program will never stop running!

Why is this useful? The above example may seem like a pointless exercise, but it is great when you want to give a user the option to repeat a process as many times as they want. For a simple example, you could have a program that takes an integer and tells you whether or not it is a prime number, and this way you wouldn’t have to restart your program every time you wanted to try a new number.

You can even nest smaller loops like this inside a larger one and have all the control you want over the flow of the user interface. For example, if you want the user to input an integer only and they input a non-integer, you can keep prompting them to try again until they input an integer. Then, once they input an acceptable value, you breaking out of the loop and continue on with the program. Here’s an example of a program that takes the sum of any two numbers:

# Welcome prompt.
print('This program will give you the sum of any two numbers.\n')
while True:# Choice to run the program or quit.
choice = input('Enter 1 to continue or 2 to quit: ')

# Move on if the choice is 1.
if choice == '1':

# Take the first number from the user.
while True:
num1 = input('Enter the first number: ')
try:
a = float(num1)
break
# In case the user enters something other than a number.
except ValueError:
print('\nThat is not a number!')

# Take the second number from the user.
while True:
num1 = input('Enter the second number: ')
try:
b = float(num1)
break
# In case the user enters something other than a number.
except ValueError:
print('\nThat is not a number!')

print(f'\nThe sum is: {a + b}\n')

# Exit if the choice is 2
elif choice == '2':
break

# In case the user enters something other than 1 or 2.
else:
print('Please enter 1 or 2.')

We can see the advantage of using break in this context. While it may not be used in very many situations, if you are trying to optimize the control flow of a program that involves user-interface, this trick can definitely come in handy.

Continue

I saved this one for last because it is arguably the most confusing of the three, although it also very unlikely you will need to use it very often, if at all. It is similar to break in the sense that it is always used inside a loop, but instead of exiting the loop entirely, continue indicates that you want to end one iteration only. In other words, any code inside your loop that comes after the continue will be ignored, and the loop will immediately start a new iteration. This means that the loop will still “continue” until the last iteration.

To demonstrate this, let’s say I have a list of names in a list, but there are some items in the list that are missing. For each of these missing items, there is a None in the place where a name should be.

names = ['Josh', None, 'Mary', 'Steve']

I want to print out each name, but ignore the missing items instead of printing them. I could use continue to do this.

for name in names:
if name == None:
continue
print(name)

This way, you can skip the print line for any iteration where a None appears and still make it all the way through the loop without stopping. The result will look like this:

Josh
Mary
Steve

There’s a good chance you will never have to use this, but it’s good to know and have in your arsenal just in case.

When Not to Use Pass, Break, and Continue

Before I close, I want to stress that while it may be tempting to use these tools all over your code now that you have learned how they work, you should not do this if you can help it. A general rule of thumb for Python which is widely agreed upon by experienced programmers is that whenever you are thinking about using pass, break, or continue, if you can find another way to accomplish the same task without it (and you almost always can) you should go that route instead. It is pretty much always going to be the better option.

Many programmers would even so far as to say that these tools should never be used. They consider it lazy and not Pythonic, and argue that it makes for code that is harder to follow and will break easily. I personally think there are some special use cases, most of which I have mentioned above, in which they can be the right way to go, although they are few and far between. In general, pass, break, andcontinue should be avoided whenever possible.

To demonstrate this point, let’s revisit the example above:

if type(x) != int:
pass
elif x < 2:
print('Less than 2')
elif x < 7:
pass
else:
print('Greater than 6')

We really don’t need to use pass here. We could just do this:

if type(x) == int and x < 2:
print('Less than 2')
elif x > 6:
print('Greater than 6')

Isn’t that much simpler? This accomplishes the same thing as the original version in a much more concise way, and we didn’t need to use pass at all! Here’s another example. Remember this example from above?

names = ['Josh', None, 'Mary', 'Steve']for name in names:
if name == None:
continue
print(name)

Well… why not do this instead?

names = ['Josh', None, 'Mary', 'Steve']for name in names:
if name != None:
print(name)

Again, there was no need to use continue here. As you can see, there really are very few situations where you would truly need to use these tools, so remember, the simplest solution is always the best!

--

--