Operators - CameronAuler/python-devops GitHub Wiki

Table of Contents

Arithmetic Operators

Operator Description Example Output
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division (float) 5 / 2 2.5
// Floor Division 5 // 2 2
% Modulus (remainder) 5 % 2 1
** Exponentiation 5 ** 2 25
a = 10
b = 3

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

Comparison Operators

Operator Description Example Output
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 5 < 3 False
>= Greater than or equal to 5 >= 5 True
<= Less than or equal to 3 <= 5 True
x = 5
y = 10

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

Logical Operators

Operator Description Example Output
and Returns True if both conditions are True True and False False
or Returns True if at least one condition is True True or False True
not Reverses the boolean value not True False
a = True
b = False

print(a and b)  # Both must be True
print(a or b)   # At least one must be True
print(not a)    # Negation
# Output:
False
True
False

Assignment Operators

Operator Description Example Equivalent Output
= Assigns value x = 5 x = 5 5
+= Add and assign x += 3 x = x + 3 8
-= Subtract and assign x -= 2 x = x - 2 6
*= Multiply and assign x *= 2 x = x * 2 12
/= Divide and assign x /= 3 x = x / 3 4.0
//= Floor divide and assign x //= 2 x = x // 2 2.0
%= Modulus and assign x %= 2 x = x % 2 0.0
**= Exponentiate and assign x **= 3 x = x ** 3 0.0
x = 5

x += 3
print(x)  # 8

x -= 2
print(x)  # 6

x *= 2
print(x)  # 12

x /= 3
print(x)  # 4.0

x //= 2
print(x)  # 2.0

x %= 2
print(x)  # 0.0

x **= 3
print(x)  # 0.0
# Output:
8
6
12
4.0
2.0
0.0
0.0

Bitwise Operators

Bitwise Operators in Python perform operations on the binary representations of integers. They are primarily used for tasks like setting, toggling, or checking specific bits, optimizing performance in low-level programming, and implementing algorithms in areas like cryptography, networking, and embedded systems.

Operator Description Example Binary Calculation Output
& AND a & b 101 & 011 = 001 1
| OR a | b 101 | 011 = 111 7
^ XOR a ^ b 101 ^ 011 = 110 6
~ NOT ~a ~101 = ...11111010 -6
<< Left Shift a << 1 101 << 1 = 1010 10
>> Right Shift a >> 1 101 >> 1 = 10 2
a = 5  # 101 in binary
b = 3  # 011 in binary

print(a & b)   # Bitwise AND
print(a | b)   # Bitwise OR
print(a ^ b)   # Bitwise XOR
print(~a)      # Bitwise NOT
print(a << 1)  # Left Shift (multiply by 2)
print(a >> 1)  # Right Shift (divide by 2)
# Output:
1
7
6
-6
10
2