Python operators

Python operators are special symbols or keywords used to perform operations on variables and values. Operators are used to manipulate data in various ways, such as performing arithmetic, comparisons, or logical operations. Python has several types of operators:

1. Arithmetic Operators:

These are used to perform basic mathematical operations like addition, subtraction, multiplication, etc.

Operator Description Example
+ Addition 10+2 →12
Subtraction 10-2 → 8
* Multiplication 10*2 → 20
/ Division (returns float) 10/2 → 5
// Floor Division (returns int) 11 // 2 → 5
% Modulus (remainder) 11 % 2 → 1
** Exponentiation (power) 10 ** 2 → 100

2. Comparison (Relational) Operators:

These operators compare two values and return a Boolean result (True or False).

Operator Description Example
== Equal to 10 == 10 → True
!= Not equal to 10 != 2 → True
> Greater than 10 > 2 → True
< Less than 10 < 2 → False
>= Greater than or equal 10 >= 2 → True
<= Less than or equal 10 <= 2 → False
** Exponentiation (power) 10 ** 2 → 100

3. Assignment Operators:

These operators are used to assign values to variables.

Operator Description Example
= Assign x = 10
+= Add and assign x += 10 → x = x + 10
-= Subtract and assign x -= 10 → x = x – 10
*= Multiply and assign x *= 10 → x = x * 10
/= Divide and assign x /= 10 → x = x / 10
% Modulus (remainder) 11 % 2 → 1
//= Floor divide and assign x //= 10 → x = x // 10
%= Modulus and assign x %= 10 → x = x % 10
**= Exponentiation and assign x **= 10 → x = x ** 10

4. Logical Operators:

These operators are used to perform logical operations and return Boolean values.

Operator Description Example
and Logical AND (both conditions must be True) True and False → False
or Logical OR (at least one condition is True) True or False → True
not Logical NOT (negates the condition) not True → False

5. Bitwise Operators:

These operators work on bits and perform bit-by-bit operations.

Operator Description Example
& Bitwise AND 5 & 3 → 1
or Logical OR (at least one condition is True) True or False → True
Bitwise OR
^ Bitwise XOR 5 ^ 3 → 6
~ Bitwise NOT ~5 → -6
<< Left Shift 5 << 1 → 10
>> Right Shift 5 >> 1 → 2

6. Identity Operators:

These operators check if two objects are identical (i.e., refer to the same memory location).

Operator Description Example
is True if both refer to the same object x is y
is not True if they refer to different objects x is not y

7. Membership Operators:

These operators test if a sequence (like a list, string, or tuple) contains a value.

Operator Description Example
in True if value is in sequence ‘a’ in [‘a’, ‘b’, ‘c’] → True
not in True if value is not in sequence ‘x’ not in [‘a’, ‘b’, ‘c’] → True

8. Ternary (Conditional) Operator:

This operator allows you to execute expressions conditionally in a single line.

Syntax:


result = value_if_true if condition else value_if_false

Example:


age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)  # Output: Adult