Data Types

Python's built-in types for representing data.

Numbers

Integers

Arbitrary precision - no overflow:

x = 42
big = 10 ** 100              # Huge number, no problem
binary = 0b1010              # 10 in binary
octal = 0o17                 # 15 in octal
hexadecimal = 0xFF           # 255 in hex
readable = 1_000_000         # Underscores for readability

Floats

64-bit floating point (IEEE 754):

pi = 3.14159
scientific = 1.5e-10         # 0.00000000015
infinity = float('inf')
not_a_number = float('nan')

# Precision gotcha
0.1 + 0.2  # 0.30000000000000004

For precise decimals (money, etc.), use decimal:

from decimal import Decimal

price = Decimal('19.99')
tax = Decimal('0.08')
total = price * (1 + tax)    # Exact: 21.5892

Complex Numbers

z = 3 + 4j
z.real      # 3.0
z.imag      # 4.0
abs(z)      # 5.0 (magnitude)

Number Operations

abs(-5)           # 5
round(3.7)        # 4
round(3.14159, 2) # 3.14
min(1, 2, 3)      # 1
max(1, 2, 3)      # 3
pow(2, 10)        # 1024
divmod(17, 5)     # (3, 2) - quotient and remainder

Math Module

import math

math.sqrt(16)      # 4.0
math.floor(3.7)    # 3
math.ceil(3.2)     # 4
math.pi            # 3.141592...
math.e             # 2.718281...
math.log(100, 10)  # 2.0
math.sin(math.pi)  # ~0

Strings

Immutable sequences of Unicode characters.

Creating Strings

single = 'Hello'
double = "World"
multi = """This is a
multi-line string"""

# Raw strings (no escape processing)
path = r"C:\Users\name"      # Backslashes literal

# Byte strings
data = b"Hello"              # bytes, not str

String Operations

s = "Hello, World!"

# Indexing and slicing
s[0]           # 'H'
s[-1]          # '!'
s[0:5]         # 'Hello'
s[7:]          # 'World!'
s[::2]         # 'Hlo ol!'  (every 2nd char)
s[::-1]        # '!dlroW ,olleH'  (reversed)

# Length
len(s)         # 13

# Concatenation
"Hello" + " " + "World"    # 'Hello World'
"Ha" * 3                   # 'HaHaHa'

# Membership
"World" in s   # True

String Methods

s = "  Hello, World!  "

# Case
s.lower()           # '  hello, world!  '
s.upper()           # '  HELLO, WORLD!  '
s.title()           # '  Hello, World!  '
s.capitalize()      # '  hello, world!  '
s.swapcase()        # '  hELLO, wORLD!  '

# Whitespace
s.strip()           # 'Hello, World!'
s.lstrip()          # 'Hello, World!  '
s.rstrip()          # '  Hello, World!'

# Find and replace
s.find("World")     # 9 (index, or -1 if not found)
s.index("World")    # 9 (raises ValueError if not found)
s.count("l")        # 3
s.replace("World", "Python")  # '  Hello, Python!  '

# Split and join
"a,b,c".split(",")  # ['a', 'b', 'c']
" ".join(["a", "b", "c"])  # 'a b c'
"line1\nline2".splitlines()  # ['line1', 'line2']

# Checking content
"hello".startswith("he")   # True
"hello".endswith("lo")     # True
"123".isdigit()            # True
"abc".isalpha()            # True
"abc123".isalnum()         # True
"   ".isspace()            # True

# Padding
"42".zfill(5)       # '00042'
"hi".ljust(10)      # 'hi        '
"hi".rjust(10)      # '        hi'
"hi".center(10)     # '    hi    '

String Formatting

name = "Alice"
age = 30

# f-strings (preferred - Python 3.6+)
f"Name: {name}, Age: {age}"

# Format specifiers
pi = 3.14159
f"{pi:.2f}"         # '3.14'
f"{42:05d}"         # '00042'
f"{1000:,}"         # '1,000'
f"{0.25:.1%}"       # '25.0%'
f"{'hi':>10}"       # '        hi'
f"{'hi':<10}"       # 'hi        '
f"{'hi':^10}"       # '    hi    '

# Expressions in f-strings
f"{2 + 2}"          # '4'
f"{name.upper()}"   # 'ALICE'

# Debug format (3.8+)
f"{name=}"          # "name='Alice'"

# .format() method (older style)
"Name: {}, Age: {}".format(name, age)
"Name: {0}, Age: {1}".format(name, age)
"Name: {n}, Age: {a}".format(n=name, a=age)

# % formatting (oldest, avoid)
"Name: %s, Age: %d" % (name, age)

Escape Characters

EscapeMeaning
\nNewline
\tTab
\\Backslash
\'Single quote
\"Double quote
\rCarriage return

Booleans

True
False

# Falsy values (evaluate to False)
bool(False)     # False
bool(None)      # False
bool(0)         # False
bool(0.0)       # False
bool("")        # False
bool([])        # False
bool({})        # False
bool(set())     # False

# Everything else is truthy
bool(1)         # True
bool("hello")   # True
bool([1, 2])    # True

Boolean Operations

True and False   # False
True or False    # True
not True         # False

# Short-circuit evaluation
x = None
x and x.value    # None (doesn't access x.value)
x or "default"   # "default"

None

Python's null value:

x = None

# Check for None
if x is None:
    print("x is None")

# Common use: default arguments
def greet(name=None):
    if name is None:
        name = "World"
    print(f"Hello, {name}")

# None is a singleton
x = None
y = None
x is y  # True (same object)

Type Conversion

# To int
int("42")        # 42
int(3.9)         # 3 (truncates)
int("1010", 2)   # 10 (from binary)
int("ff", 16)    # 255 (from hex)

# To float
float("3.14")    # 3.14
float(42)        # 42.0

# To string
str(42)          # '42'
str(3.14)        # '3.14'
str([1, 2, 3])   # '[1, 2, 3]'

# To bool
bool(1)          # True
bool("")         # False

# Check type
type(42)         # <class 'int'>
type("hi")       # <class 'str'>

isinstance(42, int)           # True
isinstance("hi", (str, int))  # True (either type)

String Encoding

# str → bytes (encode)
text = "Hello, 世界"
data = text.encode('utf-8')    # b'Hello, \xe4\xb8\x96\xe7\x95\x8c'

# bytes → str (decode)
text = data.decode('utf-8')    # 'Hello, 世界'

# Common encodings
'utf-8'      # Unicode, default
'ascii'      # Basic ASCII
'latin-1'    # Western European

Practice

# 1. Number formatting
price = 1234.5
print(f"Price: ${price:,.2f}")  # Price: $1,234.50

# 2. String manipulation
email = "  User@Example.COM  "
clean = email.strip().lower()
print(clean)  # user@example.com

# 3. Type checking
def process(value):
    if isinstance(value, str):
        return value.upper()
    elif isinstance(value, (int, float)):
        return value * 2
    return None

# 4. Truthiness
def get_name(name=None):
    return name or "Anonymous"

print(get_name())         # Anonymous
print(get_name("Alice"))  # Alice