Branching programs allow us to make choices and do different things. Let’s have look at the following flow diagram.
Observing the flow diagram:
- A test (expression that evaluates to
True
orFalse
) - A block of code to execute
- If the test is
True
- An optional block of code to execute if the test is
False
Table of Contents
- A simple example of
if
andelse
in Python: - Nested
if
,else
andelif
in Python: - Compound conditions inside
if
Such a desire can be achieved using if else
clauses in Python.
A simple example of if
and else
in Python:
Analysis of the above code:
- The expression
x%2 == 0
evaluates toTrue
when the remainder ofx
divided by2
is0
- Note that
==
is used for comparison, since=
is reserved for assignment - The indentation is important! Each indented set of expressions denotes a block of instructions
- For example, if the last statement were indented, it would be executed as part of the
else
block of code
- For example, if the last statement were indented, it would be executed as part of the
- Note how this indentation provides a visual structure that reflects the semantic structure of the program
Nested if
, else
and elif
in Python:
An example program to check if a number if divisible by 2 and/or 3.
Analysis of the above code:
- Notice the
if else
block inside the firstif
block. This is called nesting. - We have an
elif
block, this is executed when the code does not flow throughif
.elif
is, as you might have guessed, just a short form for ‘else if’. - The last
else
block is executed with the code does not flow through either ofif
orelif
Compound conditions inside if
Let’s consider a program to find the minimum of three integers.
Analysis of the above code:
- The first statement itself is a mess here, what is does is, reads a string from input and tries to split them by space and then convert each of the parts into an integer type. If the conversion of all of them is successful, it assigns each of them to
x
,y
, andz
respectively. - We check for two conditions in the
if
clause, and then print a human readable string by joining several strings and numbers. Sincex
,y
, andz
were integers, we first need to convert them intostr
objects to be able to join them elif
andelse
are quite understandable
Next, we will discuss how to perform repetitive tasks by creating a loop in Python.
Note: This is a part of what I learned in an online Open Course Ware offered by MIT on edX. Its for my personal reference & also for those who would like to revisit the course.