When writing a computer program, we often want it to execute different actions for different scenarios and conditions.
This is where the
if-else statement is used.
if-else is a conditional statement where
if the condition evaluates to true, then a certain part of the code is executed,
else an alternative path is taken.
else keyword catches anything which isn’t caught by the preceding if conditions.
The following is the syntax for an
Let’s start by taking a look at an example which checks if a variable
a is greater than or less than
#change the value of "a" so it's less than b in order to execute the else statement a = 50 b = 20 if (a > b): #this code is executed only if a is greater than b print "a is greater than b"; else: #this code is executed if the preceding "if" condition evaluates to false print "a is less than b";
The figure below illustrates the working of the above code using a flow chart:
View all Courses