Conditional Statements in Python
The Extended Form of IF
The solution to the problem on
[
page 1]
had a small inconvenience. When reading an integer in
n, we essentially have
three cases:
•
n is less than 0 (n < 0)
•
n is equal to zero (n == 0)
•
n is greater than 0 (n > 0)
Therefore, we can use the extended form of the
if statement:
Step 1. The
logical_expression is evaluated.
Step 2. If the logical expression evaluates to
True, then
set_of_instructions_1 is executed.
Otherwise, if the value is
False, the condition in the
elif block is tested.
If
other_logical_expression is true,
then
set_of_instructions_2 is executed,
otherwise
set_of_instructions_3 is executed.
LET'S FULLY SOLVE THE PROBLEM
Analyze and run the program below:
NOTES
So, we had
three cases, and the
if statement helped us perfectly to solve the problem completely!
It is important to note that you can add
as many elif clauses as you need in your code. In some situations,
there may be
a crossroads with more than 3 alternatives...
Proceed to the next page.