Decision Control

Decision control is managed via if else structure like in other languages. We don't use parenthesis in block structure, rather it is done with the help of identation block. 

Example :- 
    #conditional statement
    a = 10
    if a> 10:
        print("Number is greater than 10")
        print("This will not execute")
    else:
        print("Less than or equal to")
        print("This will continue")

We can group elements of same block with required indentation. 

The structure of if-else is similar to C,C++ but varies in terms of below

i) Parenthesis is not mandatory
ii) statement ends with label : 
iii) Identation required. 

Let say we want to introduce one more condition, then it can be rewritten like 

a = 0
if a> 10:
            print("Number is greater than 10")
            print("This will not execute")
else:
    if a ==0 :
            print("value is 0")
    else:
            print("Less than or equal to")
            print("This will continue")

Suppose, we need to include multiple checks, so in that case multiple if else condition has to be introduced in else block. This would result readability issues. So in order to better this, new alternative elif is introduced in python. 

a = 0
if a> 10:
            print("Number is greater than 10")
            print("This will not execute")
elif a ==0 :
            print("value is 0")
else:
            print("Less than or equal to")
            print("This will continue")


This looks efficient in terms of readability and maintainability. 

#single line if else like conditional operator
a = 9
print("Number is greater than 10") if a> 10 else  
print("Less than or equal to 10")

Single line if else result expression which can be assigned to a variable. Like below.  

a,b = 10,20
if a > b:
    c = a
else:
    c = b
   
#same code using single if else

c = a if a>b else b

print(c)


Comments