Control structures are used in programming to control the flow of execution of a program. In Python, the following control structures are commonly used:
- FOR loop: used to iterate over a sequence (like a list, tuple, or string) and execute a block of code for each element. For example:
In this example, the variable “element” takes on the value of each item in the list [1, 2, 3] one at a time, and the code block inside the “for” loop is executed once for each item.
- IF statement: used to check a condition and execute a block of code if the condition is true. For example:
- WHILE loop: used to repeatedly execute a block of code as long as a certain condition is true. For example:
In this example, the code block inside the “while” loop is executed repeatedly as long as the condition “x > 0” is true. The variable “x” is decremented by 1 at the end of each iteration to eventually make the condition false and exit the loop.
- TRY-EXCEPT statement: used to handle errors that may occur during the execution of a program. For example:
- FUNCTION: used to define a block of code that can be reused throughout the program. For example:
- PASS statement: it is a null statement, it is used as a placeholder where a statement is required syntactically, but no code needs to be executed. For example:
- CONTINUE statement: The continue statement is used to skip the current iteration of a loop and continue with the next iteration. It is used inside a loop (for or while) to skip the current iteration and move on to the next one.
For example, consider the following for loop that iterates over a range of numbers from 0 to 9:
In this example, the if statement checks if the current value of i is even (i.e. if i is divisible by 2). If it is even, the continue statement is executed, which skips the current iteration and continues with the next one. As a result, only the odd numbers from the range (1, 3, 5, 7, 9) are printed.
Another example would be to use continue in a while loop:
Note that the continue statement is different from the break statement, which is used to exit a loop entirely.
In summary, continue statement is used inside a loop to skip the current iteration and move on to the next one. It allows you to control the flow of the loop based on certain conditions, enabling you to selectively execute or skip certain iterations of the loop.
- BREAK statement: it is used to exit the current loop and continue with the next statement after the loop. For example: