Skip to content

Python 3 - Basic Operators

Operators are special symbols or keywords in Python that perform operations on values. The values that operators act upon are called operands. For example, in the expression 5 + 3, + is the operator, and 5 and 3 are the operands.

Python includes several categories of operators:

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

Let’s explore each type.

These perform standard mathematical operations. Assume a = 10 and b = 3:

OperatorNameDescriptionExample (a=10, b=3)
+AdditionAdds operands.a + b is 13
-SubtractionSubtracts right operand from left.a - b is 7
*MultiplicationMultiplies operands.a * b is 30
/DivisionDivides left operand by right (result is always float).a / b is 3.333...
%ModulusReturns the remainder of the division.a % b is 1
**ExponentiationRaises left operand to the power of the right.a ** b is 1000
//Floor DivisionDivides and rounds down to the nearest whole number (integer).a // b is 3. -10 // 3 is -4.
#!/usr/bin/env python3
a = 10
b = 3
print(f"a + b = {a + b}")
print(f"a - b = {a - b}")
print(f"a * b = {a * b}")
print(f"a / b = {a / b}")
print(f"a % b = {a % b}")
print(f"a ** b = {a ** b}")
print(f"a // b = {a // b}")
print(f"-10 // 3 = {-10 // 3}") # Note floor division with negative numbers

These operators compare two values and return a Boolean result (True or False). Assume a = 10 and b = 20:

OperatorNameDescriptionExample (a=10, b=20)
==Equal toChecks if values are equal.a == b is False
!=Not equal toChecks if values are not equal.a != b is True
>Greater thanChecks if left operand is greater.a > b is False
<Less thanChecks if left operand is less.a < b is True
>=Greater than or equal toChecks if left operand is greater or equal.a >= b is False
<=Less than or equal toChecks if left operand is less or equal.a <= b is True
#!/usr/bin/env python3
a = 10
b = 20
print(f"a == b: {a == b}")
print(f"a != b: {a != b}")
print(f"a > b: {a > b}")
print(f"a < b: {a < b}")
print(f"a >= b: {a >= b}")
print(f"a <= b: {a <= b}")

These operators assign values to variables. The basic assignment operator is =. Combined operators perform an operation and assign the result in one step. Assume c = 10 initially for compound assignments:

OperatorExampleEquivalent to
=x = 5x = 5
+=c += 5c = c + 5 (c becomes 15)
-=c -= 3c = c - 3 (c becomes 7)
*=c *= 2c = c * 2 (c becomes 20)
/=c /= 4c = c / 4 (c becomes 2.5)
%=c %= 3c = c % 3 (c becomes 1)
**=c **= 3c = c ** 3 (c becomes 1000)
//=c //= 3c = c // 3 (c becomes 3)
#!/usr/bin/env python3
c = 10
print(f"Initial c: {c}")
c += 5
print(f"After c += 5: {c}")
c //= 6
print(f"After c //= 6: {c}")

These operators combine conditional statements and return True or False. Assume x = True and y = False:

OperatorDescriptionExample (x=True, y=False)
andReturns True if both operands are true.x and y is False
orReturns True if at least one operand is true.x or y is True
notReverses the logical state (True becomes False, False becomes True).not x is False

Logical operators use short-circuiting: and stops evaluating if the first operand is false; or stops if the first is true.

#!/usr/bin/env python3
age = 25
has_permission = False
if age >= 18 and has_permission:
print("Access granted.")
else:
print("Access denied.")
if age < 18 or age > 65:
print("Eligible for discount.")
else:
print("Standard price applies.")
print(f"Not has_permission: {not has_permission}")

These operators test if a value is present in a sequence (like lists, tuples, strings). Assume my_list = [1, 2, 3]:

OperatorDescriptionExample (my_list = [1, 2, 3])
inReturns True if the value is found in the sequence.2 in my_list is True
not inReturns True if the value is not found in the sequence.4 not in my_list is True
#!/usr/bin/env python3
my_list = [1, 2, 3, 'a', 'b']
name = "Python"
print(f"Is 3 in my_list? {3 in my_list}")
print(f"Is 'c' not in my_list? {'c' not in my_list}")
print(f"Is 'th' in name? {'th' in name}")

These operators compare the memory locations of two objects, checking if they are the exact same object (not just if they have the same value).

OperatorDescriptionExample
isReturns True if both variables point to the same object.x is y
is notReturns True if variables point to different objects.x is not y

Use is with caution. For immutable types like integers (small ones) and strings, Python might reuse objects, leading to is returning True unexpectedly. It’s primarily used to check against singletons like None.

#!/usr/bin/env python3
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(f"a == b: {a == b}") # True (Values are equal)
print(f"a is b: {a is b}") # False (Different objects in memory)
print(f"a == c: {a == c}") # True (Values are equal)
print(f"a is c: {a is c}") # True (Point to the same object)
# Common use case for 'is'
value = None
if value is None:
print("Value is None")
if value is not None:
print("Value is not None")

These operators perform operations directly on the binary (bit) representation of integers. They are less common in general scripting but used in specific areas like low-level programming or data manipulation. Assume a = 60 (0011 1100) and b = 13 (0000 1101):

OperatorNameDescriptionExample (a=60, b=13)
&Bitwise ANDSets each bit to 1 if both corresponding bits are 1.a & b is 12 (0000 1100)
|Bitwise ORSets each bit to 1 if at least one corresponding bit is 1.a | b is 61 (0011 1101)
^Bitwise XORSets each bit to 1 if only one corresponding bit is 1.a ^ b is 49 (0011 0001)
~Bitwise NOT (Complement)Inverts all bits (0 becomes 1, 1 becomes 0). Result depends on signed representation.~a is -61
<<Left ShiftShifts bits left, filling with zeros (multiplies by 2^n).a << 2 is 240 (1111 0000)
>>Right ShiftShifts bits right (divides by 2^n, discarding remainder).a >> 2 is 15 (0000 1111)

You can use the built-in bin() function to see the binary representation:

#!/usr/bin/env python3
a = 60
b = 13
print(f"a = {a} ({bin(a)}), b = {b} ({bin(b)})")
print(f"a & b = {a & b} ({bin(a & b)})")
print(f"a | b = {a | b} ({bin(a | b)})")
print(f"a ^ b = {a ^ b} ({bin(a ^ b)})")
print(f"~a = {~a} ({bin(~a)}) # Note: Two's complement")
print(f"a << 2 = {a << 2} ({bin(a << 2)})")
print(f"a >> 2 = {a >> 2} ({bin(a >> 2)})")

When an expression contains multiple operators, Python follows a specific order of precedence to determine which operations are performed first. Parentheses () can be used to override this order.

The following table lists operators from highest precedence (executed first) to lowest:

PrecedenceOperatorDescription
Highest()Parentheses
**Exponentiation
+x, -x, ~xUnary plus, minus, bitwise NOT
*, /, //, %Multiplication, division, floor division, modulus
+, -Addition, subtraction
<<, >>Bitwise shifts
&Bitwise AND
^Bitwise XOR
|Bitwise OR
in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, Membership, Identity
not xLogical NOT
andLogical AND
LowestorLogical OR

Example:

#!/usr/bin/env python3
result = 5 + 3 * 2 # Multiplication (*) has higher precedence than Addition (+)
print(f"5 + 3 * 2 = {result}") # Output: 11
result = (5 + 3) * 2 # Parentheses override precedence
print(f"(5 + 3) * 2 = {result}") # Output: 16
result = 10 / 2 + 3 # Division (/) has higher precedence than Addition (+)
print(f"10 / 2 + 3 = {result}") # Output: 8.0