Control Structures in Python

Share

A program needs to be given direction. Otherwise it does not know where to flow. Control structured are blocks of programming that analyze variables and choose directions in which to go based on given parameters. The term flow control details the direction the program takes (which way program control “flows”). Hence it is the basic decision-making process in computing; flow control determines how a computer will respond when given certain conditions and parameters.

There are 3 main control structures used in programming:

  1. Sequence
  2. Selection
  3. Repetition

Sequence

If the steps from the beginning to the end of an algorithm are carried out in a strict order, it is called a sequence. There are no jumps or twists. Just one line being executed after another in order.

Real Life Examples:

  • Students progressing from 1st year to 4th year through 2nd year and 3rd year in the university.
  • Climbing up or down a staircase

Python Example:

In the following program, the steps execute from start to finish in order.

Control Structure: Sequence

Selection

Selection is a situation where steps are executed depending on whether a condition of an algorithm is satisfied. If the condition is satisfied (the answer to the question is true), one set of steps begins to execute. Otherwise, a different set of steps begin to execute.

Real Life Examples:

  • Buying something from a shop
    • If you have money more than or equal to the price:
      • You can buy the item
    • Otherwise
      • You cannot buy the item

Python Example:

There are 3 main instances where selections are used in python

  1. When there is only one selection to be made if a condition is trueControl Structures: Selections: IF
  2. When there is a choice between two options. One gets executed if the condition is true. The other gets executed if the condition is false.Control Structures: Selections: ELSE
  3. When there are multiple choices based on many conditionsControl Structures: Selections: ELIF

Repetition

A block of steps is executed repeatedly until a condition of satisfied. This is also called looping.

Real Life Examples:

  • Doing pushups
    • Do a push up
    • Repeat pushup until you are exhausted

Python Example:

There are two main repetition structures in Python:

  1. FOR loopControl Structures: Repetition: FOR
  2. WHILE loopControl Structures: Repetitions: WHILE