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.
Operator | Description | Example |
---|---|---|
+ | Addition | 5 + 3 = 8 |
- | Subtraction | 5 - 3 = 2 |
* | Multiplication | 5 * 3 = 15 |
/ | Division (float result) | 5 / 3 = 1.6666667 |
// | Floor Division (integer result) | 5 // 3 = 1 |
% | Modulus (remainder) | 5 % 3 = 2 |
** | Exponentiation | 5 ** 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.
Operator | Description | Example |
---|---|---|
- | 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.
Operator | Description | Example | Equivalent to |
---|---|---|---|
= | Simple assignment | x = 5 | - |
+= | Add and assign | x += 3 | x = x + 3 |
-= | Subtract and assign | x -= 3 | x = x - 3 |
*= | Multiply and assign | x *= 3 | x = x * 3 |
/= | Divide and assign | x /= 3 | x = x / 3 |
//= | Floor divide and assign | x //= 3 | x = x // 3 |
%= | Modulus and assign | x %= 3 | x = x % 3 |
**= | Exponentiate and assign | x **= 3 | x = 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
).
Operator | Description | Example |
---|---|---|
== | Equal to | 5 == 5 returns True |
!= | Not equal to | 5 != 4 returns True |
< | Less than | 3 < 5 returns True |
> | Greater than | 5 > 3 returns True |
<= | Less than or equal to | 3 <= 3 returns True |
>= | Greater than or equal to | 5 >= 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.
Operator | Description | Example |
---|---|---|
and | Returns True if both statements are true | x < 5 and x < 10 |
or | Returns True if one of the statements is true | x < 5 or x < 4 |
not | Reverses the result, returns False if the result is true | not(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.
Operator | Description | Example |
---|---|---|
& | AND | 5 & 3 = 1 |
^ | XOR | 5 ^ 3 = 6 |
~ | NOT | ~5 = -6 |
<< | Left shift | 5 << 1 = 10 |
>> | Right shift | 5 >> 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
- Arithmetic Operators: Covers basic mathematical operations with examples.
- Unary Operators: Explains operators that work with a single operand.
- Assignment Operators: Details various ways to assign values to variables.
- Comparison Operators: Covers operators used for comparing values.
- Logical Operators: Explains how to combine conditional statements.
- Bitwise Operators: Describes operators that work on the binary representation of numbers.
- 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.