Skip to main content

Decisions in python

Decisions by python 




The if–else is used to make choices in Python code. This is a compound statement. The simplest
form is
if c o n d i t i o n :
a c t i o n −1
13else :
a c t i o n −2
The indentation is required. Note that the else and its action are optional. The actions action-1
and action-2 may consist of many statements; they must all be indented the same amount. The
condition is an expression which evaluates to True or False.
Of course, if the condition evaluates to True then action-1 is executed, otherwise action-2 is exe-
cuted. In either case execution continues with the statement after the if-else. For example, the
code
x = 1
if x > 0:
print " Friday is w o n d e r f u l"
else :
print " Monday sucks "
print " Have a good w e e k e n d"
results in the output
Friday is w o n d e r f u l
Have a good w e e k e n d
Note that the last print statement is not part of the if-else statement (because it isn’t indented),
so if we change the first line to say x = 0 then the output would be
Monday sucks
Have a good w e e k e n d
More complex decisions may have several alternatives depending on several conditions. For these
the elif is used. It means “else if” and one can have any number of elif clauses between the if
and the else. The usage of elif is best illustrated by an example:
if x >= 0 and x < 10:
digits = 1
elif x >= 10 and x < 100:
digits = 2
elif x >= 100 and x < 1000:
digits = 3
elif x >= 1000 and x < 10000:
digits = 4
else :
digits = 0 # more than 4
In the above, the number of digits in x is computed, so long as the number is 4 or less. If x is
negative or greater than 10000, then digits will be set to zero.

Comments