Python Operators

Operators are used to performing operations on variables.

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

 

Arithmetic operators: Used to performs an arithmetic operation on numeric values.

Operator Example
+ (Addition) 2+3 = 5
– (Subtraction) 2-3 = -1
* (Multiplication) 2*3 = 6
/ (Division) ⅔ = 0.66
% ( Modulus) 2%3 = 2
** (Exponentiation) 2**3 = 8
// (floor division) 2//3 = 0

 

Assignment operators: Used to assign value to variable.

Operator Example equivalent to
a = 2 a = 2
+= a += 2 a = a + 2
-= a -= 2 a = a – 2
&= a &= 2 a = a & 2

 

Comparison operators: Used to compare two values.

Operator Example
== (Equal) a == b
!= (Not Equal) a != b
> (Greater than) a > b
< (Less than) a < b
>= (Greater than or equal to) a >= b
<= (Less than or equal to) a <= b

 

Logical Operators: Used to combine conditional statements

Operator  Example
and  (Returns True if both statements are true) a > 3 and a <5
or (Returns True if one of the statements is true) a > 3 or a <5
not (Reverse the result) not(a > 3)

 

Identity Operators:  Used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

Operator Example
is (Returns true if both variables are the same object) a is y
is not (Returns true if both variables are not the same object) a is not y

 

Membership Operators: Used to check if a sequence is presented in an object.

Operator Example
in (Returns True if a value is present in the object) a in y
not in (Returns True if a value is not present in the object) a not in y

 

Bitwise Operators: Used to perform bit operation on a bit.

Operator Description
& (And) Sets each bit to 1 if both bits are 1
| (OR) Sets each bit to 1 if one of two bits is 1
^ (XOR) Sets each bit to 1 if only one of two bits is 1
~ (NOT) Inverts all the bits
<< (Binary Left Shift) Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> (Binary Right Shift) Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

Leave a Reply

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

Python Tutorials

Python – List Comprehension

Python Set

Python : Assert Keyword

Python Dictionary

Python Tuple

Python List

Python: String

Python: String Formatting using f-string

Python: String Formatting – 2

Python: String Formatting – 1

Python Input/Output

Python Type Conversion and Type Casting

Python Comments

Python – Regular Expression (RegEx)

Python Iterators

Python File Handling

Python Exceptions

Python Function

Python Loops

Python If…Else

Python Collections

Variables in Python

Python Syntax

Introduction to Python

Python OOPs Concepts

Study Machine Learning