Python - Operators

Python - Operators


Previous Page

Operators are used to perform operation on two operands. Operators in Python can be categorized as follows:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Arithmetic operators

Arithmetic operators are used to perform arithmetic operations on two operands.

OperatorDescription
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponent / Powera**b is equivalent to a^b (ex: 10**2 is equal to 100)
% Modulusa%b returns remainder of a/b (ex: 10 % 3 returns 1)
// Floor divisiona//b returns greatest integer of a/b (ex: 14//3 returns 4)

Assignment operators

Assignment operators are used to assign values of right hand side expression to left hand side operand.

Operator Expression Equivalent to
= a = 5a = 5
+= a += ba = a + b
-= a -= ba = a - b
*= a *= ba = a * b
/= a /= ba = a / b
**= a **= ba = a ** b
%= a %= ba = a % b
//= a //= ba = a // b
&= a &= ba = a & b
|= a |= ba = a | b
^= a ^= ba = a ^ b
>>= a >>= ba = a >> b
<<= a <<= ba = a << b

Comparison operators

Comparison operators are used to compare values of two operands. It returns true when values matches and false when values doen not match.

Operator Description
==Equal
!=Not equal
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Logical operators

Logical operators are used to combine two or more conditions.

Operator Description
and Returns True when all conditions are true
or Returns True when any of the conditions is true
notReturns opposite result not(2<5) returns false

Identity operators

Identity operators are used to compare memory location of two objects.

Operator Description
is Returns true when both variables are the same objecta is b
is notReturns true when both variables are not the same objecta is not b

Membership operators

Membership operators are used to check the membership of element(s) in a sequence like lists, tuple etc.

Operator Description
in Returns True if element(s) is present in the objecta in b
not inReturns True if element(s) is not present in the object a not in b

Bitwise operators

Bitwise operators are used to perform bitwise operations on two operands.

Operator Description
& ANDReturns 1 if both bits at the same in both operands are 1, else returns 0
|ORReturns 1 if one of two bits at the same in both operands is 1, else returns 0
^XORReturns 1 if only one of two bits at the same in both operands is 1, else returns 0
~ NOTReverse all the bits
>>Right shiftThe left operand is moved right by the number of bits present in the right operand
<<Left shiftThe left operand value is moved left by the number of bits present in the right operand

Previous Page