Learn Python Tutorial - Decisions

Python Basics

(Learn Python Programming in 20 Minutes)


3 Python commands

 3.6 Decisions

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
else: 
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 executed. In either case execution continues with the statement after the if-else. For example, the code

x = 1 
if x > 0: 
   print "Friday is wonderful" 
else: 
    print "Monday sucks" 
print "Have a good weekend"

results in the output

Friday is wonderful 
Have a good weekend

Note that the last print statement is not part of the if-else statement (because it isn’t indented), so if we change therst line to say x = 0 then the output would be

Monday sucks 
Have a good weekend
 
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.






 

 

No comments:

Post a Comment

Your feedback is highly appreciated and will help us to improve our content.