Python Conditional Statements

Effective way of using Python Conditional Statements and Logical Operators | 6 mins read

Holla, welcome to today's tutorial on 'Python Conditional statements and logical operators'. Conditional statements are used to break the code into small pieces that execute under some circumstances. Learn various use of if,elif and else statement along with syntax and sample code. The pythonic way to use logical operators reduce the code into few lines.

Table of Contents

Introduction

Welcome back to another exciting tutorial on “Python conditional statement and logical operators”. In this Python tutorial, you’ll learn the syntax and uses of python conditional statements.

You’ll also learn how and when to use a specific python conditional statement with the help of examples. In the end, you will learn about different logical operators in python. Let’s begin our tutorial with an introduction to the Python conditional statements and relational operators,followed by an introduction to Python logical operators.

If you aren’t following along, I would recommend you to go back where you left or start from here.

Python Conditional Statement

Python Conditional statements are used to break the code into small pieces that execute under some circumstances. These are very useful for the problems which need decision making such as :-

if number%2 == 0: “This is an even number”

otherwise ‘Not’.

Python conditional statements revolve around three keywords i.e. if,elif and else. These keywords may take any form such as if-else ,if ,if-elif-else or nested if-else.The portion of code under these clauses only execute when the given condition meet.

In this article, we are going to learn about the syntax,keywords of python conditional statements and logical operators in detail.

Relational Operators

Relational operators in python conditional statements

A block of code is indented to the right(generally 1 tab space) in python.

Let us look over a sample code that describes the use and syntax detail of every relational operator.

>>> x = 5
>>> y = 6
>>> print(x == y)
False
>>> print(x != y)
True
>>> print(x<y) 
True 
>>> print(x>Y)
False
>>> print(x<=y) 
True 
>>> print(x>=y)
False

Python provides an easy way to append two or more relational operator queries .

Python Trick

A cool trick in python language is that you can combine two or more python conditional statement into one( other than using logical operator ). Consider an example, you have to check a number is greater than one number but smaller than other.

In this case, one way is to check these two condition separately and join them using ‘and’ operator.

>>> # Check if y is greater than x and less than z.
>>> x = 5
>>> y = 7
>>> z = 9
>>> print(x<y and y<z)

The other way is pythonic way to check the same condition.

>>> # Check if y is greater than x and less than z.
>>> x = 5
>>> y = 7
>>> z = 9
>>> print(x<y<z)
True

Both the approaches leads to the same result but the later one is more efficient code.These cool tricks in python help a lot while writing the program.

Python Conditional Statement : if

if statement in python is used to execute a section of code when the expression becomes true.The section of code under if block is indented.

Syntax


if expression:

……………

execute these lines

…………….


Flow chart

Flow chart of if statement
Flow chart of if statement

Example1# The piece of code under if statement is always executed as the condition is hard coded to True.

>>> if True:
...     print('Hello Coder')
... 
Hello Coder

Example2# Consider a variable x and if x is greater than 1 , print message “Number is greater than 1”

#let x  = 2
>>> x = 2
>>> if x>1:
...     print('Number is greater than 1')
...
Number is greater than 1
# let x = 0
>>> x = 0
>>> if x>1:
...     print('Number is greater than 1')
...
>>>
When x<1 , the program prints nothing .This is not an ideal case for real word problems.
The user should get to know why some piece of code is not executed .To solve this problem,there is another statement ‘else‘.

Python Conditional Statement : else

The else python conditional statement is used with if statement.(for-else and while-else in looping tutorial ) .It is executed when if statement evaluates to false.

Syntax

if expression:

execute this section

else:

execute this

Flow Chart

Flow chart of if else statement
Flow chart of if else statement

Example# In previous section, we use the same example without else part.Here, we extend previous example such that the message ‘Number is less than 1’ printed ,if condition fails.

>>> x = 0
>>> if x>1:
...     print('Number is greater than 1')
... else:
...     print('Number is less than 1')
...
Number is less than 1

Python Conditional Statement : if-elif-else

Sometime,we have to check more than one condition and for each condition we have to execute a specific piece of code.

elif statement is used to check multiple expression for true and execute the block of code when condition evaluates to true.There can be many elif for an if statement.

else statement is optional in if-elif statement.

Syntax

if expression1:

execute this section

elif expression2:

execute this section

elif expression3:

execute this section

else:

execute this section

Flow Chart

Flow chart of if elif else statement
Flow chart of if elif else statement

Example# Consider the case ,where we have to compare a number with a given key, there will be three cases:- number == key, number>key or number<key.

We check the condition and execute the apropriate code using if-elif-else.

>>> x = 1
>>> if x>1:
...     print('Number is greater than 1')
... elif x == 1:
...     print('Number is equal to 1')
... else:
...     print('Number is less than 1')
...
Number is equal to 1

is operator

Most of the people think that is operator is equivalent to ‘==‘ operator but this is not true.

is operator is used to check whether two variable are reference of same object or not.

Let us take some example to understand the meaning of the above line.


Example1# Let us initialize two python list having same content .You can see the equality operator holds true but is operator returns false.

>>> x = ['topic','trick']
>>> y = ['topic','trick']
>>> print(x == y)
True
>>> print(x is y)
False

List x and y are equal but they refer to two different location.

Example2# In this case, we initialize a list and create a reference to the list.You can see that the object id of both x and y are same ,hence they yield true on checking if x is y.

>>> x = ['topic','trick']
>>> y = x
>>> print(x is y)
True
>>> id(x)
140085174882112
>>> id(y)
140085174882112

Object id are same so x is y evaluates True.

Logical Operator

Truth Table
Truth Table

Logical operators combine one or more conditional to get a boolean value as a result.

  • AND operator :- Result is true if every condition is true.
>>> x = 2
>>> if x>1 and x<5:
...     print('Number is between 1 and 5')
... else:
...     print('I don't know then')
...
Number is between 1 and 5
  • OR operator :- Result is true if any one condition is true.
>>> like_content = True
>>> share_content = False
>>> if like_content or share_content:
...     print('Topictrick says thank you')
... else:
...     print('Topictrick says We will try again')
...
Topictrick says thank you
  • NOT operator :- It turns True to False and vice versa.
>>> is_even = False
>>> if not is_even:
...     print('Number is odd')
...
Number is odd

Datatype equivalent to false

Data type other than boolean can be used as boolean value( True or False).

The below table consists of all the value that resembles false.

false as datatype in python conditional statements