Thursday, January 30, 2020

Branching statements(if else elif)

Branching Statements(conditionals) in Python


Like other programming languages branching statements are also available in Python. In python, we have if, if-else, and if-elif-else statements. Your program can execute different branching actions based on Boolean conditions (True or False). Else-if is not used in Python, instead, elif is available.

if-statement

If else statement is used to execute a block of code only if a test condition is fulfilled, Otherwise this block of code will be bypassed untouched.

The Syntax for if-statement is,

if conditionExpression:           
   #  Code to execute if
   #  conditionExpression is true


For example,

i = 70
if (i > 50): 
   print ("70 is less than 50") 
print ("I am Not part of if-statement") 

if-else-statement


If else statement has two blocks of code as options to execute, one of which is executed if the test expression is fulfilled, and the other is executed if the test expression is failed. 

The syntax for the if-else statement is,

if (conditionExpression):
    # Executes this block of code if
    # if conditionExpression is true
else:
    # Executes this block of code if
    # if conditionExpression is false


For example,

i = 50; 
if (i < 20): 
    print ("i is smaller than 20") 
    print ("This is if Block") 
else: 
    print ("i is greater than 20") 
    print ("This else Block") 
print ("This is outside the if-else statement")

if-elif-else statement



An if-elif-else statement is something like if-else if-else ladder in other programming languages. When the user has multiple test expressions associated with multiple blocks of code to execute, then this statement can be applied.

The syntax for if-elif-else is,

if (Test Expression 1):
    statement
elif (Test Expression 2):
    statement
.
.
else:
    statement



For example, 

i = 2
if (i == 1): 
    print ("RED") 
elif (i == 2): 
    print ("BLUE") 
elif (i == 3): 
    print ("GREEN") 
else: 
    print ("YELLOW")


Example:



num=3
if num%2==1:    #if example
 print('odd')
 
if num%2==0:    #if-else example
  print('even')
else:
  print('odd')
  
if num==1:    #if-elif-else example
  print('good')
elif num==2:
  print('very good')
elif num==3:
  print('best')
else:
  print('best')