Operators

Python Operators

Operators in Python

Operators are special symbols or keywords that perform operations on one or more operands. Python provides a rich set of operators for various purposes.

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations.

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division (float result)5 / 3 = 1.6666667
//Floor Division (integer result)5 // 3 = 1
%Modulus (remainder)5 % 3 = 2
**Exponentiation5 ** 3 = 125

Examples:

a, b = 10, 3

print(f"Addition: {a + b}")        # Output: 13
print(f"Subtraction: {a - b}")     # Output: 7
print(f"Multiplication: {a * b}")  # Output: 30
print(f"Division: {a / b}")        # Output: 3.3333333333333335
print(f"Floor Division: {a // b}") # Output: 3
print(f"Modulus: {a % b}")         # Output: 1
print(f"Exponentiation: {a ** b}") # Output: 1000

Note: The division operator (/) always returns a float, even if the result is a whole number. Use floor division (//) if you need an integer result.

2. Unary Operators

Unary operators work with a single operand.

OperatorDescriptionExample
-Negation-5
+Positive (no effect)+5

Examples:

x = 5
print(f"Negation: {-x}")  # Output: -5
print(f"Positive: {+x}")  # Output: 5

# Unary operators with expressions
y = 10
print(f"Negation of expression: {-(x + y)}")  # Output: -15

Note: The unary + operator is rarely used as it doesn't change the value. It's included mainly for completeness and symmetry with the - operator.

3. Assignment Operators

Assignment operators are used to assign values to variables.

OperatorDescriptionExampleEquivalent to
=Simple assignmentx = 5-
+=Add and assignx += 3x = x + 3
-=Subtract and assignx -= 3x = x - 3
*=Multiply and assignx *= 3x = x * 3
/=Divide and assignx /= 3x = x / 3
//=Floor divide and assignx //= 3x = x // 3
%=Modulus and assignx %= 3x = x % 3
**=Exponentiate and assignx **= 3x = x ** 3

Examples:

x = 10
print(f"Initial x: {x}")  # Output: 10

x += 5
print(f"After x += 5: {x}")  # Output: 15

x -= 3
print(f"After x -= 3: {x}")  # Output: 12

x *= 2
print(f"After x *= 2: {x}")  # Output: 24

x /= 4
print(f"After x /= 4: {x}")  # Output: 6.0

x //= 2
print(f"After x //= 2: {x}")  # Output: 3.0

x %= 2
print(f"After x %= 2: {x}")  # Output: 1.0

x **= 3
print(f"After x **= 3: {x}")  # Output: 1.0

Note: Assignment operators modify the variable in-place. They're a shorthand for longer expressions and can make code more readable.

4. Comparison Operators

Comparison operators are used to compare values. They return Boolean results (True or False).

OperatorDescriptionExample
==Equal to5 == 5 returns True
!=Not equal to5 != 4 returns True
<Less than3 < 5 returns True
>Greater than5 > 3 returns True
<=Less than or equal to3 <= 3 returns True
>=Greater than or equal to5 >= 5 returns True

Examples:

a, b = 10, 5

print(f"a == b: {a == b}")  # Output: False
print(f"a != b: {a != b}")  # Output: True
print(f"a < b: {a < b}")    # Output: False
print(f"a > b: {a > b}")    # Output: True
print(f"a <= b: {a <= b}")  # Output: False
print(f"a >= b: {a >= b}")  # Output: True

# Comparison chaining
x = 5
print(f"1 < x < 10: {1 < x < 10}")  # Output: True

Note: Python allows comparison chaining, which is a concise way to write multiple comparisons in a single expression.

5. Logical Operators

Logical operators are used to combine conditional statements.

OperatorDescriptionExample
andReturns True if both statements are truex < 5 and x < 10
orReturns True if one of the statements is truex < 5 or x < 4
notReverses the result, returns False if the result is truenot(x < 5 and x < 10)

Examples:

x = 5
y = 10

print(f"x < 10 and y > 5: {x < 10 and y > 5}")  # Output: True
print(f"x > 10 or y > 5: {x > 10 or y > 5}")    # Output: True
print(f"not(x < 10): {not(x < 10)}")            # Output: False

# Short-circuit evaluation
def true_func():
    print("true_func called")
    return True

def false_func():
    print("false_func called")
    return False

print(f"false_func() and true_func(): {false_func() and true_func()}")
# Output: false_func called
#         False

print(f"true_func() or false_func(): {true_func() or false_func()}")
# Output: true_func called
#         True

Note: Python uses short-circuit evaluation for logical operators. In and operations, if the first operand is False, the second operand is not evaluated. In or operations, if the first operand is True, the second operand is not evaluated.

6. Bitwise Operators

Bitwise operators perform operations on the binary representations of numbers.

OperatorDescriptionExample
&AND5 & 3 = 1
^XOR5 ^ 3 = 6
~NOT~5 = -6
<<Left shift5 << 1 = 10
>>Right shift5 >> 1 = 2

Examples:

a, b = 5, 3  # In binary: a = 101, b = 011

print(f"a & b: {a & b}")  # Output: 1 (001 in binary)
print(f"a | b: {a | b}")  # Output: 7 (111 in binary)
print(f"a ^ b: {a ^ b}")  # Output: 6 (110 in binary)
print(f"~a: {~a}")        # Output: -6 (Two's complement representation)
print(f"a << 1: {a << 1}")  # Output: 10 (1010 in binary)
print(f"a >> 1: {a >> 1}")  # Output: 2 (10 in binary)

# Practical use: Checking if a number is even or odd
num = 42
is_even = not (num & 1)  # If the least significant bit is 0, the number is even
print(f"{num} is {'even' if is_even else 'odd'}")  # Output: 42 is even

Note: Bitwise operators are less commonly used in everyday programming but are important in certain areas like low-level programming, cryptography, and optimization.

7. Conditional Operators (Ternary Operator)

Python provides a conditional expression, often called the ternary operator, which is a shorthand way of writing an if-else statement in a single line.

Syntax: value_if_true if condition else value_if_false

Examples:

# Basic usage
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(f"{x} is {result}")  # Output: 10 is Even

# Ternary operator in a function
def abs_value(num):
    return num if num >= 0 else -num

print(f"Absolute value of -5: {abs_value(-5)}")  # Output: 5
print(f"Absolute value of 3: {abs_value(3)}")    # Output: 3

# Nested ternary operator (use with caution for readability)
a, b = 5, 10
result = "a is greater" if a > b else "b is greater" if b > a else "a and b are equal"
print(result)  # Output: b is greater

# Ternary operator with function calls
def is_even(n):
    return n % 2 == 0

numbers = [1, 2, 3, 4, 5]
even_odd = ['even' if is_even(n) else 'odd' for n in numbers]
print(even_odd)  # Output: ['odd', 'even', 'odd', 'even', 'odd']

Note: While the ternary operator can make code more concise, it's important to use it judiciously. For complex conditions or when clarity is more important than brevity, it's often better to use a full if-else statement.

Summary

  1. Arithmetic Operators: Covers basic mathematical operations with examples.
  2. Unary Operators: Explains operators that work with a single operand.
  3. Assignment Operators: Details various ways to assign values to variables.
  4. Comparison Operators: Covers operators used for comparing values.
  5. Logical Operators: Explains how to combine conditional statements.
  6. Bitwise Operators: Describes operators that work on the binary representation of numbers.
  7. Conditional Operators: Covers the ternary operator for concise if-else statements.

For each type of operator, I've included:

  • A table explaining each operator
  • Python code examples demonstrating their use
  • Expected outputs for each example
  • Additional notes on behavior, common use cases, or potential pitfalls

Some key points to note:

  • I've used f-strings extensively in the examples for clear and readable output formatting.
  • For bitwise operators, I included a practical example of checking if a number is even or odd.
  • The section on logical operators includes an example of short-circuit evaluation.
  • The conditional operator section shows how it can be used in list comprehensions and with function calls.