if Condition in python

if_condition_in_python

Skill - ‘if’, ‘else’ and ‘elif’ statements in python

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


  • if condition runs a code only if the supplied expression evaluates to True. For Example
x = 5
# the print statement will execute since x is 5
if x==5:	
	print('The value of x is 5')

# the print statement will not execute since x is not 10
if x==10:
	print('The value of x is 10')
  • else can be used to execute when if condition is supplied with value that evaluates to false. For example
x=10
if x==5:	
	print('The value of x is 5')
else:
	print('The value of x is not 5')
  • elif keyword is used to implement else-if in python. For example
x = 9

if x==2:
	print('The value of x is 2')
elif x==3:
	print('The value of x is 3')
elif x==4:
	print('The value of x is 4')
elif (x>4) and (x<10):
	print('x is greater than 4 and less than 10')
else:
	print('x is greater than 10')
  • if, else, elif can be nested with in each of them to suit our requirements, for example
age = 28
country = 'India'

if country=='India':
	if age<=25:
		print('logic for country as India and age less than or equal to 25')
		print('Executing some application logic...')
	elif age<60:
		print('logic for country as India and age more than 25 and age less than 60')
		print('Executing some application logic...')
	else:
		print('logic for country as India and age greater than or equal to 60')
		print('Executing some application logic...')

Video

The video for this post can be seen here

Online Interpreter

You can run these codes online at https://www.programiz.com/python-programming/online-compiler/

Further Reading


Table of Contents

Comments