Python Basics

Python Operators

Learn about all Python operators including arithmetic, comparison, logical, assignment, bitwise, membership, and identity operators.

Python Operators

Operators are special symbols that perform operations on variables and values. Python provides a rich set of operators organized into several categories.


Arithmetic Operators

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33.3333
//Floor Division10 // 33
%Modulus10 % 31
**Exponentiation2 ** 101024
python
a, b = 17, 5

print(a + b)    # 22
print(a - b)    # 12
print(a * b)    # 85
print(a / b)    # 3.4
print(a // b)   # 3  (floor division - rounds down)
print(a % b)    # 2  (remainder)
print(a ** b)   # 1419857  (17 to the power of 5)

# Negative floor division rounds toward negative infinity
print(-17 // 5)   # -4 (not -3!)
print(-17 % 5)    # 3

Comparison Operators

Comparison operators return True or False:

OperatorNameExampleResult
==Equal5 == 5True
!=Not equal5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater or equal5 >= 5True
<=Less or equal5 <= 3False
python
x, y = 10, 20

print(x == y)   # False
print(x != y)   # True
print(x > y)    # False
print(x < y)    # True
print(x >= 10)  # True
print(x <= 5)   # False

# Chained comparisons (unique to Python!)
age = 25
print(18 <= age <= 65)  # True
print(1 < 2 < 3 < 4)   # True

# String comparison (lexicographic)
print("apple" < "banana")  # True
print("abc" == "abc")      # True

Logical Operators

OperatorDescriptionExampleResult
andTrue if both are TrueTrue and FalseFalse
orTrue if at least one is TrueTrue or FalseTrue
notReverses the resultnot TrueFalse
python
x = 15

# Combining conditions
print(x > 10 and x < 20)   # True
print(x > 20 or x < 10)    # False
print(not (x > 20))         # True

# Short-circuit evaluation
# 'and' stops at first False, 'or' stops at first True
print(False and print("never runs"))  # False (print not executed)
print(True or print("never runs"))    # True (print not executed)

# Practical example
age = 25
has_license = True
if age >= 18 and has_license:
    print("Can drive")

Truthiness with and/or

and and or return the actual value, not just True/False:

python
# 'and' returns first falsy value or last value
print(1 and 2 and 3)      # 3 (all truthy, returns last)
print(1 and 0 and 3)      # 0 (first falsy)
print("" and "hello")     # "" (first falsy)

# 'or' returns first truthy value or last value
print(0 or "" or "hello") # "hello" (first truthy)
print(0 or "" or [])      # [] (all falsy, returns last)

# Common pattern: default values
name = "" or "Anonymous"
print(name)  # Anonymous

port = None or 8080
print(port)  # 8080

Assignment Operators

OperatorExampleEquivalent
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
//=x //= 3x = x // 3
%=x %= 3x = x % 3
**=x **= 3x = x ** 3
python
x = 10
x += 5     # x = 15
x -= 3     # x = 12
x *= 2     # x = 24
x //= 5    # x = 4
x **= 3    # x = 64
print(x)   # 64

# Works with strings too
greeting = "Hello"
greeting += " World"
print(greeting)  # Hello World

# Works with lists
items = [1, 2]
items += [3, 4]
print(items)  # [1, 2, 3, 4]

Walrus Operator := (Python 3.8+)

Assigns and returns a value in an expression:

python
# Without walrus operator
data = input("Enter data: ")
if len(data) > 10:
    print(f"Too long: {len(data)} characters")

# With walrus operator
if (n := len(input("Enter data: "))) > 10:
    print(f"Too long: {n} characters")

# Useful in while loops
while (line := input("Enter text (q to quit): ")) != "q":
    print(f"You entered: {line}")

# In list comprehensions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
results = [y for x in numbers if (y := x ** 2) > 25]
print(results)  # [36, 49, 64, 81, 100]

Identity Operators

OperatorDescriptionExample
isSame object in memoryx is y
is notDifferent objectsx is not y
python
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)      # True (same value)
print(a is b)      # False (different objects)
print(a is c)      # True (same object)
print(a is not b)  # True

# Always use 'is' with None
x = None
print(x is None)      # True (correct)
print(x == None)       # True (works but not recommended)

Best Practice: Use is to compare with None, True, and False. Use == for value comparison.


Membership Operators

OperatorDescriptionExample
inValue found in sequence"a" in "abc"True
not inValue not found4 not in [1,2,3]True
python
# In strings
print("Py" in "Python")     # True
print("java" in "Python")   # False

# In lists
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)     # True
print("grape" not in fruits)  # True

# In dictionaries (checks keys by default)
user = {"name": "Alice", "age": 25}
print("name" in user)        # True
print("email" in user)       # False
print("Alice" in user.values())  # True

# In range
print(5 in range(10))   # True
print(15 in range(10))  # False

Bitwise Operators

OperatorNameExampleResult
&AND5 & 31
|OR5 | 37
^XOR5 ^ 36
~NOT~5-6
<<Left shift5 << 110
>>Right shift5 >> 12
python
a = 0b1010  # 10
b = 0b1100  # 12

print(bin(a & b))   # 0b1000 (AND: 8)
print(bin(a | b))   # 0b1110 (OR: 14)
print(bin(a ^ b))   # 0b0110 (XOR: 6)
print(bin(~a))      # -0b1011 (NOT: -11)
print(bin(a << 2))  # 0b101000 (Left shift: 40)
print(bin(a >> 1))  # 0b101 (Right shift: 5)

# Practical: check if number is even/odd
num = 7
print("odd" if num & 1 else "even")  # odd

# Practical: flags
READ    = 0b100  # 4
WRITE   = 0b010  # 2
EXECUTE = 0b001  # 1

permissions = READ | WRITE  # 6 (read + write)
print(bool(permissions & READ))     # True
print(bool(permissions & EXECUTE))  # False

Operator Precedence

From highest to lowest priority:

PriorityOperatorDescription
1()Parentheses
2**Exponentiation
3~, +x, -xUnary operators
4*, /, //, %Multiplication, division
5+, -Addition, subtraction
6<<, >>Bitwise shifts
7&Bitwise AND
8^Bitwise XOR
9|Bitwise OR
10==, !=, <, >, <=, >=, is, inComparisons
11notLogical NOT
12andLogical AND
13orLogical OR
python
# Precedence matters!
print(2 + 3 * 4)       # 14 (not 20)
print((2 + 3) * 4)     # 20

print(2 ** 3 ** 2)     # 512 (right-associative: 2^(3^2) = 2^9)
print((2 ** 3) ** 2)   # 64

# When in doubt, use parentheses!
result = (a + b) * (c - d) / (e ** f)

Summary

  • Arithmetic: +, -, *, /, //, %, ** for math operations
  • Comparison: ==, !=, <, >, <=, >= return boolean values
  • Logical: and, or, not for combining conditions; support short-circuit evaluation
  • Assignment: =, +=, -=, etc. for updating variables
  • Walrus operator (:=) assigns and returns in expressions (Python 3.8+)
  • Identity: is, is not for comparing object identity (use with None)
  • Membership: in, not in for checking if a value exists in a collection
  • Bitwise: &, |, ^, ~, <<, >> for bit-level operations
  • Use parentheses when operator precedence is ambiguous

Next, we'll learn about Python strings in depth.