Loop control statements change execution from their 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 the loop, go back to the 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 a break is when some external condition is triggered requiring to exit from a certain loop. The
break statement can be used in both
for loops. If you are using nested loops, the
break statement stops the execution of the innermost loop and starts 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 the "Pyth" word, with each letter in new lines.
Continue statement returns the 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
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 the "o" letter in the 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 the "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 an 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 a pass statement.
In this tutorial, we covered when we use a break, continue and pass statements