Nested IF statements in Python

In many cases we need want to add additional conditions to an existing condition to make or validate the condition as true. To resolve this situation we can use nested IF conditions in Python.

In nested IF statements we can have IF , ELIF , ELSE construct within a IF , ELIF , ELSE statement.

 

For example:

The below code checks date as of today and print the value.

 

>>> import datetime as d
date1 =d.datetime.today().strftime("%d-%m-%y")
>>> print date1
01-12-15

 

From the above code we can see that the date1 variable prints today’s date . Now let us compare it date1 variable with another variable having future date i.e. “02-12-15”.

 

import datetime as d
date1 =d.datetime.today().strftime("%d-%m-%y")
date2='02-12-15'
if date1==date2:
    print 'Matched dates'
    print 'date1 i.e.' +date1 +'is equal to date2 i.e.'+ date2 
else:
    print 'Not matched'
    print 'date1 i.e.' +date1 + ' is not equal to date2 i.e.'+ date2 

 

Result of the above script is as below:

>>> ================================ RESTART ================================
>>> 
Not matched
date1 i.e.01-12-15 is not equal to date2 i.e.02-12-15

 

So now we came to know by comparing the both dates are not matched and display some custom message, now let us add one more condition by saying if the date1 is less than date2 then display the below message :

“Second date  is greater than first date”

So here is the example on how to use nested IF statements in Python:

import datetime as d
date1 =d.datetime.today().strftime("%d-%m-%y")
date2='02-12-15'
if date1<>date2:
    print 'Not matched'
    print 'date1 i.e.' +date1 + ' is not equal to date2 i.e.'+ date2
    if date1 > date2:
        print "First date  is greater than Seocnd date"
    else:
        print "Second date  is greater than first date"

elif date1==date2:
    print 'Matched dates'
    print 'date1 i.e.' +date1 +'is equal to date2 i.e.'+ date2
else :
    print "Dont know what happened"

 

Output of the above code will print as below:

>>> 
Not matched
date1 i.e.01-12-15 is not equal to date2 i.e.02-12-15
Second date  is greater than first date
>>> 

image

From the above code we see that how we added an additional condition to the existing comparison or we can say existing condition.

 

Thank you for reading my blog . Please feel free to leave me some feedback or to suggest any future topics.

Looking forward to hear from you – Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s