In general, in any programming language statements are executed sequentially. The first statement in our code is executed first, followed by the second statement, and so on. There may be a situation when you need to execute a block of code several numbers of times. Putting that block of code in loop helps to execute that code repeatedly until the condition for the loop is true.
It saves a tremendous amount of code since we do not have to write that code again and again. So to sum up a loop statement allows us to execute a statement or group of statements multiple times. Now Python programming language allows the following types of loops to handle this situation.
- For Loop – for loop is used when it is known beforehand how many times the statements or a block of code has to be repeated in a loop
- While Loop – while loop is used when it is not known before- hand the number of times the statements needs to be repeated in a loop. It will repeat until unless the condition of the loop is true.
Apart of from using for and while loop once, we can put one loop inside another loop this procedure is called nested looping. Nested looping helps to repeat a particular cycle of codes.
In any programming language control statements are used to change the control from the loop. We can change the execution from its normal sequence to either leave the loop or start the iteration again. When the scope of the loop ends the object created within the scope will automatically be destroyed. Python programming language supports the following control statements.
- Break statement
- Continue statement
- Pass statement
The break statement is used to terminate the loop statement and transfer the execution to the next statement immediately after the loop. The break statement is useful in situations when a particular condition is met then instead of continuing the loop we break out of the iteration and execute the code right after the loop statement. It saves unnecessary execution time and memory space in running the loop if it is not required. The syntax is simple, use the keyword break.
Continue statement is used in the situation where we want to skip the remainders of the loop body once the keyword continue is encountered. After that, the condition of the loop is checked again if the condition is true then the loop is reiterated.
The pass statement in Python programming is used when a statement is required for syntactical purpose but you do not want any code to be executed. It is a type of null operation where nothing happens when the pass is executed. The syntax is simple just use the keyword pass after a function or a loop construct.