Python Basics #05 – Operators in Python

In this part of the Python Basics tutorial, we will learn about the basic operators.

There are many different kinds of operators based on their function.

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators

Arithematic Operators in Python

Operators used with numeric values to perform common mathematical operations are called Arithmetic operators. (For example, addition)

OperatorNameUsage
+Additionx + y
Subtractionx – y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
**Exponentx ** y
//Floor divisionx // y

Comparison Operators in Python

Comparison operators are used to compare two values.

OperatorNameUsage
==Equalx == y
!=Not equalx != y
>Greater thanx > y
<Lesser thanx < y
>=Greater than or equal tox >= y
<=Lesser than or equal to x <= y

They return Boolean values. They return True if the condition holds true. Otherwise, they return False.

For example, consider the following code block.

>> x = 5
>> y = 5
>> x == y
True

Logical Operators in Python

Logical operators are used to combine conditional statements.

Logical operators return boolean values.

OperatorUsage exampleDescription
notnot x=yReturns opposite of
the actual result
andx=y and y<zReturn true if both
expressions are True
or x=y and y<z Return true if any one of the
expressions is True

Bitwise Operators in Python

Bitwise operators are used to compare (binary) numbers:

Membership Operators in Python

To test if a sequence is present in an object, we use membership operators.


Membership operators return boolean values.

OperatorExampleResult
in5 in [1,2,3,4,5]True
not in‘a’ not in ‘python’True

Identity Operators in Python

To compare different objects, we use Identity operators. They are not used to compare values. They tell if the objects are the same i.e. point to the same memory location.

Identity operators return boolean value.

Returns True if both objects point to the same memory location.

Returns False if both objects do not point to the same memory location.

OperatorUsage
isx is y
is notx is not y

We now know the basic operators used in python and their usage. In the next part of this tutorial, we will learn about conditional statements.

Back : Python Basics #4 – Variables

Next : Python Basics #6 – Conditional Statements

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: