techmore.in

Python - Operators

Operators are special symbols in Python that perform computations or actions on variables and values. They form the core of expressions and are essential for decision-making, loops, and data manipulation.

Operators allow you to perform operations on data, such as arithmetic calculations, logical decisions, or even bit-level manipulations, making your code both dynamic and functional.

You use operators in almost every line of code—from assigning values to performing calculations, making decisions, looping through structures, comparing data, and more.

Python supports several types of operators, categorized as follows:

1. Arithmetic Operators

Used to perform mathematical operations:

  • + Addition
  • - Subtraction
  • * Multiplication
  • / Division
  • % Modulus
  • ** Exponentiation
  • // Floor Division
python
a = 10 b = 3 print(a + b) # 13 print(a - b) # 7 print(a * b) # 30 print(a / b) # 3.333... print(a % b) # 1 print(a ** b) # 1000 print(a // b) # 3a

2. Assignment Operators

Used to assign values to variables:

  • =, +=, -=, *=, /=, etc.

3. Comparison Operators

Used to compare values:

  • ==, !=, >, <, >=, <=

4. Logical Operators

Used to combine conditional statements:

  • and, or, not

5. Bitwise Operators

Used to perform bit-level operations:

  • &, |, ^, ~, <<, >>

6. Membership and Identity Operators

Membership: in, not in
Identity: is, is not

Pros:

  • Clear and concise expression of logic.
  • Broad set of operations for various tasks.
  • Improves readability and simplicity of code.

Cons:

  • Improper use can make code unreadable.
  • Overuse in a single line can reduce clarity.
  • Bitwise operators may be complex for beginners.