Topic 6: Selection Structure

If Statements

Selection structure is used when a decision has to be made, based on some condition, before selecting an instruction to execute. The condition tested in the selection structure must be a Boolean expression (evaluating to true or false). The Boolean expression can contain variables, constants, arithmetic operators, comparison operators, and logical operators.

Types of selection structure:

  • Single-alternative selection structure: A set of instructions is executed only if the condition evaluates to true
  • Dual-alternative selection structure: Executes different sets of instructions based on whether the condition evaluates to true or false
Syntax:
  1. if condition:
  2. one or more statements (true path)
  3. [else:
  4. one or more statements (false path)]
  • The else portion in brackets is optional, executed only if the condition is false. It is only used for dual-alternative selection structures
  • Indentation is important

Example 1: one statement in only true path
    1. if value == 5:
    2. x += value
Example 2: Multiple statements in the only true path
    1. if answer == 3:
    2. print(“congratulations”)
    3. score +=1
Example 3: one statement in each path
    1. if savings >= 15000:
    2. print(“buy a car”)
    3. else:
    4. print(“travel by bus”)
Example 4: multiple statements in the true path and one statement in the false path
    1. if x > 2:
    2. print(“yes”)
    3. x = 5
    4. else:
    5. print(“no”)
Example 5: multiple statements in both paths
    1. if grade >= 50:
    2. print( “congratulations you passed”)
    3. print(“you will receive a prize”)
    4. else:
    5. print(“sorry you failed”)
    6. print(“you will go on probations”)

The if-else Chain

if-else chain is a nested if statement occurring in the else clause of the outer if-else. If any condition is true, the corresponding statement is executed and the chain terminates. Final else is only executed if no conditions were true. It serves as a catch-all case. if-else chain provides one selection from many possible alternatives.

Syntax:
  1. if condition:
  2. statement(s)
  3. elif condition:
  4. statement(s)
  5. else:
  6. statement(s)
Example
    1. a = 200
    2. b = 33

    3. if b > a:
    4. print("b is greater than a")
    5. eif a == b:
    6. print("a and b are equal")
    7. else:
    8. print("a is greater than b")