Tutorial - Python 3 basics
Break, continue, pass statements
Posted October 4, 2018 by Rokas Balsys
Loop control statements change execution from its normal loop sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports break, continue and pass control statements, using them we can leave loop, go back to beginning of the loop or skip certain code.
Break statement terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C language.
The most common use for break is when some external condition is triggered requiring to exit from a certain loop. The break statement can be used in both while and for loops. If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.
for letter in "Python": if letter == 'o': break print ('Current Letter :', letter)
In a print Shell this will print only "Pyth" word, with each letter in new lines.
Continue statement returns cursor to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
for letter in "Python": if letter == 'o': continue print ("Current Letter :", letter)
In a print Shell this will print only "Pythn" word, with each letter in a new line and will skip "o" letter in whole word.
Pass statement is used when a statement is required but you don't want any command or code to execute at that moment.
The pass statement is a null operation; nothing happens when it executes.
The pass is mostly useful in places where your code will eventually go and do something, but has not been written yet.
for letter in 'Python': if letter == "o": pass print ("This is pass statement line") print ("Current Letter :", letter)
In a print Shell this will print "Python" word, with each letter in a new line and after "h" letter it will print "This is pass statement line". Usually if we are using if statement, we must add something, what our statement will do, but sometimes we don't know what our code will do there yet, in this case we can add pass statement.
In this tutorial we covered when we use break, continue and pass statements. Now you can move to next tutorial: