Operators in Python [ Complete Guide ]

Tech Orcus
By -
12 minute read
0

Chapter 4: Operators in Python


Operators in Python

In this chapter, we’ll learn all about operators in Python. Operators are special symbols or keywords that perform operations on variables and values. Python supports several types of operators to make coding easier and more efficient.

Types of Operators in Python:

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations:

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b
** Exponentiation a ** b
// Floor Division a // b

2. Comparison Operators

Comparison operators compare two values and return a boolean (True/False):

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

3. Assignment Operators

Assignment operators are used to assign values to variables:

Operator Description Example
= Assigns value a = 5
+= Add and assign a += 2 (same as a = a + 2)
-= Subtract and assign a -= 2
*= Multiply and assign a *= 2
/= Divide and assign a /= 2
%= Modulus and assign a %= 2

4. Logical Operators

Logical operators are used to combine conditional statements:

  • and: Returns True if both statements are true (a > 5 and b < 10)
  • or: Returns True if at least one statement is true (a > 5 or b < 10)
  • not: Reverses the result (not(a > 5))

5. Bitwise Operators

Bitwise operators perform operations at the binary level. These are more advanced but powerful in certain scenarios:

  • &: AND
  • |: OR
  • ^: XOR
  • ~: NOT
  • <<: Left Shift
  • >>: Right Shift

6. Membership Operators

  • in: Returns True if a sequence is found in the object ('a' in 'apple')
  • not in: Returns True if a sequence is not found in the object ('b' not in 'apple')

7. Identity Operators

  • is: Returns True if two objects are the same (a is b)
  • is not: Returns True if two objects are not the same (a is not b)

That’s it for operators in Python! Practice these with simple examples to understand them better. In the next chapter, we’ll explore Control Flow Statements.

Post a Comment

0Comments

Post a Comment (0)
Today | 15, April 2025