Python Operators

From performing basic arithmetic and comparisons to logical manipulations and bitwise operations, explore the different categories of Python operators that form the building blocks of programming. Mastering these operators equips you to solve problems efficiently, automate tasks, and create interactive programs.

Python-Operators
Table of Contents

Python Operators

Python operators are special symbols that let you perform different actions on values within your code. Think of them like tools in a toolbox: you have operators for doing math (like +, , *), comparing things (like ==, <, >), checking logic (like and, or, not), and even changing the values themselves. Understanding these operators is key to writing Python code that can calculate, solve problems, and make decisions based on the data you give it.

Example Operators in Python

Here’s a comprehensive example that shows the most common Python operators, along with clear comments for explanations:

# Arithmetic Operators
result = 10 + 5  # Addition
result = 20 - 3  # Subtraction
result = 2 * 5   # Multiplication
result = 10 / 2  # True division
result = 15 // 4 # Floor division (rounds down to whole number)
result = 17 % 3  # Modulo (remainder)
result = 2 ** 3  # Exponentiation (2 to the power of 3)

# Comparison Operators
is_equal = 5 == 5        # Equality
is_not_equal = 4 != 2    # Not equal
is_greater = 10 > 8      # Greater than
is_less = 3 < 5          # Less than
is_greater_equal = 6 >= 6  # Greater than or equal to
is_less_equal = 4 <= 4    # Less than or equal to

# Logical Operators
is_true = True and False # Logical AND
is_true = True or False  # Logical OR
is_true = not False      # Logical NOT

# Bitwise Operators
result = 5 & 3  # Bitwise AND
result = 5 | 2  # Bitwise OR
result = ~4     # Bitwise NOT (inverts the bits)
result = 4 ^ 3  # Bitwise XOR (exclusive OR)
result = 12 << 1 # Bitwise left shift (multiplies by 2)
result = 6 >> 1  # Bitwise right shift (divides by 2)

# Assignment Operators
value = 10
value += 5   # Equivalent to value = value + 5
value -= 2   # Equivalent to value = value - 2
value *= 3   # Equivalent to value = value * 3
# ... and others like /=, //=, %=, **=, &=, |=, ^=, <<=, >>=

# Identity Operators
x = 5
y = 5
is_same = x is y    # Checks if objects refer to the same memory location
is_not_same = x is not y  # Checks if objects refer to different memory locations

# Membership Operators
list_data = [1, 2, 3]
is_member = 2 in list_data     # Checks if a value is present in a sequence
is_not_member = 5 not in list_data  # Checks if a value is not in a sequence

Understanding Operands in Python

In Python, operands are the elements you use with operators to perform actions. Imagine them as the ingredients in a recipe, and the operators are the tools you use to cook with them. Operands can be variables, numbers, strings, or even calculations.

  • Variables store values and are referenced by their names (e.g., x, name).
  • Numbers can be integers (whole numbers) or floats (decimals).
  • Strings are text enclosed in quotes (single '' or double "" quotes).

Example

age = 30  # Assign the value 30 (integer) to the variable `age`
message = "Hello, world!"  # Assign the string "Hello, world!" to the variable `message`
total_days = age * 365  # Calculate total days (multiplication)
print(f"{message}. You've lived for {total_days} days.")

Explanation

  • Line 1: Assigns the integer value 30 to the variable age.
  • Line 2: Assigns the string “Hello, world!” to the variable message.
  • Line 3: Calculates total_days by multiplying age (variable) and 365 (integer). Notice the operands involved in the calculation.
  • Line 4: Uses an f-string to print a message that combines the string from message and the calculated total_days.

Output

Hello, world!. You’ve lived for 10950 days.


Understanding Expressions in Python

In Python, expressions are combinations of operands (values) and operators that create a single result. Think of them like a mini-recipe where you follow instructions (operators) using ingredients (operands) to get a final output. These expressions involve variables, numbers, strings, and even function calls.

  • They follow the order of operations (PEMDAS – Parentheses, Exponents, Multiplication and Division from left to right, Addition and Subtraction from left to right).
  • Parentheses can be used to group parts of the expression and control the order of operations.

Example

# Calculate the area of a rectangle (length x width)
length = 5  # Assign length as 5
width = 3  # Assign width as 3
area = length * width  # Calculate area using multiplication

# Calculate the volume of a box (length x width x height)
height = 2  # Assign height as 2
volume = length * width * height  # Notice parentheses around length * width

print(f"The area of the rectangle is: {area}")
print(f"The volume of the box is: {volume}")

Explanation

  • Lines 2-3: Assign values to length and width.
  • Line 4: Calculates the area by multiplying length and width.
  • Lines 7-8: Assign a height and calculate the volume using parentheses to ensure the multiplication of length and width happens before multiplying by height.
  • Lines 10-11: Print the calculated area and volume using f-strings.

Output

The area of the rectangle is: 15
The volume of the box is: 30

Evaluation of Expressions 

In Python, evaluation refers to the process of interpreting an expression and calculating its final result. Imagine you have a complex recipe (the expression) with various steps (operators) and ingredients (operands). Evaluation involves following those steps in the correct order (according to PEMDAS) to arrive at the final dish (the result).

  • PEMDAS order
    Python follows PEMDAS (Parentheses, Exponents, Multiplication, and Division from left to right, Addition, and Subtraction from left to right) during evaluation.
  • Left to right
    Operations are evaluated from left to right within the same precedence level (e.g., multiplication and division).

Example

# Calculate the area of a circle (pi * radius^2)
pi = 3.14  # Assign an approximation of pi
radius = 5  # Assign the radius value

# Area calculation with PEMDAS in mind
area = pi * radius**2  # Exponentiation happens first (radius^2)

print(f"The area of the circle is: {area:.2f}")

Explanation

  • Lines 2-3: Assign values to pi and radius.
  • Line 6: Calculates the area using pi and radius. Notice the exponentiation (**) happening before multiplication (*) due to PEMDAS.
  • Line 7: Prints the area using an f-string with two decimal places.

Output

The area of the circle is: 78.50

Working with Complex Expressions

Complex expressions in Python go beyond simple calculations. They can combine multiple operators, operands (values), and even function calls within parentheses to achieve a more intricate result. Parentheses are crucial here, as they allow you to control the order of operations and ensure the expression is evaluated correctly.

  • Parentheses () group parts of the expression, forcing calculations within them to happen first.
  • Order of Operations (PEMDAS)
    Remember PEMDAS (Parentheses, Exponents, Multiplication and Division from left to right, Addition and Subtraction from left to right) to determine the evaluation order when multiple operators are involved.

Example

# Check if a number is even and divisible by 4
number = 16
is_even = number % 2 == 0  # Check if remainder after division by 2 is 0 (even)
is_divisible_by_four = number % 4 == 0 and is_even  # Combine checks using AND

print(f"{number} is even: {is_even}")
print(f"{number} is divisible by 4: {is_divisible_by_four}")

Explanation

  • Line 2: Assign a value to number.
  • Line 3: Checks if the remainder after dividing number by 2 is 0 using the modulo operator (%).
  • Line 4: This expression checks if number is divisible by 4. It uses the and operator to ensure both conditions (even and divisible by 2) are true.
  • Lines 6-7: Print the results using f-strings.

Output

16 is even: True
16 is divisible by 4: True


Arithmetic Operators in Python

