Table of Contents
- Basic Variables
- Python Flow Control
- Type Conversion & Explicit Conversion
- Built-in Functions
- String Methods
- List Methods
- Dictionary Methods
- Common Patterns
- Python Date and Time
- Data Structures
- Advanced Topics
Basic Variables
Variables store data values and can be created without explicit type declarations.
Declaring and Assigning Variables
# Creating variables (no type declaration needed)name = "John" # Stringage = 25 # Integerheight = 5.9 # Floatis_student = True # Boolean
print(name) # → Johnprint(age) # → 25Variable Name Rules
# Valid variable namesmy_var = 10myVar = 10MyVar = 10_private = 10var123 = 10
# Invalid variable names (will cause errors)# 123var = 10 # Cannot start with number# my-var = 10 # Cannot contain hyphens# my var = 10 # Cannot contain spacesMultiple Assignment
# Assign same value to multiple variablesa = b = c = 5print(a, b, c) # → 5 5 5
# Unpack valuesx, y, z = 1, 2, 3print(x, y, z) # → 1 2 3
# Swap variablesx, y = y, xprint(x, y) # → 2 1Variable Scope
# Global variableglobal_var = 10
def my_function(): # Local variable local_var = 5 print(local_var) # → 5 print(global_var) # → 10
my_function()print(global_var) # → 10# print(local_var) # Error: not defined outside functionPython Flow Control
Control program execution using conditions and loops.
If-Else Statements
Step 1: Simple If Statement
age = 18
if age >= 18: print("Adult")# Output: AdultStep 2: If-Else Statement
age = 15
if age >= 18: print("Adult")else: print("Minor")# Output: MinorStep 3: If-Elif-Else Statement
score = 75
if score >= 90: print("A")elif score >= 80: print("B")elif score >= 70: print("C")else: print("F")# Output: CStep 4: Logical Operators
age = 25has_license = True
# AND operatorif age >= 18 and has_license: print("Can drive")# Output: Can drive
# OR operatorif age < 18 or not has_license: print("Cannot drive")
# NOT operatorif not (age < 18): print("Is adult")# Output: Is adultWhile Loop
Step 1: Basic While Loop
i = 0while i < 3: print(i) i += 1# Output: 0, 1, 2Step 2: While with Break
i = 0while i < 10: if i == 3: break # Exit loop print(i) i += 1# Output: 0, 1, 2Step 3: While with Continue
i = 0while i < 5: i += 1 if i == 2: continue # Skip this iteration print(i)# Output: 1, 3, 4, 5For Loop
Step 1: Basic For Loop
for i in range(3): print(i)# Output: 0, 1, 2Step 2: For Loop with List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: print(fruit)# Output: apple, banana, cherryStep 3: For Loop with Index
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits): print(i, fruit)# Output: 0 apple, 1 banana, 2 cherryStep 4: For Loop with Range
# range(start, stop, step)for i in range(0, 10, 2): print(i)# Output: 0, 2, 4, 6, 8Step 5: For Loop with Break
for i in range(5): if i == 3: break print(i)# Output: 0, 1, 2Step 6: For Loop with Continue
for i in range(5): if i == 2: continue print(i)# Output: 0, 1, 3, 4Nested Loops
for i in range(3): for j in range(2): print(f"i={i}, j={j}")
# Output:# i=0, j=0# i=0, j=1# i=1, j=0# i=1, j=1# i=2, j=0# i=2, j=1Type Conversion & Explicit Conversion
Implicit Conversion
Python automatically converts compatible data types when needed.
# Integer to Floatx = 10y = 5.5z = x + yprint(z) # → 15.5 (float)print(type(z)) # → <class 'float'>Explicit Conversion
Manually convert data types using built-in functions.
Convert to Integer
# From stringnum_str = "42"num_int = int(num_str)print(num_int) # → 42
# From float (truncates decimal)num_float = 3.9num_int = int(num_float)print(num_int) # → 3
# From booleanbool_val = Truenum_int = int(bool_val)print(num_int) # → 1Convert to Float
# From stringnum_str = "3.14"num_float = float(num_str)print(num_float) # → 3.14
# From integernum_int = 42num_float = float(num_int)print(num_float) # → 42.0
# From booleanbool_val = Falsenum_float = float(bool_val)print(num_float) # → 0.0Convert to String
# From numbernum = 42str_num = str(num)print(str_num) # → "42"
# From floatnum_float = 3.14str_num = str(num_float)print(str_num) # → "3.14"
# From booleanbool_val = Truestr_bool = str(bool_val)print(str_bool) # → "True"Convert to Boolean
# From numberprint(bool(1)) # → Trueprint(bool(0)) # → Falseprint(bool(5)) # → True
# From stringprint(bool("hello")) # → Trueprint(bool("")) # → False (empty string)
# From listprint(bool([1, 2])) # → Trueprint(bool([])) # → False (empty list)Convert to List
# From stringstr_val = "abc"list_val = list(str_val)print(list_val) # → ['a', 'b', 'c']
# From tupletuple_val = (1, 2, 3)list_val = list(tuple_val)print(list_val) # → [1, 2, 3]
# From rangerange_val = range(3)list_val = list(range_val)print(list_val) # → [0, 1, 2]Convert to Tuple
# From listlist_val = [1, 2, 3]tuple_val = tuple(list_val)print(tuple_val) # → (1, 2, 3)
# From stringstr_val = "abc"tuple_val = tuple(str_val)print(tuple_val) # → ('a', 'b', 'c')Built-in Functions
Numeric Functions
Perform mathematical operations on numbers.
abs(-5) # Absolute value → 5round(3.14159, 2) # Round to 2 decimals → 3.14max(1, 5, 3) # Maximum value → 5min(1, 5, 3) # Minimum value → 1sum([1, 2, 3, 4]) # Sum of list → 10pow(2, 3) # Power (2^3) → 8len([1, 2, 3]) # Length of list → 3Type Conversion Helpers
int("5") # String to integer → 5float("3.14") # String to decimal → 3.14str(42) # Number to string → "42"bool(1) # To boolean → True
list("abc") # String to list → ['a', 'b', 'c']tuple([1, 2, 3]) # List to tuple → (1, 2, 3)dict([("a", 1)]) # List of tuples to dict → {'a': 1}Iteration Functions
range(5) # Create sequence → 0, 1, 2, 3, 4enumerate(["a", "b"]) # Get index and valuezip([1, 2], ["a", "b"]) # Combine lists → (1, 'a'), (2, 'b')sorted([3, 1, 2]) # Sort items → [1, 2, 3]list(reversed([1, 2, 3])) # Reverse items → [3, 2, 1]Other Useful Functions
print() # Print output to screeninput("Enter: ") # Get user input
type(5) # Get data type → <class 'int'>isinstance(5, int) # Check if type matches → True
all([True, True]) # All items True? → Trueany([False, True]) # Any item True? → TrueMath Module
Advanced mathematical functions require import math.
import math
# Square root and powermath.sqrt(16) # Square root → 4.0math.pow(2, 3) # Power (2^3) → 8.0
# Roundingmath.ceil(3.14) # Round up → 4math.floor(3.14) # Round down → 3
# Trigonometrymath.sin(0) # Sine of anglemath.cos(0) # Cosine of anglemath.tan(0) # Tangent of angle
# Logarithm and exponentialmath.log(10) # Natural logarithmmath.exp(2) # e raised to power x
# Constantsmath.pi # Pi → 3.14159...math.e # Euler's number → 2.71828...String Methods
Work with text and characters without extra imports.
Basic String Operations
text = "hello"
# Change casetext.upper() # → "HELLO"text.lower() # → "hello"
# Find and replacetext.replace("l", "L") # → "heLLo""hello".find("l") # → 2"hello".count("l") # → 2Split and Join
text = "hello world"
# Split string into listtext.split() # → ['hello', 'world']"a,b,c".split(",") # → ['a', 'b', 'c']"Hello, World!".split(", ") # → ['Hello', 'World!']
# Join list into string" ".join(["hello", "world"]) # → "hello world"",".join(["a", "b", "c"]) # → "a,b,c"Strip Whitespace
text = " hello "
text.strip() # Remove both sides → "hello"text.lstrip() # Remove left side only → "hello "text.rstrip() # Remove right side only → " hello"Access Characters
text = "Hello"
text[0] # First character → "H"text[-1] # Last character → "o"text[1:4] # Characters 1-3 → "ell"text[0:3] # First 3 characters → "Hel"List Methods
Work with lists and arrays.
Create Lists and Access Items
arr = [1, 2, 3]
# Access elementsarr[0] # First element → 1arr[-1] # Last element → 3arr[0:2] # Slice: elements 0-1 → [1, 2]
# Get infolen(arr) # Length → 3Add Elements
arr = [1, 2, 3]
arr.append(4) # Add to end → [1, 2, 3, 4]arr.insert(0, 0) # Insert at index 0 → [0, 1, 2, 3, 4]Remove Elements
arr = [0, 1, 2, 3, 4]
arr.pop(0) # Remove at index 0, returns 0arr.remove(2) # Remove by valueDictionary Methods
Work with key-value pairs.
Create Dictionaries and Access Values
mapping = {"a": 1, "b": 2}
# Access valuesmapping["a"] # By key → 1mapping.get("a") # Safe access → 1mapping.get("c", 0) # Default if not found → 0
# Check if exists"a" in mapping # Is key in dict? → TrueGet Keys and Values
mapping = {"a": 1, "b": 2}
mapping.keys() # → dict_keys(['a', 'b'])mapping.values() # → dict_values([1, 2])mapping.items() # → dict_items([('a', 1), ('b', 2)])
len(mapping) # Number of items → 2Common Patterns
Split and Strip with Variable Spacing
Handle text where spacing is inconsistent.
text = "Hello, World!"
# Step 1: Split on commawords = text.split(",")print(words) # ['Hello', ' World!']
# Step 2: Remove spaces from each elementwords = [s.strip() for s in words]print(words) # ['Hello', 'World!']
# Step 3: Join with spaceresult = " ".join(words)print(result) # 'Hello World!'Loop Through List with Index and Value
Get both position and value in a loop.
arr = [10, 20, 30]
for i, v in enumerate(arr): print(i, v)
# Output:# 0 10# 1 20# 2 30Check if Value Exists in Dictionary
Membership testing with dictionaries.
mapping = {1: True, 2: False, 3: True}
if 100 in mapping: print("100 is in mapping")elif 2 in mapping: print("2 is in mapping")else: print("Neither 100 nor 2 is in mapping")Python Date and Time
Work with dates, times, and time-related operations.
Current Date and Time
Step 1: Get Current Date and Time
from datetime import date, datetime
now = datetime.now()print(now) # → 2026-03-09 14:30:45.123456
today = date.today()print(today) # → 2026-03-09
current_time = datetime.now().time()print(current_time) # → 14:30:45.123456Step 2: Access Date and Time Components
from datetime import datetime
now = datetime.now()
print(now.year) # → 2026print(now.month) # → 3print(now.day) # → 9print(now.hour) # → 14print(now.minute) # → 30print(now.second) # → 45Create Specific Dates and Times
Step 1: Create Specific Date
from datetime import date
d = date(2026, 3, 9)print(d) # → 2026-03-09
print(d.weekday()) # → 0 (Monday=0, Sunday=6)print(d.strftime("%A")) # → MondayStep 2: Create Specific DateTime
from datetime import datetime
dt = datetime(2026, 3, 9, 14, 30, 45)print(dt) # → 2026-03-09 14:30:45Format Date and Time
Step 1: Convert to String with strftime
from datetime import datetime
now = datetime.now()
# Common format codes:# %Y = Year (4 digits) → 2026# %y = Year (2 digits) → 26# %m = Month (01-12) → 03# %d = Day (01-31) → 09# %H = Hour (00-23) → 14# %M = Minute (00-59) → 30# %S = Second (00-59) → 45# %A = Full weekday name → Monday# %a = Short weekday name → Mon# %B = Full month name → March# %b = Short month name → Mar
print(now.strftime("%Y-%m-%d"))print(now.strftime("%H:%M:%S"))print(now.strftime("%A, %B %d, %Y"))print(now.strftime("%d/%m/%Y"))print(now.strftime("%m/%d/%Y %H:%M:%S"))Step 2: Parse String to DateTime with strptime
from datetime import datetime
date_str = "2026-03-09"dt = datetime.strptime(date_str, "%Y-%m-%d")print(dt) # → 2026-03-09 00:00:00
datetime_str = "03/09/2026 14:30:45"dt = datetime.strptime(datetime_str, "%m/%d/%Y %H:%M:%S")print(dt) # → 2026-03-09 14:30:45Date and Time Arithmetic
Step 1: Add or Subtract Days
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=7)print(future)
past = now - timedelta(days=7)print(past)
diff = future - pastprint(diff.days) # → 14Step 2: Add or Subtract Hours, Minutes, Seconds
from datetime import datetime, timedelta
now = datetime.now()
future_hours = now + timedelta(hours=5)future_minutes = now + timedelta(minutes=30)future_seconds = now + timedelta(seconds=45)future_combined = now + timedelta(days=1, hours=5, minutes=30, seconds=45)
print(future_hours)print(future_minutes)print(future_seconds)print(future_combined)Step 3: Calculate Difference Between Dates
from datetime import datetime
date1 = datetime(2026, 3, 1)date2 = datetime(2026, 3, 9)
diff = date2 - date1print(diff.days) # → 8print(diff.total_seconds()) # → 691200.0Time Zones (Basic)
Step 1: UTC Time
from datetime import datetime, timezone
utc_time = datetime.now(timezone.utc)print(utc_time) # → 2026-03-09 14:30:45.123456+00:00
local_time = datetime.now()print(local_time) # → 2026-03-09 14:30:45.123456Measure Elapsed Time
Step 1: Calculate Execution Time
import time
start = time.time()
for _ in range(1_000_000): pass
end = time.time()elapsed = end - startprint(f"Elapsed time: {elapsed:.2f} seconds")Step 2: Sleep or Pause Execution
import time
print("Start")time.sleep(2)print("After 2 seconds")Data Structures
Queue (FIFO)
First element added is the first element removed.
Step 1: Import and Initialize Queue
from collections import deque
queue = deque()Step 2: Add Items (Enqueue)
queue.append(1)queue.append(2)queue.append(3)# Queue now: deque([1, 2, 3])Step 3: Remove Items (Dequeue)
item = queue.popleft()print(item) # → 1print(queue) # → deque([2, 3])Step 4: Check Operations
if queue: print("Queue has items")
len(queue) # → 2Heap (Min Heap by Default)
Parent values are always less than or equal to their children.
Step 1: Import and Initialize Heap
import heapq
heap = []Step 2: Add Items to Heap
heapq.heappush(heap, 5)heapq.heappush(heap, 3)heapq.heappush(heap, 7)heapq.heappush(heap, 1)
print(heap) # → [1, 3, 7, 5]Step 3: Get Minimum
min_val = heap[0]print(min_val) # → 1
min_val = heapq.heappop(heap)print(min_val) # → 1print(heap) # → [3, 5, 7]Step 4: Convert List to Heap
nums = [5, 3, 7, 1]heapq.heapify(nums)print(nums) # → [1, 3, 7, 5]Step 5: Max Heap Using Negation
max_heap = []heapq.heappush(max_heap, -5)heapq.heappush(max_heap, -3)
max_val = -heapq.heappop(max_heap)print(max_val) # → 5Linked List
Series of nodes where each node points to the next node.
Step 1: Define Node Class
class Node: def __init__(self, data): self.data = data self.next = NoneStep 2: Create Linked List
head = Node(1)head.next = Node(2)head.next.next = Node(3)Step 3: Traverse and Print
current = headwhile current: print(current.data, end=" -> ") current = current.nextprint("None")Step 4: Insert at Beginning
new_node = Node(0)new_node.next = headhead = new_nodeStep 5: Insert at End
current = headwhile current.next: current = current.nextcurrent.next = Node(4)Step 6: Delete First Node
head = head.nextprint(head.data) # → 1Step 7: Reverse Linked List
def reverse_linked_list(head): prev = None current = head while current: next_temp = current.next current.next = prev prev = current current = next_temp return prev
head = reverse_linked_list(head)Graph (Adjacency List)
Connected nodes with edges between them.
Step 1: Create Graph
graph = { "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "E"], "D": ["B", "F"], "E": ["C", "F"], "F": ["D", "E"],}Step 2: Breadth-First Search
from collections import deque
def bfs(graph, start): visited = set() queue = deque([start]) visited.add(start)
while queue: node = queue.popleft() print(node, end=" ")
for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) print()
bfs(graph, "A") # Output: A B C D E FStep 3: Depth-First Search
def dfs(graph, start, visited=None): if visited is None: visited = set()
visited.add(start) print(start, end=" ")
for neighbor in graph[start]: if neighbor not in visited: dfs(graph, neighbor, visited)
dfs(graph, "A") # Output: A B D F E CStep 4: Find Shortest Path
from collections import deque
def shortest_path(graph, start, end): visited = set() queue = deque([(start, [start])])
while queue: node, path = queue.popleft()
if node == end: return path
if node not in visited: visited.add(node)
for neighbor in graph[node]: if neighbor not in visited: queue.append((neighbor, path + [neighbor]))
return None
path = shortest_path(graph, "A", "F")print(path)2D Matrix
Two-dimensional array with rows and columns.
Step 1: Create Matrix
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9],]Step 2: Access Elements
print(matrix[0][0]) # → 1print(matrix[1][1]) # → 5print(matrix[2][2]) # → 9Step 3: Modify Elements
matrix[0][0] = 10Step 4: Get Dimensions
rows = len(matrix)cols = len(matrix[0])Step 5: Traverse Row by Row
for i in range(rows): for j in range(cols): print(matrix[i][j], end=" ") print()Step 6: Traverse Column by Column
for j in range(cols): for i in range(rows): print(matrix[i][j], end=" ") print()Step 7: Transpose Matrix
transposed = [[matrix[i][j] for i in range(rows)] for j in range(cols)]print(transposed)Step 8: Rotate Matrix 90° Clockwise
rotated = [[matrix[rows - 1 - j][i] for j in range(cols)] for i in range(rows)]print(rotated)Step 9: Sum of All Elements
total = sum(sum(row) for row in matrix)print(total)Step 10: Find an Element in the Matrix
def find_in_matrix(matrix, target): for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == target: return (i, j) return None
position = find_in_matrix(matrix, 5)print(position) # → (1, 1)Step 11: Create an $N \times M$ Matrix
n, m = 3, 4matrix = [[0 for _ in range(m)] for _ in range(n)]print(matrix)Advanced Topics
Functions
Step 1: Basic Function
def greet(): print("Hello!")
greet() # → Hello!Step 2: Function with Parameters
def add(a, b): return a + b
result = add(5, 3)print(result) # → 8Step 3: Default Arguments
def greet(name="Guest"): print(f"Hello, {name}!")
greet() # → Hello, Guest!greet("John") # → Hello, John!Step 4: Multiple Return Values
def get_coordinates(): return 10, 20
x, y = get_coordinates()print(x, y) # → 10 20Step 5: Variable Arguments (*args)
def sum_all(*args): return sum(args)
print(sum_all(1, 2, 3, 4)) # → 10Step 6: Keyword Arguments (**kwargs)
def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")
print_info(name="John", age=25)Exception Handling
Step 1: Try-Except
try: num = int("abc")except ValueError: print("Invalid number")Step 2: Multiple Except Blocks
try: x = 10 / 0except ZeroDivisionError: print("Cannot divide by zero")except ValueError: print("Invalid value")Step 3: Try-Except-Else-Finally
try: with open("data.txt", "r") as file: data = file.read()except FileNotFoundError: print("File not found")else: print(data)finally: print("Done")Step 4: Catch All Exceptions
try: result = 10 / 0except Exception as e: print(f"Error: {e}")File I/O
Step 1: Read File
with open("data.txt", "r") as file: content = file.read() print(content)
with open("data.txt", "r") as file: for line in file: print(line.strip())Step 2: Write to File
with open("data.txt", "w") as file: file.write("Hello, World!")
with open("data.txt", "a") as file: file.write("\nNew line")Step 3: Read and Write Multiple Lines
lines = ["Line 1", "Line 2", "Line 3"]with open("data.txt", "w") as file: file.writelines([line + "\n" for line in lines])
with open("data.txt", "r") as file: lines = file.readlines() print(lines)List Comprehensions
Step 1: Basic List Comprehension
squares = []for i in range(5): squares.append(i ** 2)
squares = [i ** 2 for i in range(5)]print(squares) # → [0, 1, 4, 9, 16]Step 2: With Condition
evens = [i for i in range(10) if i % 2 == 0]print(evens) # → [0, 2, 4, 6, 8]
nums = [int(x) for x in ["1", "2", "3"]]print(nums) # → [1, 2, 3]Step 3: Nested List Comprehension
matrix = [[i + j for j in range(3)] for i in range(3)]print(matrix)Lambda Functions
Step 1: Basic Lambda
add = lambda x, y: x + yprint(add(5, 3)) # → 8
square = lambda x: x ** 2print(square(4)) # → 16Step 2: Lambda with map()
nums = [1, 2, 3, 4]squared = list(map(lambda x: x ** 2, nums))print(squared) # → [1, 4, 9, 16]Step 3: Lambda with filter()
nums = [1, 2, 3, 4, 5, 6]evens = list(filter(lambda x: x % 2 == 0, nums))print(evens) # → [2, 4, 6]Step 4: Lambda with sorted()
students = [("John", 25), ("Jane", 23), ("Bob", 24)]sorted_by_age = sorted(students, key=lambda x: x[1])print(sorted_by_age)Sets
Step 1: Create Set
s = {1, 2, 3, 3, 2}print(s) # → {1, 2, 3}
s = set([1, 2, 3])print(s) # → {1, 2, 3}Step 2: Set Operations
s = {1, 2, 3}
s.add(4)s.remove(2)s.pop()
print(1 in s)print(len(s))Step 3: Union, Intersection, Difference
s1 = {1, 2, 3}s2 = {2, 3, 4}
print(s1 | s2) # Union → {1, 2, 3, 4}print(s1 & s2) # Intersection → {2, 3}print(s1 - s2) # Difference → {1}String Formatting
Step 1: f-strings (Recommended)
name = "John"age = 25
print(f"Name: {name}, Age: {age}")print(f"Result: {10 + 5}")Step 2: .format() Method
name = "John"age = 25
print("Name: {}, Age: {}".format(name, age))print("Name: {0}, Age: {1}".format(name, age))Step 3: % Formatting
name = "John"age = 25
print("Name: %s, Age: %d" % (name, age))Step 4: Formatting Numbers
num = 3.14159
print(f"{num:.2f}")print(f"{num:>10}")print(f"{1000:,}")Classes and OOP
Step 1: Define a Class
class Dog: def __init__(self, name): self.name = name
def bark(self): print(f"{self.name} says Woof!")
dog = Dog("Buddy")dog.bark()Step 2: Class Attributes and Methods
class Car: wheels = 4
def __init__(self, brand): self.brand = brand
def drive(self): print(f"{self.brand} is driving")
car = Car("Toyota")print(car.wheels)car.drive()Step 3: Inheritance
class Animal: def sound(self): print("Generic sound")
class Dog(Animal): def sound(self): print("Woof!")
dog = Dog()dog.sound()Modules and Imports
Step 1: Import Built-in Modules
import math
print(math.sqrt(16)) # → 4.0
from math import pi
print(pi) # → 3.14159...Step 2: Import with Alias
import numpy as npimport pandas as pdStep 3: Import Specific Functions
from datetime import datetime, timedelta
now = datetime.now()future = now + timedelta(days=7)print(future)Step 4: Create Your Own Module
# save as utils.pydef add(a, b): return a + b
# In another filefrom utils import add
print(add(5, 3)) # → 8