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.
The else keyword catches anything which isn’t caught by the preceding if conditions.
The following is the syntax for an if-else statement.
Let’s start by taking a look at an example which checks if a variable a is greater than or less than b:
#change the value of "a" so it's less than b in order to execute the else statementa = 50b = 20if (a > b):#this code is executed only if a is greater than bprint "a is greater than b";else:#this code is executed if the preceding "if" condition evaluates to falseprint "a is less than b";
The figure below illustrates the working of the above code using a flow chart:
Free Resources