Search⌘ K
AI Features

Introduction to Decision Control Instructions

Explore how to control program flow using decision control instructions in Python. Understand how to use if, else, and elif blocks effectively with proper indentation to make decisions within your code.

We'll cover the following...

So far, statements in all of our programs have been executed sequentially. The sequence of executing instructions in a program can be altered using:

  • Decision control instruction
  • Repetition control instruction

What is a decision control instruction?

A decision control instruction is described using a flow chart in the figure below.

A flowchart describing the decision control instruction
A flowchart describing the decision control instruction

There are three ways to make decisions in a program:

  • In the first form shown below, else and elif are optional.
Python 3.8
# First form
a = 5
condition = a > 0
if condition :
print(condition)
  • In the second form, if the condition is True, all statements in the if block get executed. If the condition is False, the statements in the else block get executed.
Python 3.8
# Second form
a = 5
condition = a < 0
if condition :
print(condition)
else :
print(condition)
  • In the third form, if a condition fails, the condition in the following elif block is checked. The else block goes to work if all conditions fail.
Python 3.8
# Third form
a = 5
condition1 = a < 0
condition2 = a == 0
if condition1 :
print(condition1)
elif condition2 :
print(condition2)
else :
print(condition1)
print(condition2)

The colon : after if, else, and elif is compulsory. Statements in the if block, else block, and elif block have to be indented. Indented statements are treated as a block of statements.

Note: Indentation is used to group statements together. Use either four spaces or a tab for indentation. Don’t mix tabs and spaces. They may appear okay on screen but would be reported as errors.

The if-else statements can be nested. Nesting can be as deep as the program logic demands.