Python’s arithmetic operators are like your mathematical toolkit for calculations. You have addition (+), subtraction (), multiplication (*), and division (/). Additionally, the floor division operator (//) rounds down the result to a whole number, and the modulo operator (%) gives you the remainder after a division. These handy operators are essential for writing Python programs that crunch numbers, compute values, and make decisions based on calculations.

Addition ( + )

The addition operator (+) in Python is your go-to tool for combining numbers or strings.

Syntax

operand1 + operand2

  • operand1: The first value you want to add (can be a number or a string).
  • operand2: The second value you want to add (can be a number or a string).

When adding numbers, it behaves as you’d expect for regular addition. However, if you add strings, Python concatenates (joins) them together.

Example

num1 = 15
num2 = 4
result = num1 + num2  # Add num1 and num2
print(f"Addition: {num1} + {num2} = {result}")

Explanation

  • Line 1: Assigns the value 15 to the variable num1.
  • Line 2: Assigns the value 4 to the variable num2.
  • Line 3: Calculates the sum of num1 and num2, storing the result in the result variable.
  • Line 4: Prints a user-friendly message to the console using an f-string. It displays the values of num1, num2, and the calculated result.

Output

Addition: 15 + 4 = 19

Subtraction ( - )

The subtraction operator () in Python lets you remove one number from another.

Syntax

operand1 operand2

It’s straightforward for calculations, subtracting the second operand from the first.

Example

num1 = 15
num2 = 4
result = num1 - num2  # Subtract num2 from num1
print(f"Subtraction: {num1} - {num2} = {result}")

Explanation

Line 3: Calculates the difference between num1 and num2, storing the result in the result variable.

Output

Subtraction: 15 – 4 = 11

Multiplication ( * )

The multiplication operator (*) in Python comes in handy when you need to multiply numbers.

Syntax

operand1 * operand2

Example

num1 = 15
num2 = 4
result = num1 * num2  # Multiply num1 and num2
print(f"Multiplication: {num1} * {num2} = {result}")

Explanation

Line 3: Multiplies the values in num1 and num2 using the asterisk (*) operator, and assigns the calculation’s result to the variable result.

Output

Multiplication: 15 * 4 = 60

Division ( / )

The division operator (/) in Python performs what you might expect: it divides one number by another. However, the result is always a floating-point number (a decimal value), even if both operands are integers.

Syntax

operand1 / operand2

Example

num1 = 15
num2 = 4
result = num1 / num2  # Divide num1 by num2
print(f"True Division: {num1} / {num2} = {result}")

Explanation

Line 3: Performs true division. It divides num1 by num2 using the forward-slash (/) operator and stores the result (a floating-point number) in the result variable.

Output

True Division: 15 / 4 = 3.75

Modulus ( % )

Python’s modulo operator (%) is a bit trickier but useful! It gives you the remainder after performing a division.

Syntax

operand1 % operand2

Imagine you have a certain number of candies (dividend) and want to share them equally among friends (divisor). The remainder you get using the modulo operator tells you how many candies are leftover after everyone gets a share.

Example

num1 = 15
num2 = 4
result = num1 % num2  # Calculate remainder after dividing num1 by num2
print(f"Modulo: {num1} % {num2} = {result}")

Explanation

Line 3: Calculates the remainder after the division of num1 by num2 using the modulo operator (%) and assigns the result to the variable result.

Output

Modulo: 15 % 4 = 3

Exponentiation ( ** )

The exponentiation operator (**) in Python raises a number (base) to a certain power (exponent).

Syntax

operand1 ** operand2

It’s a shorthand way of writing out repeated multiplication of the base number.

Example

num1 = 15
num2 = 4
result = num1 ** 2    # Raise num1 to the power of 2 (num1 * num1)
print(f"Exponentiation: {num1} ** 2 = {result}")

Explanation

Line 3: Calculates the square of num1 (raises num1 to the power of 2) using the exponentiation operator (**) and stores the result in the result variable.

Output

Exponentiation: 15 ** 2 = 225

Floor Division ( // )

The floor division operator (//) in Python comes in handy when you need to divide numbers and discard any remainder, rounding down to the nearest whole number.

Syntax

operand1 // operand2

Example

num1 = 15
num2 = 4
result = num1 // num2  # Divide num1 by num2 (disregard remainder)
print(f"Floor Division: {num1} // {num2} = {result}")

Explanation

Line 3: Performs floor division. It divides num1 by num2 using the double forward-slash (//) operator, discards any remainder and stores the integer quotient in the result variable.

Output

Floor Division: 15 // 4 = 3


Comparison Operators in Python

Python’s comparison operators allow you to compare values and determine their relationship. You can use them to check if one value is equal to another (==), greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=), or not equal (!=). These operators are either True or False, making them essential for conditional logic in your programs.

Equal ( == )

Python’s equal operator (==) checks whether two values are identical.

Syntax

operand1 == operand2

It returns True if the values are equal and False otherwise.

Example

value1 = 20
value2 = 10
is_equal = value1 == value2  # Check if value1 is equal to value2
print(f"{value1} == {value2}: {is_equal}")

Explanation

  • Line 1: Assigns the value 20 to the variable value1.
  • Line 2: Assigns the value 10 to the variable value2.
  • Line 3: Tests if value1 is equal to value2 using the == operator, storing the Boolean result (True or False) in is_equal.
  • Line 4: Prints the values compared (value1 and value2), the comparison symbol (==), and the comparison result (is_equal).

Output

20 == 10: False

Not Equal ( != )

The not equal operator (!=) in Python does the opposite of the equal operator. It checks if two values are different.

Syntax

operand1 != operand2

It returns True if the values are not equal and False otherwise. This can be useful for identifying unequal values or making decisions based on differences.

Example

value1 = 20
value2 = 10
is_not_equal = value1 != value2  # Check if value1 is not equal to value2
print(f"{value1} != {value2}: {is_not_equal}")

Explanation

Line 3: Compares if value1 is not equal to value2 using the not equal to operator (!=). The result (True or False) is stored in the variable is_not_equal.

Output

20 != 10: True

Greater Than ( > )

The greater than operator (>) in Python helps you determine if one value is larger than another.

Syntax

operand1 > operand2

Example

value1 = 20
value2 = 10
is_greater = value1 > value2  # Check if value1 is greater than value2
print(f"{value1} > {value2}: {is_greater}")

Explanation

Line 3: Uses the greater than operator (>) to check if value1 is greater than value2. The comparison result (True or False) is stored in the is_greater variable.

Output

20 > 10: True

Less Than ( < )

The less than operator (<) in Python works the other way around than the greater than operator. It checks if one value is smaller than another.

Syntax

operand1 < operand2

Example

value1 = 20
value2 = 10
is_less = value1 < value2  # Check if value1 is less than value2
print(f"{value1} < {value2}: {is_less}")

Explanation

Line 3: Uses the less than operator (<) to compare if value1 is less than value2. The result of this comparison (True or False) is stored in the is_less variable.

Output

20 < 10: False

Greater Than or Equal To ( >= )

The greater than or equal to operator (>=) in Python lets you check if one value is strictly greater than or equal to another. 

Syntax

operand1 >= operand2

Example

value1 = 20
value2 = 10
is_greater_or_equal = value1 >= value2  # Check if value1 is greater than or equal to value2
print(f"{value1} >= {value2}: {is_greater_or_equal}")

Explanation

Line 3: Uses the greater than or equal to operator (>=) to check if value1 is either greater than or equal to value2. The result of this comparison (True or False) is stored in the variable is_greater_or_equal.

Output

20 >= 10: True

Less Than or Equal To ( <= )

The less than or equal to operator (<=) in Python comes in handy when you need to check if a value is strictly less than another value or equal to it.

Syntax

operand1 <= operand2

Example

value1 = 20
value2 = 10
is_less_or_equal = value1 <= value2  # Check if value1 is less than or equal to value2
print(f"{value1} <= {value2}: {is_less_or_equal}")

Explanation

Line 3: Uses the less than or equal to operator (<=) to determine if value1 is less than or equal to value2. The Boolean result (True or False) is stored in the variable is_less_or_equal.

Output

20 <= 10: False


Logical Operators in Python (and, or, not)

Logical operators in Python allow you to combine and manipulate conditions to make more complex decisions within your code. The three main ones are and, or, and not. Think of them as tools for connecting and evaluating statements that result in True or False. The and operator requires both conditions to be True for the overall result to be True. The or operator is more flexible, requiring at least one condition to be True for a True result. Lastly, the not operator flips things around, reversing the True/False value of a condition.

The and Operator

The and operator in Python acts like a strict bouncer in your code, ensuring only scenarios that meet all conditions get the True pass.

Syntax

operand1 and operand2

Both operand1 and operand2 need to be True for the entire expression using and to evaluate to True.

Example

is_sunny = True
is_warm = False
feels_like_summer = True
perfect_weather = is_sunny and is_warm  # Sunny and warm
print(f"Is it perfect weather? {perfect_weather}")

Explanation

  • Line 1: Assigns True to is_sunny, indicating a sunny day.
  • Line 2: Assigns False to is_warm, indicating it’s not warm outside.
  • Line 3: Assigns True to feels_like_summer, representing a general feeling.
  • Line 4: Uses the and operator to check for perfect weather (both sunny and warm). The result is False (since is_warm is False) and is stored in perfect_weather.
  • Line 5: Prints a message asking if it’s perfect weather, displaying the outcome from perfect_weather.

Output

Is it perfect weather? False

The or Operator

The or operator in Python is more lenient than the and operator. It’s like having two doors to enter your code block; as long as at least one condition is True, access is granted (the result is True).

Syntax

operand1 or operand2

Example

is_sunny = True
is_warm = False
feels_like_summer = True
enjoyable_outside = is_sunny or is_warm  # Either sunny or warm
print(f"Is it enjoyable outside? {enjoyable_outside}")

Explanation

Line 4: Uses the or operator to check if it’s enjoyable outside based on whether it’s sunny or warm. The result (True in this case) is stored in the enjoyable_outside variable.

Output

Is it enjoyable outside? True

The not Operator

The not operator in Python works like a toggle switch for truth values. It flips the outcome of a single condition from True to False and vice versa.

 Syntax

not operand

The not operator works by itself, taking only one operand (condition) and returning the opposite Boolean value.

Example

is_sunny = True
is_warm = False
feels_like_summer = True
going_swimming = not feels_like_summer  # If it doesn't feel like summer
print(f"Going swimming? {going_swimming}")

Explanation

Line 4: Uses the not operator to reverse the value of feels_like_summer. Since it currently holds True, the result is False and is stored in going_swimming.

Output

Going swimming? False


Bitwise Operators in Python

Python’s bitwise operators allow you to delve into the nitty-gritty of numbers by directly manipulating the individual bits (0s and 1s) that represent them at the lowest level. Think of them as specialized tools to perform operations on the “building blocks” of your data. These operators include bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise NOT (~), and shifts (<<, >>). They often find use in fields like computer networking, low-level programming, and encryption, where bit-level control is necessary.

Bitwise AND (&)

In Python, the bitwise AND operator (&) compares corresponding bits within two numbers. Think of each operand (number) as having a row of lightbulbs representing its bits (0s and 1s). The operator checks pairs of bulbs from both rows. If both bulbs in a pair are lit (both bits are 1), the resulting bit in the answer will also be a 1. Otherwise, it becomes 0.

Syntax

operand1 & operand2

operand1 and operand2: The numbers you want to perform the bitwise AND operation on.

Example

# Example numbers (represented in binary)
num1 = 10  # 00001010
num2 = 5   # 00000101
result = num1 & num2
print(f"Bitwise AND ({num1} & {num2}): {result}")  # Output: 0

Explanation

  • Line 1: Comment explaining that the following numbers are represented in binary.
  • Line 2: Assigns the decimal 10 (binary 00001010) to num1.
  • Line 3: Assigns the decimal 5 (binary 00000101) to num2.
  • Line 4: Performs a bitwise AND on num1 and num2, storing the result (0) in result.
  • Line 5: Prints the bitwise AND operation, the original numbers (num1, num2), and the result.

Output

Bitwise AND (10 & 5): 0

Bitwise OR ( | )

Imagine two flashlights signaling messages in a dark room, one with a beam (1) and one with an off beam (0). Python’s bitwise OR operator (|) combines bits from two numbers like those flashlights. Here’s the syntax:

Syntax

operand1 | operand2

It checks each bit position in the operands. If at least one bit in a position is 1 (flashlight beam on), the corresponding bit in the result is also 1. If both bits are 0 (both flashlights off), only then is the result bit a 0.

Example

num1 = 10  # 00001010
num2 = 5   # 00000101
result = num1 | num2
print(f"Bitwise OR ({num1} | {num2}): {result}")  # Output: 15

Explanation

Line 3: Performs a bitwise OR operation between num1 and num2. The result (decimal 15) is stored in the variable result.

Output

Bitwise OR (10 | 5): 15

Bitwise XOR ( ^ )

The bitwise XOR operator (^) in Python acts like a guard for bits, checking IDs (0s and 1s) at the bitwise door. Here’s the syntax:

Syntax

operand1 ^ operand2

For each bit position in the operands, the XOR operator lets only one bit through:

  • If only one of the bits in a position is 1 (one has ID, the other doesn’t), the result bit is also 1.
  • If both bits are 0 or both are 1 (both lack ID or both have ID), the result bit becomes 0.

Example

num1 = 10  # 00001010
num2 = 5   # 00000101
result = num1 ^ num2
print(f"Bitwise XOR ({num1} ^ {num2}): {result}")  # Output: 15

Explanation

Line 3: Performs a bitwise XOR operation on num1 and num2. The result (decimal value 15) is stored in the result variable.

Output

Bitwise XOR (10 ^ 5): 15

Bitwise NOT ( ~ )

The bitwise NOT operator (~) in Python works like a bitwise inverter, flipping the individual bits (0s and 1s) of a single number. Imagine a row of switches representing the number’s bits (on for 1, off for 0). The NOT operator flips the state of each switch. If a switch is currently on (1), it becomes off (0), and vice versa.

Syntax

~operand

Example

num1 = 10  # 00001010
num2 = 5   # 00000101
result = ~num1
print(f"Bitwise NOT (~{num1}): {result}")  # Output: -11 (using two's complement)

Explanation

Line 3: Applies the bitwise NOT operator (~) to the value in num1. This inverts each bit (turning 0s to 1s and vice versa) and stores the result in the variable result.

Output

Bitwise NOT (~10): -11

Bitwise Left Shift ( << )

In Python, the bitwise left shift operator (<<) acts like a bit-shifter, moving the bits in a number to the left by a certain number of positions. Imagine a row of dominoes representing the number’s bits (0 or 1 on the domino face). Shifting left moves all the dominoes to the left, and depending on how many positions are specified:

  • Zeros are filled in on the newly vacant rightmost positions.
  • Any bits that fall off the left end are discarded.

Syntax

operand1 << operand2

Example

num1 = 10  # 00001010
num2 = 5   # 00000101
result = num1 << 1
print(f"Bitwise Left Shift ({num1} << 1): {result}")  # Output: 20

Explanation

Line 3: Performs a bitwise left shift operation on num1 by 1 position. This shifts the bits one place to the left, adding a zero in the rightmost position, and the result is stored in result.

Output

Bitwise Left Shift (10 << 1): 20

Bitwise Right Shift ( >> )

Python’s bitwise right shift operator (>>) acts like a bit mover, nudging the bits in a number to the right by a specified amount. Picture a row of marbles representing the number’s bits (0 or 1). Shifting right moves the marbles to the right, and here’s what happens:

  • Bits on the far right that fall off are discarded.
  • For positive numbers, zeros are filled in on the newly vacated leftmost positions.

Note: For negative numbers (represented in two’s complement), the sign bit (leftmost bit) is replicated to fill the empty left positions during the shift.

Syntax

operand1 >> operand2

Example

num1 = 10  # 00001010
num2 = 5   # 00000101
result = num2 >> 1
print(f"Bitwise Right Shift ({num2} >> 1): {result}")  # Output: 2

Explanation

Line 3: Performs a bitwise right shift operation on num2 by one position. This shifts the bits in num2 one place to the right, filling in a zero on the leftmost side, and storing the outcome in result.

Output

Bitwise Right Shift (5 >> 1): 2


Assignment Operators in Python

The most common one is the equals sign (=), which takes a value on the right side and assigns it to a variable on the left. This is like putting an item into a labeled box (the variable). Python also has a bunch of other handy assignment operators that combine arithmetic operations with assignment to save on code space. Examples include adding and assigning (+=), subtracting and assigning (-=), and more!

Basic Assignment Operator (=)

Python’s basic assignment operator (=) acts like a label maker in your code. It’s used to assign values to variables. Here’s the syntax:

Syntax

variable_name = value

  • variable_name: The name you choose for your variable (like a label for a box).
  • value: The data you want to store in the variable (the thing that goes in the box).

Example

age = 30
name = "Alice"
is_raining = True

Explanation

  • Line 1: Assigns the value 30 (an integer) to the variable age.
  • Line 2: Assigns the string “Alice” to the variable name.
  • Line 3: Assigns the Boolean value True to the variable is_raining.

Add and Assign Operator (+=)

The add and assign operator (+=) in Python combines adding and assigning in one step, like an express lane for calculations. Imagine you have a variable with a value, and you want to add something to it. Here’s the syntax:

Syntax

variable_name += value

This is the same as writing variable_name = variable_name + value, but it’s shorter. It adds the value to what’s already in the variable and stores the result back in the same variable, effectively updating its value.

Example

value = 10
# Add and assign (value becomes value + 5)
value += 5  
print(f"After += 5: {value}")  # Output: 15

Explanation

  • Line 1: Assigns the initial value 10 to the variable value.
  • Line 2: Comment (ignored by the computer) explaining the next line.
  • Line 3: Uses the += operator to add 5 to value and update its value (equivalent to value = value + 5).
  • Line 4: Prints the updated value (15) along with a descriptive message.

Output

After += 5: 15

Subtract and Assign Operator (-=)

In Python, the subtract and assign operator (-=) acts like a shortcut for updating a variable’s value by subtracting something from it. Here’s the syntax:

Syntax

variable_name -= value

Example

value = 10
# Subtract and assign (value becomes value - 2)
value -= 2  
print(f"After -= 2: {value}")  # Output: 13

Explanation

Line 3: Uses the -= operator to subtract 2 from the current value stored in value and then updates the variable with the result (equivalent to writing value = value - 2).

Output

After -= 2: 13

Multiply and Assign Operator (*=)

The multiply and assign operator (*=) in Python is a time-saver that combines multiplication and assignment into a single step. Here’s the syntax:

Syntax

variable_name *= value

Example

value = 10
# Multiply and assign (value becomes value * 3)
value *= 3  
print(f"After *= 3: {value}")  # Output: 39

Explanation

Line 3: Uses the *= operator to multiply value by 3 and assigns the result (30) back to value.

Output

After *= 3: 39

Divide and Assign Operator (/=)

Python’s divide and assign operator (/=) acts like an express lane for division and assignment calculations. Imagine you have a variable storing a value and want to divide it by another number and update the variable with the result. Here’s the syntax:

Syntax

variable_name /= value

It’s important to remember that this operator works with both whole numbers (integers) and floating-point numbers (decimals).

Example

value = 10
# Divide and assign (value becomes value / 2)
value /= 2  
print(f"After /= 2: {value:.1f}")  # Output: 19.5 (float division)

Explanation

Line 3: Uses the /= operator to divide value by 2. This performs float division and updates the value variable with the result (5.0).

Output

After /= 2: 19.5

Modulus and Assign Operator (%=)

Python’s modulus and assign operator (%= ) is handy for keeping track of remainders after division. Imagine you have a variable storing several items and want to know how many would be leftover after dividing by a certain amount. Here’s the syntax:

Syntax

variable_name %= value

Example

value = 10
# Modulo and assign (value becomes value % 3)
value %= 3  
print(f"After %= 3: {value}")  # Output: 1 (remainder)

Explanation

Line 3: Uses the modulo and assign operator (%=). This calculates the remainder when value is divided by 3 (which is 1) and stores that remainder back into the value variable.

Output

After %= 3: 1.0

Exponent and Assign Operator (**=)

The exponent and assign operator (**=) in Python streamlines raising a variable’s value to power and reassigning it. Imagine you have a variable storing a number and want to repeatedly multiply it by a specific number of times. Here’s the syntax:

Syntax

variable_name **= value

Example

value = 10
# Raise to a power and assign (value becomes value ** 2)
value **= 2  
print(f"After **= 2: {value}")  # Output: 1 (exponent)

Explanation

Line 3: Uses the exponent and assign operator (**=). This raises value to the power of 2 (value squared) and stores the result (100) back into the value variable.

Output

After **= 2: 1.0

Floor Divide and Assign Operator (//=)

Python’s floor divide and assign operator (//=) is like a shortcut for integer division and updating a variable. It discards any fractional remainders, focusing solely on the whole number result. Here’s the syntax:

Syntax

variable_name //= value

Example

value = 10
# Floor divide and assign (value becomes value // 4)
value //= 4  
print(f"After //= 4: {value}")  # Output: 4 (integer division)

Explanation

Line 3: Uses the floor divide and assign operator (//=). This performs integer division (discards the remainder) when dividing value by 4, and the result (2) is assigned back to value.

Output

After //= 4: 4.0


Identity Operators in Python (is, is not)

Identity operators in Python, specifically is and is not, act like detectives specializing in object identities rather than their values. They compare whether two objects or variables refer to the same spot in your computer’s memory. This differs from the equality operator (==), which compares if two things have the same contents. Think of it like this: the is operator checks if two names are attached to the same individual, while == checks if two people look similar.

The is Operator

The is operator in Python acts like a strict identity checker. It verifies if two references (variable names) point to the same object in memory. Imagine two boxes; the is operator checks if they’re the same box, not just if they contain the same things. Here’s the syntax:

Syntax

operand1 is operand2

operand1 and operand2: The variables or expressions you want to compare.

Example

# Create two lists with the same contents
list1 = [1, 2, 3]
list2 = [1, 2, 3]

# Create two integers with the same value
num1 = 5
num2 = 5

# Check identity: same object in memory?
print(list1 is list2)  # False - Different lists despite the same contents
print(num1 is num2)    # True - Integers with the same value often share memory space

Explanation

  • Lines 1-2: Creates two separate lists (list1, list2) with identical contents ([1, 2, 3]). Despite looking the same, they occupy different places in memory.
  • Lines 4-5: Assigns the value 5 to both num1 and num2.
  • Line 7: Prints False because list1 is list2 compares object identity (memory location), not just contents.
  • Line 8: Prints True (likely) because Python often reuses memory space for small integers, so num1 is num2 is comparing the same object.

Output

False
True

The is not Operator

The is not operator in Python works like the opposite of the is operator. It acts as a loose identity checker, verifying if two references (variable names) don’t point to the same object in memory. Imagine two boxes; the is not operator checks if they are different boxes, even if they contain the same things. Here’s the syntax:

Syntax

operand1 is not operand2

The result is True if the objects are not the same in memory and False otherwise. It focuses on object identity, not value equality.

Example

list1 = [1, 2, 3]
list2 = [1, 2, 3]
num1 = 5
num2 = 5

# Check for non-identity
print(list1 is not list2)  # True 
print(num1 is not num2)    # False

Explanation

  • Line 7: Prints True because list1 is not list2 correctly confirms the lists are not the same object in memory (different containers even though the contents are the same).
  • Line 8: Prints False (likely). Since num1 and num2 reference the same integer object in memory, the check for non-identity fails.

Output

True
False


Membership Operators  in Python (in, not in)

Python’s membership operators (in and not in) are like guards. They check if a specific value is a member (present) in a sequence like a list, string, or tuple. The in operator gives a thumbs up (True) if the value is found within the sequence. The not in operator does the opposite, signaling thumbs down (False) if the value is absent from the sequence. Think of them as answering the questions: “Is this item on the list?” or “Is this item NOT on the list?

The in Operator

The in operator in Python acts like a membership checker. Imagine you have a collection of items, like a basket of fruits. You can use in to see if a specific item is present in that collection. Here’s the syntax:

Syntax

item in collection

  • item: The value you’re searching for (the specific fruit).
  • collection: The collection you’re searching within (the basket of fruits).

The result is True if the item is found in the collection and False otherwise.

Example

# A list of fruits
fruits = ["apple", "banana", "orange"]

# Check if a fruit is in the list (membership)
print("mango" in fruits)   # False - not in the list
print("banana" in fruits)  # True -  found in the list

Explanation

  • Line 2: Creates a list fruits storing strings: ‘apple‘, ‘banana‘, ‘orange‘.
  • Line 5: Prints False – ‘mango‘ is not found in the fruits list.
  • Line 6: Prints True – ‘banana‘ is present within the fruits list.

Output

False
True

The not in Operator

The not in operator in Python works alongside the in operator but with the opposite logic. It acts like a “not in the club” checker for collections. Imagine you have a group of members and want to see if someone is not on the list. Here’s the syntax:

Syntax

item not in collection

The result is True if the item is not found in the collection and False otherwise. It’s useful for finding things excluded from a set or list.

Example

fruits = ["apple", "banana", "orange"]

print(5 not in fruits)     # True - number not in the fruit list
print("apple" not in fruits)  # False - the fruit is in the list

Explanation

  • Line 3: Prints True 5 is correctly not found in the fruits list.
  • Line 4: Prints False – “apple” is correctly found in the fruits list (meaning it is not absent).

Output

True
False


Exponentiation (**) and Unary Operators in Python

Python offers several operators that change or analyze a single value. The most common ones include the exponentiation operator (**), which helps you calculate powers (e.g., 3 raised to the power of 4), and the unary operators. Unary operators come in two flavors: the positive operator (+), which mostly just confirms a number as positive, and the negative operator (), which flips the sign of a number (positive to negative, and vice versa). Unary operators work on only one operand (number) and sit directly in front of it.

Exponent Operator ( ** )

The exponent operator (**) in Python is your shortcut for repeated multiplication. Imagine you have a number and want to multiply it by itself a certain number of times. Here’s the syntax:

Syntax

base ** exponent

  • base: The number you want to multiply (like the growth rate).
  • exponent: The number of times to multiply by itself (like how many times it grows).

Calculates base to the power of exponent. For example, 2 ** 3 is the same as 2 * 2 * 2.

Example

# Calculate the square of 5 (5 to the power of 2)
result = 5 ** 2
print(f"5 squared: {result}")  # Output: 25

# Calculate the cube of 3 (3 to the power of 3)
result = 3 ** 3
print(f"3 cubed: {result}")    # Output: 27

Explanation

  • Line 1: Comment explaining the upcoming calculations.
  • Line 2: Calculates 5 squared (5 ** 2) and stores the result (25) in the result variable.
  • Line 3: Prints “5 squared: 25” using an f-string.
  • Line 6: Calculates 3 cubed (3 ** 3) and stores the result (27) in the result variable.
  • Line 7: Prints “3 cubed: 27” using an f-string.

Output

5 squared: 25
3 cubed: 27

Caret Operator ( ^ )

The caret operator (^) in Python performs a bitwise exclusive OR (XOR) operation on integers. Imagine having two lights, one representing 1s and the other 0s. The XOR operation turns on a light only if the corresponding bits in the two numbers are different. Here’s the syntax:

Syntax

operand1 ^ operand2

operand1 and operand2: The integers you want to perform the bitwise XOR on (like the two sets of lights).

For example, 10 ^ 3 (in binary, 1010 ^ 0011) results in 13 (in binary, 1101) because the bits in positions 1 and 4 are different (1 XOR 0 is 1).

Example

result = 10 ^ 3  # Perform bitwise XOR on 10 and 3
print(result)      # Output: 13

Explanation

  • Line 1: Assigns the result of the bitwise XOR operation between 10 and 3 (10 ^ 3) to the result variable.
  • Line 2: Prints the result, which is 13.

Unary Plus and Minus Operators

Python offers two unary operators: the positive (+) and the negative () signs. While the negative unary operator changes a number’s sign, the positive unary operator has a more subtle effect. It largely confirms that a number is already positive (often leaving it unchanged) but can be used in certain situations to force a non-numeric value to become a number if possible. The negative unary operator works to flip a positive number to a negative and vice versa.

Unary Plus Operator ( + )

Python’s unary plus operator (+) acts like a neutral observer for numbers. Unlike mathematical plus for addition, it doesn’t change the value of a positive number. It says, “Hey, this is already a positive number.” Here’s the syntax:

Syntax

+operand

While seemingly redundant for positive numbers, it can be useful in specific situations, like forcing a conversion to a numeric value.

Example

x = +10  # The plus sign has no effect here
y = +"hello"  # Attempt to convert "hello" to a number (causes an error)
print(x)  # Output: 10
# print(y)  # This line will cause an error because "hello" cannot be converted to a number

Explanation

  • Line 1: Assigns the value 10 to x. The unary plus has no effect here.
  • Line 2: Tries to convert the string “hello” to a number using the unary plus. This will cause a TypeError because “hello” cannot be converted to a numerical value.
  • Line 3: Prints the value of x, which is 10.

Unary Minus Operator ( - )

The unary minus operator () in Python flips the sign of a number. It essentially acts like a minus sign in front of a number without needing another operand. Here’s the syntax:

Syntax

-operand

This operator is handy for quickly making positive numbers negative and vice versa.

Example

x = 10
y = -x  # Negate the value of x
print(f"x: {x}, y: {y}")  # Output: x: 10, y: -10

Explanation

  • Line 1: Assigns the value 10 to x.
  • Line 2: Assigns the negation of x to y. The unary minus operator flips the sign, so -10 is stored in y.
  • Line 3: Uses an f-string to print the values of x and y.

Unary Tilde Operator ( ~ )

The unary tilde operator (~) in Python delves into bitwise operations, acting like a bitwise NOT. Imagine a series of switches (0s and 1s) representing a number in binary. The tilde operator flips all the bits: 0s become 1s, and 1s become 0s. Here’s the syntax:

Syntax

~operand

Remember that this operation works on binary representations of integers, so a basic understanding of binary can be helpful.

Example

x = 10  # In binary, 1010
y = ~x  # Flips all the bits (0101)
print(f"x: {x}, y: {y}")  # Output: x: 10, y: -11 (one's complement interpretation)

Explanation

  • Line 1: Assigns the value 10 to x. In binary, 10 is represented as 1010.
  • Line 2: Applies the bitwise NOT operation to x using the tilde operator (~). This flips all the bits, resulting in 0101 in binary.
  • Line 3: Prints the values of x and y. While y shows -11, it’s due to one’s complement interpretation (inverting bits and adding 1). The actual binary value of y is 0101, which is 5 in decimal.

Advanced Concepts of Python Operators

While Python’s basic operators handle common mathematical and comparison tasks, the language offers more powerful tools for advanced scenarios. You can override the behavior of these operators for custom data types like classes, a concept called operator overloading. Python also provides the bitwise operators (&, |, ~, ^, <<, >>) for manipulating numbers at the bit level. The walrus operator (:=), introduced in Python 3.8, embeds assignments within expressions. Additionally, Python’s operator module provides functions corresponding to standard operators, giving you more flexibility for specialized use cases.

The Walrus Operator ( := )

The walrus operator, introduced in Python 3.8, is a handy shortcut for assigning values while writing expressions. Think of it as a way to catch a value (“walrus“) while the expression (“water“) flows around it.

Syntax

walrus_operator := expression

  • walrus_operator (can be any valid variable name): Assigns the result of the expression to this variable.
  • expression: The calculation or operation that produces a value.

It reduces the need for temporary variables, making your code more concise.

Example

# Check if a number is even using the walrus operator

number = 10
is_even = number % 2 == 0  # Traditional even check (multiple lines)

# Achieve the same result with the walrus operator (one line)
number = 12
is_even := number % 2 == 0  

print(f"{number} is even: {is_even}")

Explanation

  • Line 1: Assigns the value 10 to the variable number.
  • Lines 3-4: Traditional way to check if a number is even. It involves a modulo operation (%) to find the remainder, compare it to zero using the equality operator (==). The result is stored in is_even.
  • Lines 6-7: Achieves the same even number check with the walrus operator. Here, the modulo operation and equality check are part of the expression. The result is assigned directly to is_even while assigning 12 to number.
  • Line 8: Prints a message indicating if the number is even based on the is_even variable.

Short-Circuit Evaluation

Python’s short-circuit evaluation is a behind-the-scenes optimization technique for logical expressions (those using and or or). It improves efficiency by stopping the evaluation as soon as the overall result is determined. Imagine a series of interconnected lights in a circuit; if the first light is off and you know everything connected after it will be off too, there’s no need to turn on the rest!

Syntax

operand1 [and/or] operand2 [and/or] operand3…

  • operand: The conditions (True or False) you want to evaluate.
  • and/or: The logical operators that connect the conditions.

Short-circuit evaluation works with the and and or operators. It stops evaluating after:

  • A False is encountered with and (since the entire expression is False regardless).
  • A True is encountered with or (since the entire expression is True already).

Example

# Short-circuit evaluation with login access check

is_logged_in = False  # Not logged in
has_permission = True  # Has permission (but irrelevant here)

# Traditional check (might evaluate has_permission unnecessarily)
can_access = is_logged_in and has_permission

# Using short-circuit evaluation (stops after is_logged_in is False)
can_access := is_logged_in and has_permission

print(f"Can access the resource? {can_access}")

Explanation

  • Lines 1-2: Assign False to is_logged_in (indicating not logged in) and True to has_permission (which won’t matter in this case).
  • Lines 4-5: Traditional approach using and. This would evaluate both is_logged_in and has_permission even though is_logged_in is False.
  • Lines 7-8: Leverages the walrus operator (:=) with short-circuit evaluation. Since is_logged_in is False, the expression stops there and assigns False to can_access without checking has_permission.
  • Line 9: Prints a message indicating access permission based on can_access.

Operator Precedence in Python

Operator precedence in Python dictates how operations within an expression are evaluated. It’s like having a set of rules to avoid confusion when multiple calculations are mixed together. Like following the order of operations (PEMDAS) in math, Python follows a hierarchy for its operators. Higher precedence operators are evaluated first, ensuring the correct outcome.

Syntax

operand1 operator1 operand2 operator2 operand3 …

  • operand: The values (numbers, variables) involved in the calculations.
  • operator: The mathematical symbols that perform operations (+, , *, /, etc.) or logical comparisons (==, !=, <, >, etc.).

Here’s a breakdown of the precedence order (from highest to lowest):

  1. Exponentiation (**)
  2. Multiplication and Division (*, /)
  3. Addition and Subtraction (+, )
  4. Comparison operators (==, !=, <, >, <=, >=)
  5. Logical NOT operator (not)
  6. Logical AND operator (and)
  7. Logical OR operator (or)

Note: Operators with the same precedence are evaluated from left to right.

Example

# Expression with mixed operators and parentheses

result = 2 + 3 * 4 - (10 / 2) ** 2  # PEMDAS wouldn't work here!

print(f"The result: {result}")

Explanation

  • Line 2: The expression involves calculations with different operators. Without proper precedence, the answer might be wrong.
  • Line 3: Parentheses are used to group operations and force the evaluation order. Here, the exponentiation inside the parentheses happens first (10 / 2 becomes 5, then 5 squared is 25).
  • Line 3 (continued): Then, multiplication (3 * 4) is done before addition and subtraction, following left-to-right associativity within the remaining calculation.
  • Line 4: Prints the final result, which is 7 (not 11 as you might get with incorrect operator order).

Output

The result: -11.0