Join our community of software engineering leaders and aspirational developers. Always
stay in-the-know by getting the most important news and exclusive content delivered
fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter
in the past. Click the button below to open the re-subscribe form
in a new tab. When you're done, simply close that tab and continue
with this form to complete your subscription.
The New Stack does not sell your information or share it with
unaffiliated third parties. By continuing, you agree to our
Terms of Use and
Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!
We’re so glad you’re here. You can expect all the best TNS content to arrive
Monday through Friday to keep you on top of the news and at the top of your game.
What’s next?
Check your inbox for a confirmation email where you can adjust your preferences
and even join additional groups.
Follow TNS on your favorite social media networks.
Loops are an integral part of your Python code, without which you’d struggle to do anything effectively (or without having to use far too much code for the purpose). With loops, you can create automated tasks that repeat actions until a particular condition is met. You can use for loops to iterate over a sequence of items and while loops to continue executing statements as long as a condition is true.
But you might find there are times when you need to exit the loop, skip an iteration, or ignore a condition. For example, you might create a loop that executes a statement until a condition is met but you need to break out of the loop if a different condition occurs.
Here’s a simple example:
You create a for loop to print out “Hello, New Stack!” but you want to break out of the loop if it discovers the S character. That’s very simple and doesn’t really have much in the way of real-world application, but it makes for a good demonstration.
Let’s create that bit of code.
We’ll start by defining our text like this:
t = 'Hello, New Stack!'
Then we create a for loop that iterates through the string and includes a break statement to catch the S character. That loop looks like this:
for letter in t:
print(letter)
if letter == 'S':
break
print("For Loop Broken")
print()
The entire code block looks like this:
t = 'Hello, New Stack!'
for letter in t:
print(letter)
if letter == 'S':
break
print("For Loop Broken")
print()
If you run the above code, the output would look like this:
Hello,New SFor Loop Broken
As you can see, as soon as the for loop hits S, it breaks the loop. We can also do this with a while loop, like so:
t = 'Hello, New Stack!'
i = 0
while True:
print(t[i])
if t[i] == 'S':
break
i += 1
print("While Loop Broken")
Run the above code and you’ll get the same output you did with the for loop.
Another form of loop control is the continue statement which is used to skip the execution of the statement block and returns control to the beginning of the loop to start the next iteration. In other words, the remaining statements in the loop will be skipped for the current iteration and the loop will begin the next iteration.
Remember, back with our break statement, when the loop reached the letter S, it broke such that everything past that character was ignored. With the continue statement, the loop reaches the S and immediately returns and iterates again, so it can print out the remaining characters. The code for this might look something like this:
for letter in 'New Stack':
if letter == 'S':
continue
print ('Current Letter :', letter)
If you were to run the above, the output would be:
Current Letter = NCurrent Letter = eCurrent Letter = wCurrent Letter =Current Letter = tCurrent Letter = aCurrent Letter = cCurrent Letter = k
As you can see, our loop skips S but continues to iterate so the entire string (minus the S) is printed.
We can do this with a while loop as well. This time it will count backwards from 10 to 0 but skip 7. That code looks like this:
var = 11
while var > 0:
var = var -1
if var == 7:
continue
print ('Current Value :', var)
Run the above and you get:
Current Value : 10Current Value : 9Current Value : 8Current Value : 6Current Value : 5Current Value : 4Current Value : 3Current Value : 2Current Value : 1Current Value : 0
Another loop control is the pass statement, which acts as a sort of a null operation. When using a pass loop control, no code is executed. This can come in handy when you want to write empty loops (which can be used as a placeholder for code you plan on writing later or when you want to consume an iterator).
Let’s create a block of code that prints out New Stack but also includes a for loop and a function definition, both of which do nothing and use the pass statement. That code might look something like this:
s = "New Stack"
for i in s:
pass
def fun():
pass
fun()
for i in s:
if i == 'S':
print('Pass Statement Used')
pass
print(i)
If you were to run the above code, the output would be:
N
e
w
Pass Statement Used
S
t
a
c
k
As you can see, both our initial for loop and our function are both skipped because they include the pass statement.
And that’s how you use the break, continue, and pass loop controls in Python. With the help of these three statements, you can more effectively and efficiently use loops. As you gain more experience with the language, you’ll come to appreciate these three loop control statements.