Python Operators: an introduction

P

Operators are one of the foundational concepts in any programming language, and Python is no different. They allow you to perform operations on variables and values, whether it’s basic math, comparing numbers, or performing complex bitwise manipulations.

In this post, we’ll explore the different types of Python operators and understand their usage. We’ll cover unary, binary, and ternary operators, followed by specific operator types like arithmetic, comparison, logical, bitwise, assignment, membership, and identity operators. By the end of this guide, you’ll have a strong grasp of how to use Python operators in various programming scenarios.

What is a python Operator?

An operator is a symbol or keyword that performs an operation on one or more values, called operands. These operations can range from arithmetic (like adding numbers) to logic checks (like determining if two conditions are true).

Categories of python Operators

Python operators are categorized into three main types:

  • Ternary operators: Operate on three operands.
  • Unary operators: Operate on a single operand.
  • Binary operators: Operate on two operands.

Unary operators

Unary operators only require a single operand. They are often used to modify a number or value.

  • Unary positive (+): Returns the positive value of an operand.
  • Unary negation (-): Returns the negative value of an operand.
  • Logical negation (not): Inverts the boolean value of an operand.
x = 5
print(+x)   # Unary positive, prints: 5
print(-x)   # Unary negation, prints: -5

# Logical negation
is_active = True
print(not is_active)  # Inverts the boolean, prints: False

Binary operators

Binary operators work with two operands, these are the most common python operators. These include arithmetic, comparison, logical, and bitwise operators.

Arithmetic operators

