Prediction of conditions in a program and specifying actions to be taken for each condition is called decision making.Python evaluates expressions that give True or False as output.
For example, if your score in Mathematics exam is above 90, then your grade is A. If your score is greater than 80 and less than 90, then your grade is B. Similarly you have grades C,D,E and if you get a score less than 40 you get F grade.Here we are checking for conditions and comparing the score obtained with 90,80,70 etc and assigning a particular grade to the student .
Three decision making statements in Python are:
- if statement
- if else statements
- if-elif-else statements
- Nested if statements
After any decision making clause like if or else or elif there is a “:” symbol and it is followed by statements that are intended.All the statements(block) under the if or else or elif must follow same spacing.
if statement consists of a boolean expression followed by one or more statements to be executed. So if the expression returns True, the statements within the if are executed. It evaluates only one boolean expression.Else if the expression returns False, control skips and moves to next line.The boolean expression can also check for 2 logical conditions.For example : if((a>10)and(a<15)):
In the above example, a is given the value 10. Then a is checked for equality with 5. “a==5” is a boolean expression which in this case will give False as 10 is not equal to 5. The number a is not printed as the condition was not satisfied.
Later a is assigned the value of 5. Then when a is checked for equality with 5, “a==5” boolean expression gives True in this case.The number a is printed in this case as the condition of equality is satisfied.
It also evaluates a boolean expression.The if statement is followed by the else statement. When the boolean expression evaluates to True,the if statement gets executed.When the boolean expression evaluates to False, the else statement gets executed.
Here a is given the value of 5. When a is checked for equality with 5, the expression is True.It prints a and prints “hi i am 5”. The else statement does not get executed.Now if a is not 5, if statement will not be executed. Instead the else statement gets executed. One of them will get executed.So there are only 2 possibilities.
This is called if-elif-else ladder.It is used when there are multiple conditions to be checked.As soon as one of the conditions is satisfied, the rest of the ladder is skipped.
elif is nothing but else if.
Let us use the grade example that we had used earlier.
My score is 87. So it fails the first if condition as it is not greater than 90.The next condition is satisfied as 87 is greater than 80.Now it prints “B grade” and it ignores the rest of the ladder.
Nested if statements
Nested if statements are nothing but if statements within another if statement.
Image courtesy : Google Images.