In the last tutorial, we studied about the logical and relational expressions and tried to understand their usage with help of various examples. We also saw examples about how multiple relational expressions can be put together with the help of logical operators to create meaningful logical expressions.
We also mentioned how these logical and relational expressions can be used to control the flow of execution.
In this section, we will learn some more ways to control the flow of execution. In programming, there are two ways to achieve this, and they are known as conditional statements and looping.
In this tutorial, we will be discussing about the conditional statements, so let's begin.
There will be various situations while writing a program when you will have to take care of different possible conditions that might arise while execution of the program. In such situations,
if conditions can be used.
Syntax for using the
if keyword is as follows:
if [conditional expression]: [statement(s) to execute]
if keyword and the conditional expression is ended with a colon. In [conditional expression] some conditional expression is introduced that is supposed to return a boolean value, i.e.,
False. If the resulting value is
True then the [statement to execute] is executed, which is mentioned below the
if condition with a tabspace(This indentation is very important).
Taking a real-life example, let's say in a savings bank account a user A, has Rs.1000. The user A, visits the ATM to withdraw money from his savings account. Now the program which handles the ATM transactions should be able to perform in every situation, like the program should be aware of the user's bank account balance, and should not allow the user to withdraw money more than the available balance in his account. Also, the program must update the account balance once the user has withdrawn money from the account, to keep the records updated. Let's write a small piece of code to stop user from withdrawing money more than the available account balance.
>>> savingAmt = 1000 >>> withdrawAmt = int(raw_input("Amount to Withdraw: ")) >>> if withdrawAmt > savingAmt: print "Insufficient balance"
Amount to Withdraw: 2000 Insufficient balance
In the above program if the user enters any amount more than Rs. 1000, a message is displayed on the screen saying "Insufficient Funds".
There are two more keywords that are optional, but can be accompanied with
if statements, the are:
elif(also known as else if)
else, let's first see how it is used alongside the
if[conditional expression]: [statement to execute] else: [alternate statement to execute]
Continuing with the bank account-ATM example, if you noticed in the program above, we forgot to subtract the withdrawn amount from the savings account balance. Since now we have an additional
else condition to use, we can print a warning with the message, "Insufficient balance" if the saving amount is less than the withdraw amount, or else we can subtract the withdrawn amount from the savings account amount to update the account balance. So the
if condition written in the previous example, will get an additional
if withdrawAmt > savingAmt: print "Insufficient balance" else: savingAmt = savingAmt - withdrawAmt print "Account Balance:" + str(savingAmt)
And with the
else block introduced, in case there is sufficient balance, the
withdrawAmt will be subtracted from the
savingAmt and the updated account balance will be displayed on screen.
else, now we can diverge the flow of execution into two different directions. In case of a savings account, there will be only two cases, you have sufficient money or you don't, but what if we come across some situation where there are more than two possibilities? In such cases, we use yet another statement that is accompanied with the
else statements, called
elif (or else if in proper English).
elif statement is added between
if[condition #1]: [statement #1] elif[condition #2]: [statement #2] elif[condition #3]: [statement #3] else: [statement when if and elif(s) are False]
With this, you can add as many
elif blocks as you want depending upon the possibilities that may arise.
Let's say you are given a time and you have to tell what phase of the day it is- (morning, noon, afternoon, evening or night). You will have to check the given time against multiple ranges of time within which each of the 5 phases lies. Therefore, the following conditions:
Below we have a simple program, using the
else conditional statements:
if (time >= 600) and (time < 1200): print "Morning" elif (time == 1200): print "Noon" elif (time > 1200) and (time <= 1700): print "Afternoon" elif (time > 1700) and (time <= 2000): print "Evening" elif ((time > 2000) and (time < 2400)) or ((time >= 0) and (time < 600)): print "Night" else: print "Invalid time!"
Notice the logical operators that have been used in each condition in the program, this example demonstrates how you will generally be using them with if-else statements.
Simply put, nesting
if else means that you will be writing if-else statements inside another if-else statements. Syntactically,
if[condition #1]: if[condition #1.1]: [statement to exec if #1 and #1.1 are true] else: [statement to exec if #1 and #1.1 are false] else: [alternate statement to execute]
Needless to say you can write the same if-else block inside an
else block too. Or in fact you can add an
elif condition, according to your needs. Although if you think about it, nested if-else is actually an alternative to
elif. And just like we created a program which printed the phase of the day by checking the range of time, that can be done without using
elif as well, by nesting
if (time >= 600) and (time < 1200): print "Morning" else: if (time == 1200): print "Noon" else: if (time > 1200) and (time <= 1700): print "Afternoon" else: if (time > 1700) and (time <= 2000): print "Evening" else: if ((time > 2000) and (time < 2400)) or ((time >= 0) and (time < 600)): print "Night" else: print "Invalid time!"
As you can see in the above program, all we did was, we started by adding a condition to the
if block, and then used another
if-else block in its
else block. And we kept on doing the nesting until all the conditions were taken care of. This, however, is a little tedious than using
Also, if you remember our first example while explaining the
if statement, the savings bank account example. There is actually a quicker way to do it, a one-line way because, it's python. The following is the logic:
if (saving > withdraw) then saving = (saving - withdraw), else saving will remain as it is and there will be no transaction.
>>> savingAmt = savingAmt - withdrawAmt if (savingAmt > withdrawAmt) else savingAmt