Python Tutorial 4-If Then Else in Python

Conditional statement is most sought after situation in programming. There are many rules and operators get used while using IF THEN ELSE in python. These statement get used when programmer some output based on certain condition or want to perform any function or activity upon any conditional event. Before starting example, we will see some of very frequent operator that will be used further

Relational Operators



Examples:

We want to calculate the interest amount in three different ways and will print the result if method generating the equal value of different value. Given

P = 1,000 
R=5
T=2

X=(P*R*T/100) # First method 
Y=(P*R*T)/100 # second method
Z=(P/100)*R*T # third method

if X==Y:
print("X & Y are equal")
if Y==Z:
print("y &z are equal")
if Y==Z:
print("y &z are equal")
if X==Y==Z:
print("X ,Y & Z are equal")

Here * represent multiplication sign and == represent to logical equal sign. We have to remember that = sign the assign the values to a variable and == is a logical operator.

Now in above example we have seen that we have used multiple if statement instead of using ELSE with IF.  In above example, we will print output after each if command however if we use ELSE statement with IF then we will only get the output where condition will be true. Please see below example :

if X==Y:
print("X & Y are equal")
elif Y==Z:
print("y &z are equal")
elif Y==Z:
print("y &z are equal")
else X==Y==Z:
print("X ,Y & Z are equal")

In above example, output will  be generated only once. ELIF in above example represent else if statement.

Now , we will see another example .

One person want to know if given year is leap year or not. So there is one formula to know if given year is leap year or not. We have to divide the year by 4 and if there will be no remainder then year will be leap year else not. So programmer may write the program in below way

year=2018
if year%4==0:
print(" Year %s is leap year " % (year))
else:
print(" Year %s is not leap year " % (year))

Hope above example will help reader to understand the usage of IF-THEN-ELSE  in python. Readers are requested to keep watching our blogs for free tutorials for python . We also provide full time Data Science Training in Delhi, Python Training in Delhi, Machine learning in Delhi . We are best Data Science Training Institute in Delhi and have best Data Scientist to provide classroom training in Delhi. Please write to us if you are looking for classroom training for Data Science in Delhi.

LEAVE A COMMENT

Code Calibre