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.
There are three ways to make decisions in a program:
- In the first form shown below,
elseandelifare optional.
- In the second form, if the condition is
True, all statements in theifblock get executed. If the condition isFalse, the statements in theelseblock get executed.
- In the third form, if a condition fails, the condition in the following
elifblock is checked. Theelseblock goes to work if all conditions fail.
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.