Basic Operators

Whenever you write a program in Python, the language offers you a variety of tools to perform arithmetic, logical, and comparison operations efficiently. These tools are called operators, and they form the backbone of manipulating data in your code.

In this lesson, we will explore the basic operators in Python. By the end, you will understand how to use arithmetic, assignment, comparison, logical, and bitwise operators with confidence, which will empower you to write powerful expressions and make decisions in your programs.

Let's dive right in and explore each category with detailed explanations and examples.

Architecture of Basic Operators
Architecture of Basic Operators

Arithmetic Operators

Arithmetic operators allow you to perform mathematical calculations. These are the most common operators you'll encounter when dealing with numbers.

Arithmetic Operators
OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division (always float)5 / 31.666...
//Floor Division (integer quotient)5 // 31
%Modulus (remainder)5 % 32
**Exponentiation5 ** 3125

Notice the subtle differences between / and //. The / operator always returns a floating-point number, even if the division is exact, while // returns the quotient after floor division (i.e., it discards the fractional part).

📌 Deep Dive: Arithmetic Examples

PYTHON
# Basic arithmetic operations
a = 15
b = 4

print("Addition:", a + b)          # 19
print("Subtraction:", a - b)       # 11
print("Multiplication:", a * b)    # 60
print("Division:", a / b)           # 3.75 (float result)
print("Floor Division:", a // b)   # 3 (integer quotient)
print("Modulus:", a % b)            # 3 (remainder)
print("Exponentiation:", a ** b)   # 50625 (15^4)
Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625

Assignment Operators

Assignment operators not only assign values to variables but can also perform operations on the variable and then assign the result back to it. This makes your code concise and readable.

Assignment Operators
OperatorEquivalent To
=Assign value
+=x = x + y
-=x = x - y
*=x = x * y
/=x = x / y
//=x = x // y
%=x = x % y
**=x = x ** y

These compound operators help to simplify and shorten your code when you need to update the value of a variable based on its current value.

📌 Deep Dive: Assignment Operators in Action

PYTHON
x = 10
print("Initial value:", x)

x += 5      # x = x + 5
print("After += 5:", x)

x *= 2      # x = x * 2
print("After *= 2:", x)

x %= 6      # x = x % 6
print("After %= 6:", x)
Output
Initial value: 10
After += 5: 15
After *= 2: 30
After %= 6: 0

Comparison Operators

Comparison operators are essential for decision-making in your programs. They compare two values and return a bool value — either True or False.

Comparison Operators
OperatorMeaningExampleResult
==Equal to5 == 3False
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater than or equal to5 >= 5True
<=Less than or equal to5 <= 3False

Comparison operators are often used in if statements and loops, controlling the flow of your program based on conditions.

📌 Deep Dive: Using Comparison Operators

PYTHON
age = 20

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

print("Is age equal to 20?", age == 20)
print("Is age not equal to 18?", age != 18)
Output
You are an adult.
Is age equal to 20? True
Is age not equal to 18? True

Logical Operators

Logical operators combine multiple boolean expressions and return a boolean value. They are crucial for building complex decision-making conditions.

Logical Operators
OperatorDescriptionExampleResult
andTrue if both operands are TrueTrue and FalseFalse
orTrue if at least one operand is TrueTrue or FalseTrue
notNegates the boolean valuenot TrueFalse

These operators are often used inside conditional statements to check multiple conditions simultaneously.

📌 Deep Dive: Logical Operators in Conditions

PYTHON
username = "admin"
password = "secret"

if username == "admin" and password == "secret":
    print("Access granted.")
else:
    print("Access denied.")

is_logged_in = False
if not is_logged_in:
    print("Please log in first.")
Output
Access granted.
Please log in first.

Bitwise Operators

Bitwise operators work on the binary representation of integers. They are more advanced but extremely useful in certain domains like networking, cryptography, and performance optimization.

Bitwise Operators
OperatorDescriptionExampleResult (Decimal)
&Bitwise AND5 & 31
Bitwise OR5 │ 37
^Bitwise XOR5 ^ 36
~Bitwise NOT (invert all bits)~5-6
<<Left shift bits5 << 110
>>Right shift bits5 >> 12

If you're unfamiliar with binary numbers, don't worry! You can think of bitwise operators as tools that manipulate the "bit patterns" that make up integers behind the scenes.

📌 Deep Dive: Bitwise Operator Usage

PYTHON
x = 5   # binary: 0101
y = 3   # binary: 0011

print("x & y:", x & y)    # 1 (0001)
print("x | y:", x | y)    # 7 (0111)
print("x ^ y:", x ^ y)    # 6 (0110)
print("~x:", ~x)          # -6 (two's complement)
print("x << 1:", x << 1)  # 10 (1010)
print("x >> 1:", x >> 1)  # 2  (0010)
Output
x & y: 1
x | y: 7
x ^ y: 6
~x: -6
x << 1: 10
x >> 1: 2

💡 Understanding Operator Precedence

Python follows a specific order when evaluating expressions with multiple operators, known as operator precedence. For example, multiplication has higher precedence than addition, so 3 + 4 * 2 is evaluated as 3 + (4 * 2) = 11, not (3 + 4) * 2 = 14.

When in doubt, use parentheses to make your code clear and explicit.

Operator Precedence Quick Overview

Here is a simplified list of operator precedence from highest to lowest:

  • Parentheses: ( )
  • Exponentiation: **
  • Unary operators: +x, -x, ~x
  • Multiplication, Division, Floor Division, Modulus: *, /, //, %
  • Addition and Subtraction: +, -
  • Bitwise shifts: <<, >>
  • Bitwise AND: &
  • Bitwise XOR: ^
  • Bitwise OR:
  • Comparison operators: ==, !=, <, >, <=, >=
  • Logical NOT: not
  • Logical AND: and
  • Logical OR: or
  • Assignment operators: =, +=, -=, ...

⚠️ Beware of Confusing Equality and Assignment

Remember, = is an assignment operator, used to assign a value to a variable. The comparison for equality is done with ==. Mixing these two is a common mistake that leads to errors.

Putting It All Together: A Practical Example

Let's create a simple program that calculates the total price of items in a shopping cart, applies a discount, and determines if the total qualifies for free shipping.

📌 Deep Dive: Shopping Cart Total Calculation

PYTHON
# Prices of items in the cart
item1 = 29.99
item2 = 9.99
item3 = 4.99

# Calculate subtotal
subtotal = item1 + item2 + item3

# Apply a 10% discount
discount = 0.10
total_after_discount = subtotal * (1 - discount)

# Check if qualifies for free shipping (total >= 30)
free_shipping = total_after_discount >= 30

print(f"Subtotal: ${subtotal:.2f}")
print(f"Total after discount: ${total_after_discount:.2f}")
print("Free shipping:", free_shipping)

# If not free shipping, add shipping cost
if not free_shipping:
    shipping_cost = 5.99
    total_after_discount += shipping_cost
    print(f"Shipping cost added: ${shipping_cost:.2f}")
    print(f"Final total: ${total_after_discount:.2f}")
else:
    print(f"Final total: ${total_after_discount:.2f}")
Output
Subtotal: $44.97
Total after discount: $40.47
Free shipping: True
Final total: $40.47

This example used arithmetic operators to calculate totals, comparison operators to check if the total qualifies for free shipping, and logical operators to branch logic accordingly.

💡 Tip for Beginners

Practice combining different operators in small programs. Try changing values and adding new conditions to see how operators interact and affect your program's behavior.

Summary

Here’s what you should take away from this lesson:

  • Arithmetic operators perform basic math operations.
  • Assignment operators assign or update variable values succinctly.
  • Comparison operators compare values and return boolean results.
  • Logical operators combine boolean expressions to build complex conditions.
  • Bitwise operators manipulate integers at the binary level.
  • Operator precedence determines how expressions are evaluated; parentheses help control this order.

Mastering these operators is essential for writing effective and efficient Python code. As you continue your coding journey, you’ll use these operators daily to manipulate and compare data, control program flow, and implement logic.