What is the Control structures in Python
Control structures in Python allow you to control the flow of your program execution. They determine the order in which statements are executed based on conditions and loops. The primary control structures in Python are:
Selection
- This is used to execute a block of code only if a specified condition is true.
- There are 2 Selections
2. Repetition / Iteration / Loop
- In programming, repetition refers to the concept of running a certain block of code or set of instructions more than once.
- It is a basic control structure used to automate no of tasks that need to be performed iteratively or repeatedly.
- Repetition allows you to avoid writing the same code over and over again. So that it is essential for handling various data processing.
- Repetition in programming is typically implemented using loops with conditional statements, depending on the task to achieve.
2 common types of Repetition
- Counter Controlled Iteration
- Logic Controlled Iteration
Counter Controlled Iteration
- Counter controlled iteration, is a type of loop where the number of iterations are known.
- Typically, a counter variable is used to keep track of the current iteration, and the loop continues as long as the counter meets end.
- Example: To print 1 to 10 numbers, this has a counter 1-10
- This type of iteration is often implemented using For loop in Python.
Logic Controlled Iteration
- Logic controlled iteration is a type of loop where the number of iterations are known, the loop continues as long as a specific condition or set of conditions is true, that means until termination condition will meet.
- This type of iteration is often implemented using While loop in Python.
2 primary types of loops used for repetition are:
- for loop
- while loop
- There is no repeat .. until loop in python. But it can be implemented using while loop
Advantages of Control structures in Python
- Flow Control
- Using Control structures can manage the flow of the program, determining which statements are executed under specific conditions.
- Conditional Execution
- Conditional statements are essential for making decisions in your program, allowing it to adapt and respond to different situations.
- Repetition
- Loops (for and while) let you execute the same block of code multiple times.
- Code Organization
- Control structures increase the readability of the code. They make it easier to understand the logical structure of the program and break it into smaller, more manageable parts.
- Modularity
- Control structures makes your code easier to maintain and reuse.