Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Wednesday, 30 November 2016

Python Conditional Statements : if-elif-else & Nested if-else

Python if-elif-else statement - In the previous articles, we have learned about data structures in Python, viz. String, List, Dictionary, Tuple, File and Set. Now, this is the point from where we start performing certain operations on them. In this article, we will be knowing about the conditional statements in Python, which are if, if-else and if-elif-else statements. Before we proceed, I would like to remind you about the term Indentation, that we had mentioned in our introductory article on Python.

python-if-elif-else-statement

Indentation

In many other languages, in order to include a sequence of statements inside a block, a pair of curly braces ({ ... }) are used. This would not only add logic to your code, but also enhance the readability of the code, as indentation aligns our code vertically and gives an idea about which statement is a part of which block. Normally, the code would look like something as shown below (I've indented the code, but even if it was not indented, the meaning of the code would have remained intact.):

if (some_condition) {
    # Block of code begins
    ---- ;
    ---- ;
    ---- ;
    # Block of code ends
    if (some_other_condition) {
        # Block of code begins
        ---- ;
        ---- ;
        ---- ;
        # Block of code ends
    }
}

In Python, we have white-space indented statements, in order to indicate that these statements belong to the same block. For this, we make use of TAB or four white-spaces at the beginning of each statement. Thus, end of indentation suggests that, the block has ended and subsequent statements are not the part of this block. So, immense care must be taken while coding in Python, as an error while indenting the statements will change the meaning of your entire code. In Python, above shown piece of code would look like (You need not bother about syntax at all, at this point of time) :

if (some_condition) :
    # Block of code begins
    ---- 
    ---- 
    ---- 
    # Block of code ends
    if (some_other_condition) :
        # Block of code begins
        ---- 
        ---- 
        ---- 
        # Block of code ends

Please observe that, statements inside first if statement are indented with a single TAB character, while those inside second if statement are indented with two TAB characters. This depicts that, first block of statement are the part of first if statement, while other block belongs to the second one. Had I indented the second block with single TAB, it would have become the part of first if statement, changing the meaning of entire code. Thus, indentation in Python has a special meaning and can change the logic of your entire code.

if statement

Generally, conditional statements are used when there is a need of doing something depending upon outcome of some event. As in any other programming language, Python if statement executes a block of statements, depending upon some condition and if it evaluates to True. The condition is an another Python statement, which returns a bool type, we have already seen relational and logical operations that would return True or False. Lets now see the syntax for using an if statement.

Syntax :

if (condition) :
    # Block of code starts
    ----
    ----
    ----
    # Block of code ends

Example 1 :

>>> var = 5
>>> if var == 5:
...     print "Value of 'var' is 5."
...     print "So, 'if' statement has executed"
...
Value of 'var' is 5.
So, 'if' statement has executed

>>> var = 7
>>> if var == 5:
...     print "Value of 'var' is 5."
...     print "So, 'if' statement has executed"
...
>>>

Example 2 : Check if a number is Even

>>> myNum = 63
>>> if myNum % 2 == 0 :
...     print 'myNum is Even'
...     print 'Executing "if" block'
...

>>> myNum = 16
>>> if myNum % 2 == 0 :
...     print 'myNum is Even'
...     print 'Executing "if" block'
...
myNum is Even
Executing "if" block

You can observe in above example that, condition is var == 5 and block of the code comprises of two print statements. As we are using if statement, the block of code will only be executed if and only if the condition evaluates to True. In first case, var = 5 which makes condition True, so the two print statements are executed. While in other case, var = 7 makes the condition False because of which block of code is skipped from executing. Please note that, the condition needs not always be an expression like we used here. It can be a Python object also, a String, a List, a Tuple, a Dictionary, a number and so on. An empty Python object or a zero denotes False, while a non-empty and a non-zero Python object will always denote a True.

Examples :

# A zero always denotes 'False'
>>> myInt = 0
>>> if myInt:
...     print 'This is a non-zero integer.'
...
# A non-zero number always denotes 'True'
>>> myInt = 12.34
>>> if myInt:
...     print 'This is a non-zero integer.'
...
This is a non-zero integer.

# An empty string always denotes 'False'
>>> myStr = ""
>>> if myStr:
...     print 'This is a non-empty string.'
...
>>> myStr = "CodeNinja"
>>> if myStr:
...     print 'This is a non-empty string.'
...
This is a non-empty string.

# An empty list always denotes 'False'
>>> myList = []
>>> if myList:
...     print 'This is a non-empty list.'
...
>>> myList = [1, 2, 3]
>>> if myList:
...     print 'This is a non-empty list.'
...
This is a non-empty list.

# An empty tuple always denotes 'False'
>>> myTuple = ()
>>> if myTuple:
...     print 'This is a non-empty tuple.'
...
>>> myTuple = (100,)
>>> if myTuple:
...     print 'This is a non-empty tuple.'
...
This is a non-empty tuple.

if-else statement

As we've seen, if will execute the block of statements if the condition evaluates to True, but what if we want to perform some action if the condition doesn't follow? In that case, we need to make use of else block, which is optional one but can be used as and when required. With if-else statement, we check the condition in the if statement, if it evaluates to True, the if block is executed. But, if it evaluates to False, else block will be executed. The syntax to use if-else statement in Python is as below:

Syntax :

if (condition) :
    # Block of code starts
    ----
    ----
    ----
    # Block of code ends
else :
    # Block of code starts
    ----
    ----
    ----
    # Block of code ends

Example 1 :

# Condition evaluates to 'True' -> 'if' block will be executed
>>> myInt = 5
>>> if myInt == 5 :
...     print 'myInt is 5.'
...     print 'Executing "if" statement.'
... else:
...     print 'myInt is not equal to 5.'
...     print 'Executing "else" block.'
...
myInt is 5.
Executing "if" statement.

# Condition evaluates to 'False' -> 'else' block will be executed
>>> myInt = 55
>>> if myInt == 5 :
...     print 'myInt is 5.'
...     print 'Executing "if" statement.'
... else:
...     print 'myInt is not equal to 5.'
...     print 'Executing "else" block.'
...
myInt is not equal to 5.
Executing "else" block.

Example 2 : Checking if a number is Even or Odd

>>> myNum = 63
>>> if myNum % 2 == 0:
...     print 'myNum is Even'
...     print 'Executing "if" block'
... else:
...     print 'myNum is Odd'
...     print 'Executing "else" block'
...
myNum is Odd
Executing "else" block

>>> myNum = 16
>>> if myNum % 2 == 0:
...     print 'myNum is Even'
...     print 'Executing "if" block'
... else:
...     print 'myNum is Odd'
...     print 'Executing "else" block'
...
myNum is Even
Executing "if" block

Thus, with if-else statement, we can perform certain actions if the condition follows and if it doesn't. What if we have multiple conditions, e.g. to find out whether a number is divisible by 2 or 3 or neither of them? We have another statement - if-elif-else, which we will see next.

if-elif-else statement

So far, in if and if-else we have checked only one condition. Sometimes, it necessitates to check more than one condition, where we can use if-elif-else statement. In this statements, we have one if and one else block and one or more elif blocks. With each elif statement, we can check a condition, if it evaluates to True corresponding block of statements get executed. Thus, flow of the condition check is - first of all, it will check the condition in if statement, if False, it will check condition in elif statement(s) one-by-one. If none of the conditions evaluates to True, control goes to else statement and corresponding block is executed. The syntax for this statement is as below:

if (condition1) :
    ----
    ----
    ----
elif (condition2) :
    ----
    ----
    ----
elif (condition3) :
    ----
    ----
    ----
...
...
...
elif (conditionN) :
    ----
    ----
    ----
else :
    ----
    ----
    ----

Example: Check a number is divisible by 2 or 3

>>> myNum = 7
>>> if myNum % 2 == 0 and myNum %3 == 0:
...     print 'myNum is divisible by both 2 and 3'
...     print 'Executing "if" block'
... elif myNum % 2 == 0:
...     print 'myNum is divisible by 2 only'
...     print 'Executing first "elif" block'
... elif myNum % 3 == 0:
...     print 'myNum is divisible by 3 only'
...     print 'Executing second "elif" block'
... else:
...     print 'myNum is neither divisible by 2 nor 3'
...     print 'Executing "else" block'
...
myNum is neither divisible by 2 nor 3
Executing "else" block

>>> myNum = 9
>>> if myNum % 2 == 0 and myNum %3 == 0:
...     print 'myNum is divisible by both 2 and 3'
...     print 'Executing "if" block'
... elif myNum % 2 == 0:
...     print 'myNum is divisible by 2 only'
...     print 'Executing first "elif" block'
... elif myNum % 3 == 0:
...     print 'myNum is divisible by 3 only'
...     print 'Executing second "elif" block'
... else:
...     print 'myNum is neither divisible by 2 nor 3'
...     print 'Executing "else" block'
...
myNum is divisible by 3 only
Executing second "elif" block

>>> myNum = 8
>>> if myNum % 2 == 0 and myNum %3 == 0:
...     print 'myNum is divisible by both 2 and 3'
...     print 'Executing "if" block'
... elif myNum % 2 == 0:
...     print 'myNum is divisible by 2 only'
...     print 'Executing first "elif" block'
... elif myNum % 3 == 0:
...     print 'myNum is divisible by 3 only'
...     print 'Executing second "elif" block'
... else:
...     print 'myNum is neither divisible by 2 nor 3'
...     print 'Executing "else" block'
...
myNum is divisible by 2 only
Executing first "elif" block

>>> myNum = 12
>>> if myNum % 2 == 0 and myNum %3 == 0:
...     print 'myNum is divisible by both 2 and 3'
...     print 'Executing "if" block'
... elif myNum % 2 == 0:
...     print 'myNum is divisible by 2 only'
...     print 'Executing first "elif" block'
... elif myNum % 3 == 0:
...     print 'myNum is divisible by 3 only'
...     print 'Executing second "elif" block'
... else:
...     print 'myNum is neither divisible by 2 nor 3'
...     print 'Executing "else" block'
...
myNum is divisible by both 2 and 3
Executing "if" block

Nested if-else statement

In nested if-else statements, we can have one or more if-elif-else statement inside an if-elif-else statement. This is where indentation plays a very crucial role, as in order to introduce an if statement inside other, we need to indent it properly, or the entire logic will change.

Syntax :

if (condition) :
    ---
    ---
    if (condition) :
        ---
        ---
    elif (condition) :
        ---
        ---
    else:
        ---
        ---
elif (condition) :
    ---
    ---
    if (condition) :
        ---
        ---
    else :
        ---
        ---
else :
    ---
    ---
    if (condition) :
        ---
        ---
    else :
        ---
        ---

Example : Check whether a number is divisible by 2 or 3

>>> myNum = 7
>>> if myNum % 2 == 0 :
...     if myNum % 3 == 0 :
...             print 'myNum is divisible by both 2 and 3'
...     else:
...             print 'myNum is divisible by 2 only'
... elif myNum % 3 == 0 :
...     print 'myNum is divisible by 3 only'
... else :
...     if myNum % 5 == 0:
...             print 'myNum is neither divisible by 2 nor 3, but divisible by 5'
...     else:
...             print 'myNum is neither divisible by 2 nor by 3'
...
myNum is neither divisible by 2 nor by 3

>>> myNum = 25
>>> if myNum % 2 == 0 :
...     if myNum % 3 == 0 :
...             print 'myNum is divisible by both 2 and 3'
...     else:
...             print 'myNum is divisible by 2 only'
... elif myNum % 3 == 0 :
...     print 'myNum is divisible by 3 only'
... else :
...     if myNum % 5 == 0:
...             print 'myNum is neither divisible by 2 nor 3, but divisible by 5'
...     else:
...             print 'myNum is neither divisible by 2 nor by 3'
...
myNum is neither divisible by 2 nor 3, but divisible by 5

>>> myNum = 24
>>> if myNum % 2 == 0 :
...     if myNum % 3 == 0 :
...             print 'myNum is divisible by both 2 and 3'
...     else:
...             print 'myNum is divisible by 2 only'
... elif myNum % 3 == 0 :
...     print 'myNum is divisible by 3 only'
... else :
...     if myNum % 5 == 0:
...             print 'myNum is neither divisible by 2 nor 3, but divisible by 5'
...     else:
...             print 'myNum is neither divisible by 2 nor by 3'
...
myNum is divisible by both 2 and 3

You can observe that, in the else block also, we have put an if-else just to check whether the number is divisible by 5 and print the result accordingly. Nothing so great about it, but it was just to give you a glimpse about how a nested if-else statement works.

With this, we have come to an end of the discussion on if-elif-else statement in Python. After reading this article, one should be able to decide which statement must be used given a scenario and write those statements. Although very basic examples are provides, those should have given you a clear idea about how the control flow is switched depending on what the condition evaluates to. In the next article, we will be covering for loop, which is used to iterate over a Python iterable object or repeat a certain task for number of times. Please share your views and feedback on this article in the comment section below and stay tuned for more articles. Thank you!

This article is originally published at www.codeninja.in - Python Conditional Statements

0 comments:

Post a Comment