Python: Control Structure

In Python, The commonly used control structures are:

Selection Statements

During the execution of the program, we may not wish to execute all sets of statements sequentially. Sometimes we may wish to select between the set of statements based on some conditions. Based on the test condition evaluation, the flow is determined inside the program. Here is the list of selection statements in Python:

  • If statement: It is a conditional statement used for decision making in python. Example
  • else if statement: It is a conditional statement if block condition is false then execute the else block. Example
  • else if ladder statement: These are multiple else if statement in sequence if one condition not match then go next else for condition check .Example
  • Nested if statement: You can write if block with in another if block that is called nested if. Example

The example of if, else, elif and nested if will discuss in further blogs in more detail.

Looping Statements

Looping statements are used to execute the same block of code multiple times in python based on the test condition. Here is the list of looping statements in python.

  • while loop: The while loop is used to execute a piece of code as long as the test condition is true. While loop is preferred whenever the number of iterations is not known. Example
  • for loop: In python, for loop allows the loop to run over a specific sequence of values. In other words, for every value in the sequence, the loop runs once. Thus we can avoid infinite loops by using a for loop. Example
  • Nested loops: Loop with in another loop is called as nested loop. Example

The example of while loop, for loop and nested loop will discuss in further blogs in more detail.

Loop Control Statements

The flow inside looping statements are controlled using the looping control statements like pass, break and continue.

  • break: When we want to stop a loop or break away from it we can use the break statement. Example
  • continue: When we want to skip the remaining portion of loop statements and continue with the next iteration, we can use the continue statement. Example
  • pass : pass is a null statement that is used to do create empty blocks. When the pass is executed, it results in no operation and the control will move to the next statement applicable. Example

The example of the break, continue, and pass will discuss in further blogs in more detail.