Arithmetic operators handle the basic math operations.

  • Addition (+): Adds two values.
  • Subtraction (-): Subtracts one value from another.
  • Multiplication (*): Multiplies two values.
  • Division (/): Divides one value by another.
  • Floor division (//): Divides and rounds down the result to the nearest whole number.
  • Modulus (%): Returns the remainder of division.
  • Exponentiation (**): Raises a number to the power of another.

You can read more about arithmetic operators in python, here.

a = 10
b = 3

print(a + b)  # Addition, prints: 13
print(a - b)  # Subtraction, prints: 7
print(a * b)  # Multiplication, prints: 30
print(a / b)  # Division, prints: 3.3333...
print(a // b)  # Floor division, prints: 3
print(a % b)  # Modulus, prints: 1
print(a ** b)  # Exponentiation, prints: 1000

Comparison Operators

Comparison operators allow you to compare two values. These operators always return a boolean value: True or False.

  • Equal (==): Checks if two values are equal.
  • Not equal (!=): Checks if two values are not equal.
  • Greater than (>): Checks if the left operand is greater than the right.
  • Less than (<): Checks if the left operand is less than the right.
  • Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right.
  • Less than or equal to (<=): Checks if the left operand is less than or equal to the right.
x = 10
y = 5

print(x == y)   # Equality, prints: False
print(x != y)   # Not equal, prints: True
print(x > y)    # Greater than, prints: True
print(x < y)    # Less than, prints: False
print(x >= y)   # Greater than or equal to, prints: True
print(x <= y)   # Less than or equal to, prints: False

Logical Operators

Logical operators are used to combine multiple conditions or check the logical relationship between values.

  • AND (and): Returns True if both conditions are true.
  • OR (or): Returns True if at least one condition is true.
  • NOT (not): Inverts the boolean value of a condition.
x = 10
y = 5

print(x > 5 and y < 10)  # Both conditions are true, prints: True
print(x > 5 or y > 10)   # At least one condition is true, prints: True
print(not (x == 10))     # Inverts the condition, prints: False

Bitwise Operators

Bitwise operators work on the binary representation of numbers. They are typically used in low-level programming, but it’s important to know how they work.

  • AND (&): Performs a bitwise AND operation.
  • OR (|): Performs a bitwise OR operation.
  • XOR (^): Performs a bitwise XOR operation.
  • NOT (~): Performs a bitwise NOT operation (flips the bits).
  • Left shift (<<): Shifts the bits to the left.
  • Right shift (>>): Shifts the bits to the right.
x = 5  # Binary: 101
y = 3  # Binary: 011

print(x & y)   # Bitwise AND, prints: 1 (Binary: 001)
print(x | y)   # Bitwise OR, prints: 7 (Binary: 111)
print(x ^ y)   # Bitwise XOR, prints: 6 (Binary: 110)
print(~x)      # Bitwise NOT, prints: -6 (Binary: ...1010 in two's complement)
print(x << 1)  # Left shift, prints: 10 (Binary: 1010)
print(x >> 1)  # Right shift, prints: 2 (Binary: 10)

Assignment Operators

Assignment operators assign values to variables. For example, the most basic is =, but Python also offers combined assignment operators that perform both an operation and assignment in a single step.

  • Assignment (=): Assigns a value to a variable.
  • Addition assignment (+=): Adds and assigns the result.
  • Subtraction assignment (-=): Subtracts and assigns the result.
  • Multiplication assignment (*=): Multiplies and assigns the result.
  • Division assignment (/=): Divides and assigns the result.
  • Modulus assignment (%=): Performs modulus and assigns the result.
  • Exponentiation assignment (**=): Raises to power and assigns the result.
x = 10
x += 5  # Same as x = x + 5
print(x)  # Prints: 15

x *= 2  # Same as x = x * 2
print(x)  # Prints: 30

Membership Operators

Membership operators are used to check if a value exists in a sequence (such as a list, tuple, or string).

  • In (in): Returns True if the value is found in the sequence.
  • Not in (not in): Returns True if the value is not found in the sequence.
my_list = [1, 2, 3, 4, 5]

print(3 in my_list)    # Checks if 3 is in the list, prints: True
print(6 not in my_list)  # Checks if 6 is not in the list, prints: True

Identity Operators

Identity operators check if two variables point to the same object in memory, rather than just comparing their values, ensuring they refer to the exact same instance.

  • Is (is): Returns True if the operands refer to the same object.
  • Is not (is not): Returns True if the operands do not refer to the same object.
x = [1, 2, 3]
y = [1, 2, 3]
z = x

print(x is y)  # Prints: False, because x and y are different objects
print(x is z)  # Prints: True, because x and z refer to the same object
print(x is not y)  # Prints: True, because x and y are different objects

Ternary Operator

The ternary operator is our last, and less comonly used python operators, it allows for conditional expressions in a single line. It’s a shorthand for an if-else statement.

result = value_if_true if condition else value_if_false
x = 10
y = 5

result = "x is greater" if x > y else "y is greater"
print(result)  # Prints: x is greater

Python operators – Conclusion

In conclusion, understanding operators in Python is crucial for writing effective code. For instance, from performing arithmetic to comparing values and manipulating bits, operators allow you to work with data in meaningful ways. By mastering these operators, you’ll gain more control over your programs and improve your ability to express logic efficiently.

Later, we’ll dive deeper into specific operator types and explore how you can use them in more advanced programming scenarios. Happy coding!

Add comment

By Peter

About me

Hi, I’m Peter, a professional developer with over 25 years of experience. My journey with coding started when I was just a kid, exploring the world of programming and building my first projects out of pure curiosity and passion. Since then, I’ve turned this lifelong passion into a rewarding career, working on a wide range of projects, from small scripts to complex applications.

Now, I’m here to help others get started with coding through this blog. I know that learning to code can feel overwhelming at first, but I believe that with the right guidance, anyone can develop the skills they need to become a proficient programmer. My goal is to simplify the learning process and provide step-by-step resources that make coding accessible, fun, and practical for everyone.

Whether you’re just starting out or looking to sharpen your skills, I hope this blog serves as a valuable resource on your coding journey. Let’s dive into Python together!

Get in touch

Have any questions or feedback? Feel free to reach out—I’m always happy to help you on your coding journey!

Tags