Python is an object-oriented programming language ideally designed for rapid prototyping of complex applications. Like Perl, Python source code is also available under the GNU General Public License (GPL).

In this article we will see how to use, simple if-else, if-else-if (elif) and nested if-else in python with example.

1) Simple if-else in python

The code within every if-else starts with a colon (:) and should be indented (space):
con = 1;
if(con==1):
	print 'con is 1'
else:
	print 'con is not 1'

Output: Output will be something like this:

con is 1


2) Simple if-else-if in python (elif)

The code within every if-else-if starts with a colon (:) and should be indented (space), else-if condition is defined by keyword 'elif' in python:
con = 3;
if(con==1):
	print 'con is 1'
elif(con==2):
	print 'con is 2'
else:
	print 'con is neither 1 nor 2'

Output: Output will be something like this:

con is neither 1 nor 2


3) Nested if-else in python

The code within every if-else-if starts with a colon (:) and should be indented (space):
con = 3;
if(con>1):
	print 'con is greater than 1'
	if(con==3):
		print 'con is 3'
else:
	print 'con is neither 1 nor 2'

Output: Output will be something like this:

con is greater than 1
con is 3


In this article we have seen, how to use, simple if-else, if-else-if (elif) and nested if-else in python. In upcoming articles we will see more complex usecases and tricks of python.
  • By Techburps.com
  • Sep 30, 2017
  • Python