Python is dynamically typed — no need to declare variable types. Types are inferred at runtime.
# Numbers
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
# Strings
name = "Alice"
multi = """Multi
line string"""
# Boolean
flag = True
empty = False
# None (null equivalent)
value = None
# Type checking
type(x) # <class 'int'>
isinstance(x, int) # True
# Type conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(0) # False
list("abc") # ['a', 'b', 'c']
Lists are mutable ordered sequences. Tuples are immutable. Sets store unique unordered elements.
# List (mutable, ordered)
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits.insert(1, "avocado")
fruits.remove("banana")
fruits.pop() # removes last
fruits[0] # "apple"
fruits[-1] # last element
fruits[1:3] # slice [1,2]
len(fruits) # length
fruits.sort()
"apple" in fruits # True
# Tuple (immutable, ordered)
coords = (10, 20)
x, y = coords # unpacking
# Set (unique, unordered)
nums = {1, 2, 3, 2, 1} # {1, 2, 3}
nums.add(4)
nums.discard(2)
a = {1,2,3}; b = {2,3,4}
a | b # union {1,2,3,4}
a & b # intersection {2,3}
a - b # difference {1}
Dictionaries store key-value pairs. Keys must be unique and immutable. Python 3.7+ dicts maintain insertion order.
# Create dictionary
person = {
"name": "Alice",
"age": 30,
"city": "NYC"
}
# Access
person["name"] # "Alice"
person.get("age") # 30
person.get("x", "N/A") # "N/A" (default)
# Modify
person["age"] = 31
person["email"] = "a@b.com"
del person["city"]
# Methods
person.keys()
person.values()
person.items()
person.update({"age": 32, "job": "Dev"})
# Iterate
for key, value in person.items():
print(f"{key}: {value}")
# Dict comprehension
squares = {x: x**2 for x in range(5)}
Functions are defined with def. Python supports default arguments, *args, **kwargs, and lambda functions.
# Basic function
def greet(name):
return f"Hello, {name}!"
# Default arguments
def power(base, exp=2):
return base ** exp
power(3) # 9
power(3, 3) # 27
# *args (variable positional)
def add(*nums):
return sum(nums)
add(1, 2, 3, 4) # 10
# **kwargs (variable keyword)
def info(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")
info(name="Alice", age=30)
# Lambda
square = lambda x: x ** 2
# Higher-order functions
nums = [1, 2, 3, 4, 5]
list(map(lambda x: x*2, nums)) # [2,4,6,8,10]
list(filter(lambda x: x>2, nums)) # [3,4,5]
Python supports full OOP with classes, inheritance, encapsulation, and polymorphism.
class Animal:
kingdom = "Animalia" # class variable
def __init__(self, name, age):
self.name = name # instance variable
self.age = age
def speak(self):
return f"{self.name} makes a sound"
def __str__(self):
return f"Animal({self.name}, {self.age})"
@classmethod
def create(cls, name):
return cls(name, 0)
@staticmethod
def is_animal(obj):
return isinstance(obj, Animal)
# Inheritance
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def speak(self): # override
return f"{self.name} says Woof!"
dog = Dog("Rex", 3, "Labrador")
print(dog.speak()) # Rex says Woof!
List comprehensions provide a concise way to create lists. They are faster and more Pythonic than traditional loops.
# Basic: [expression for item in iterable]
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# Nested
matrix = [[i*j for j in range(3)] for i in range(3)]
# String manipulation
words = ["hello", "world", "python"]
upper = [w.upper() for w in words]
lengths = [len(w) for w in words]
# Dict comprehension
word_len = {w: len(w) for w in words}
# Set comprehension
unique_lens = {len(w) for w in words}
# Generator (memory efficient)
gen = (x**2 for x in range(1000000))
next(gen) # 0 — lazy evaluation
Python makes file operations simple. Always use with statements — they automatically close files even if an error occurs.
# Reading
with open("file.txt", "r") as f:
content = f.read() # entire file
lines = f.readlines() # list of lines
line = f.readline() # one line
# Writing
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.writelines(["line1\n", "line2\n"])
# Append
with open("log.txt", "a") as f:
f.write("New log entry\n")
# File modes: "r" read, "w" write, "a" append, "rb"/"wb" binary
# CSV
import csv
with open("data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"])
# JSON
import json
data = {"name": "Alice", "age": 30}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
with open("data.json", "r") as f:
loaded = json.load(f)
Python uses try/except/else/finally for exception handling. Create custom exceptions by subclassing Exception.
# Basic try-except
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
# Multiple exceptions
try:
x = int(input("Enter number: "))
result = 100 / x
except ValueError:
print("Not a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Unexpected: {e}")
else:
print(f"Result: {result}") # no exception
finally:
print("Always runs")
# Custom exception
class ValidationError(Exception):
def __init__(self, message, field=None):
super().__init__(message)
self.field = field
def validate_age(age):
if age < 0:
raise ValidationError("Negative age", "age")
return age
Decorators modify functions using the @ syntax. Widely used in frameworks like Flask and Django for routing, auth, and caching.
import time
from functools import wraps
# Basic decorator
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start:.4f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "done"
# Decorator with arguments
def repeat(n):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
# Built-in decorators
class MyClass:
@staticmethod
def static_method(): pass
@classmethod
def class_method(cls): pass
@property
def value(self): return self._value
Python's standard library covers most common tasks — OS operations, dates, math, regex, and specialized containers.
# os — operating system interface
import os
os.getcwd()
os.listdir(".")
os.path.join("a", "b")
os.makedirs("dir", exist_ok=True)
# datetime — dates and times
from datetime import datetime, timedelta
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M")
future = now + timedelta(days=7)
# math — mathematical functions
import math
math.sqrt(16) # 4.0
math.pi # 3.14159...
math.ceil(4.2) # 5
# random — random numbers
import random
random.randint(1, 10)
random.choice(["a","b","c"])
random.shuffle(my_list)
# re — regular expressions
import re
re.findall(r"\d+", "abc123def456")
re.sub(r"\s+", " ", "too many spaces")
# collections — specialized containers
from collections import Counter, defaultdict, deque
Counter("hello") # {'l':2,'h':1,'e':1,'o':1}