In one of the previous posts, we had explored the logical operators in Python. Logical operators alone cannot help much as they return only True
or False
. However, practically, logical operators are used in combination with conditional statements or looping statements. In this post, we would be exploring conditional statements in Python.
A note on indentation
Going forward from here, Python interprets the statements within a conditional statement, looping statement or a function based on indentation. Improper indentation may lead to syntax or logical errors. So, make sure to properly indent your code, indenting each and every line within a conditional, loop or function with the correct number of white spaces or tabs.
The if
Statement
The if
statement in Python evaluates a conditional expression and executes the statement within its body only if the conditional expression evaluates to True
. Given below is the syntax of the if
statement (Note the indentation of statements within if
):
statements_before_if
if conditional_expression: # Example 75>25
statements_within_if # Executed if the conditional_expression evaluates to True.
statements_after_if
Let’s take a simple program. A person can apply for a credit card with a certain bank if his annual income is above $50,000. A program which evaluates the eligibility and prints “You are eligible for credit card.” is as under:
income = int(input("Enter your annual income: "))
if income>50000:
print ("You are eligible for credit card.")
You can try the above snippet for yourself. (We have given the complete code and output at the end of this post).
The else
statement
But there is a problem with the above snippet. What if the person is ineligible for a credit card (i.e., his/her annual income is less than $50,000)? This is where the else
statement comes handy. The else
statement gets triggered when the conditional expression in the if
statement evaluates to False
.
Following is the syntax of the else
statement:
statements_before_ifelse
if conditional_expression: # Example: 75>25
statements_within_if # Executed if the conditional_expression evaluates to True.
else:
statements_within_else
statements_after_ifelse
So extending the above snippet to print output for ineligible persons would look like this:
income = int(input("Enter your annual income: "))
if income>50000:
print ("You are eligible for credit card.")
else:
print ("You are ineligible for credit card.")
The elif
statement
Congratulations on completing the credit card eligibility check program. But as soon as you complete this program, the bank official realizes that there are 2 variants of credit card, one named “Platinum” offered to those customers whose annual income exceeds $50,000 but is less than $150,000 and the other named “Gold” offered to customers having income above $150,000. Now you have to check exactly which credit card should the customer be offered.
Don’t worry, Python has got you covered! For situations like this, we have the elif
statement (or else-if in simple words) which unlike the else
statement allows you to check for another condition if the condition of the if
statement is not satisfied. You can use multiple elif
statements too one below the other.
Following is the syntax of the elif
statement:
statements_before_ifelifelse
if conditional_expression: # Example: 75>25
statements_within_if # Executed if the conditional_expression evaluates to True.
elif conditional_expression: # Example: 35<40
statements_within_elif
else:
statements_within_else
statements_after_ifelifelse
So our corrected program would look like this:
income = int(input("Enter your annual income: "))
if income>50000 and income<150000: # Note the use of and to check if both the conditions are true.
print ("You are eligible for Platinum credit card.")
elif income>150000:
print ("You are eligible for Gold credit card.")
else:
print ("You are ineligible for credit card.")
Nested if
statements
As you complete the above code, there is one more condition to be satisfied, the age of any credit card holder should be greater than or equal to 18 years. Since this condition is independent of the annual income condition and must be satisfied before even checking for income based eligibility, we can use nested if
here.
Nested if
means you could use if
statements within another if
statement for any number of times you like. Nested if
statements are no different than if
statements and hence, they can contain their own elif
and else
counterparts.
So on updating the previous snippet, the new code would look like this:
age = int(input("Enter your age: "))
if age>=18:
income = int(input("Enter your annual income: "))
if income>50000 and income<=150000:
print ("You are eligible for Platinum credit card.")
elif income>150000:
print ("You are eligible for Gold credit card.")
else:
print ("You are ineligible for credit card.")
else:
print ("You are ineligible for credit card due to age.")
The output of the above snippet would be as under:
Multiple if
statements
You can have multiple if
statements one after the other in a program. The difference between using if-elif-else block and multiple if block is that in the former, only one of the set of statements would get executed (i.e., either if
or one of the elif
statements or else
statement) as the control stops when either of the conditions are satisfied while in multiple if
statements, the control checks each and every if
statement.
Consider the following program:
a = 20
if a>10:
print ("More than 10")
if a>15:
print ("More than 15")
if a>20:
print ("More than 20")
The output of the given program is as under. You will notice that the first two if
statements have got executed. However, if the same had been written in an if-elif-else
format, only the first if
statement would have been executed.
Examples
Let’s go through some example snippets below based on conditionals.
Write code to calculate the net payable amount by the customer based on the following slab for a retail shop:
Gross Purchase Value ($) Discount (%) 500 to 1000 2% More than 1000 less than 2000 5% More than 2000 10% Code:
amt = int(input("Enter the gross purchase value: ")) disc = 0 if amt>500 and amt<=1000: disc = amt*0.02 elif amt>1000 and amt<=2000: disc = amt*0.05 elif amt>2000: disc = amt*0.1 print(f"Net payable amount is {amt-disc}")
The output can be seen as under:
Write code to calculate the monthly electricity bill amount of the customer based on the following slab:
Units consumed Rate per unit (Rs.) 0-10 20 10-50 50 50-200 75 200-500 120 Above 500 150 Code:
u = int(input("Enter the units consumed: ")) bill_amt = 0 if u <=10: bill_amt = u*20 elif u>10 and u<=50: bill_amt = (10*20)+((u-10)*50) elif u>50 and u<=200: bill_amt = (10*20)+(40*50)+((u-50)*75) elif u>200 and u<=500: bill_amt = (10*20)+(40*50)+(150*75)+((u-200)*120) elif u>500: bill_amt = (10*20)+(40*50)+(150*75)+(300*120)+((u-500)*150) print (f"Electricity bill payable amount is {bill_amt}")
The output can be seen as under:
Summary
In this post, we covered conditional statements such as if
, elif
and else
in Python. Thank you for reading through and hope you learnt something valuable from this post. Do not forget to share this post and follow us for more similar content.