Data Science Interview Machine Learning Python

Decision Statements in Python

Sometimes you need to take some decision in programming. You need to test some condition: true or false. In Python there are various types of statements for this. Some of them are given below.

  • If Statement
  • If Else statement
  • Nested If statements
  • If-elif ladder.

If Statement

Syntax

if condition:
         #some statement here if condition is true


Example

i=10
if (i==10):
    print("value of i is 10")

Output

value of i is 10

If Else Statement

The Java if-else decision statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.

Flow Chart

Syntax

if condition:
       #some statement if true
else:
       #some statement if false

Example

i=11
if(i<10):
    print("i is smaller than 10")
else:
    print("i is greater than 10")

Output

i is greater than 10

The block of code following the else statement is executed as the condition present in the if statement is false after call the statement which is not in block(without spaces).

Nested If Else Statements

A nested if is an if statement that is the target of another if statement. Nested if statements means an if statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement

Syntax

if condition:   
     //code to be executed    
          if condition:  
             //code to be executed    
        

Example

i=10
if(i==10):
    if(i<15):
        print("i is smaller than 15")
    else:
        print("i is greater than 15")

Output

i is smaller than 15

If Else Ladder( If Elif)

The if-else-if ladder statement executes one condition from multiple statements.

Syntax

if condition1:  
//execute the statement if condition1 is true  

elif condition2:  
//execute the statement if condition2 is true  

elif condition3:  
//execute the statement if condition3 is true  

..
else:  
// execute the statement if all the conditions are false  

Flowchart

Example

i = 20
if (i == 10): 
    print ("i is 10") 
elif (i == 15): 
    print ("i is 15") 
elif (i == 20): 
    print ("i is 20") 
else: 
    print ("i is not present") 

Output

i is 20

To read more about Programming click here

Leave a Reply

%d bloggers like this: