Back

/ 17 min read

Python Cheat Sheet 🏷️

Table of Contents

  1. Basic Variables
  2. Python Flow Control
  3. Type Conversion & Explicit Conversion
  4. Built-in Functions
  5. String Methods
  6. List Methods
  7. Dictionary Methods
  8. Common Patterns
  9. Python Date and Time
  10. Data Structures
  11. 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" # String
age = 25 # Integer
height = 5.9 # Float
is_student = True # Boolean
print(name) # → John
print(age) # → 25

Variable Name Rules

# Valid variable names
my_var = 10
myVar = 10
MyVar = 10
_private = 10
var123 = 10
# Invalid variable names (will cause errors)
# 123var = 10 # Cannot start with number
# my-var = 10 # Cannot contain hyphens
# my var = 10 # Cannot contain spaces

Multiple Assignment

# Assign same value to multiple variables
a = b = c = 5
print(a, b, c) # → 5 5 5
# Unpack values
x, y, z = 1, 2, 3
print(x, y, z) # → 1 2 3
# Swap variables
x, y = y, x
print(x, y) # → 2 1

Variable Scope

# Global variable
global_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 function

Python 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: Adult

Step 2: If-Else Statement

age = 15
if age >= 18:
print("Adult")
else:
print("Minor")
# Output: Minor

Step 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: C

Step 4: Logical Operators

age = 25
has_license = True
# AND operator
if age >= 18 and has_license:
print("Can drive")
# Output: Can drive
# OR operator
if age < 18 or not has_license:
print("Cannot drive")
# NOT operator
if not (age < 18):
print("Is adult")
# Output: Is adult

While Loop

Step 1: Basic While Loop

i = 0
while i < 3:
print(i)
i += 1
# Output: 0, 1, 2

Step 2: While with Break

i = 0
while i < 10:
if i == 3:
break # Exit loop
print(i)
i += 1
# Output: 0, 1, 2

Step 3: While with Continue

i = 0
while i < 5:
i += 1
if i == 2:
continue # Skip this iteration
print(i)
# Output: 1, 3, 4, 5

For Loop

Step 1: Basic For Loop

for i in range(3):
print(i)
# Output: 0, 1, 2

Step 2: For Loop with List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output: apple, banana, cherry

Step 3: For Loop with Index

fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)
# Output: 0 apple, 1 banana, 2 cherry

Step 4: For Loop with Range

# range(start, stop, step)
for i in range(0, 10, 2):
print(i)
# Output: 0, 2, 4, 6, 8

Step 5: For Loop with Break

for i in range(5):
if i == 3:
break
print(i)
# Output: 0, 1, 2

Step 6: For Loop with Continue

for i in range(5):
if i == 2:
continue
print(i)
# Output: 0, 1, 3, 4

Nested 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=1

Type Conversion & Explicit Conversion

Implicit Conversion

Python automatically converts compatible data types when needed.

# Integer to Float
x = 10
y = 5.5
z = x + y
print(z) # → 15.5 (float)
print(type(z)) # → <class 'float'>

Explicit Conversion

Manually convert data types using built-in functions.

Convert to Integer

# From string
num_str = "42"
num_int = int(num_str)
print(num_int) # → 42
# From float (truncates decimal)
num_float = 3.9
num_int = int(num_float)
print(num_int) # → 3
# From boolean
bool_val = True
num_int = int(bool_val)
print(num_int) # → 1

Convert to Float

# From string
num_str = "3.14"
num_float = float(num_str)
print(num_float) # → 3.14
# From integer
num_int = 42
num_float = float(num_int)
print(num_float) # → 42.0
# From boolean
bool_val = False
num_float = float(bool_val)
print(num_float) # → 0.0

Convert to String

# From number
num = 42
str_num = str(num)
print(str_num) # → "42"
# From float
num_float = 3.14
str_num = str(num_float)
print(str_num) # → "3.14"
# From boolean
bool_val = True
str_bool = str(bool_val)
print(str_bool) # → "True"

Convert to Boolean

# From number
print(bool(1)) # → True
print(bool(0)) # → False
print(bool(5)) # → True
# From string
print(bool("hello")) # → True
print(bool("")) # → False (empty string)
# From list
print(bool([1, 2])) # → True
print(bool([])) # → False (empty list)

Convert to List

# From string
str_val = "abc"
list_val = list(str_val)
print(list_val) # → ['a', 'b', 'c']
# From tuple
tuple_val = (1, 2, 3)
list_val = list(tuple_val)
print(list_val) # → [1, 2, 3]
# From range
range_val = range(3)
list_val = list(range_val)
print(list_val) # → [0, 1, 2]

Convert to Tuple

# From list
list_val = [1, 2, 3]
tuple_val = tuple(list_val)
print(tuple_val) # → (1, 2, 3)
# From string
str_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 → 5
round(3.14159, 2) # Round to 2 decimals → 3.14
max(1, 5, 3) # Maximum value → 5
min(1, 5, 3) # Minimum value → 1
sum([1, 2, 3, 4]) # Sum of list → 10
pow(2, 3) # Power (2^3) → 8
len([1, 2, 3]) # Length of list → 3

Type Conversion Helpers

int("5") # String to integer → 5
float("3.14") # String to decimal → 3.14
str(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, 4
enumerate(["a", "b"]) # Get index and value
zip([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 screen
input("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? → True
any([False, True]) # Any item True? → True

Math Module

Advanced mathematical functions require import math.

import math
# Square root and power
math.sqrt(16) # Square root → 4.0
math.pow(2, 3) # Power (2^3) → 8.0
# Rounding
math.ceil(3.14) # Round up → 4
math.floor(3.14) # Round down → 3
# Trigonometry
math.sin(0) # Sine of angle
math.cos(0) # Cosine of angle
math.tan(0) # Tangent of angle
# Logarithm and exponential
math.log(10) # Natural logarithm
math.exp(2) # e raised to power x
# Constants
math.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 case
text.upper() # → "HELLO"
text.lower() # → "hello"
# Find and replace
text.replace("l", "L") # → "heLLo"
"hello".find("l") # → 2
"hello".count("l") # → 2

Split and Join

text = "hello world"
# Split string into list
text.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 elements
arr[0] # First element → 1
arr[-1] # Last element → 3
arr[0:2] # Slice: elements 0-1 → [1, 2]
# Get info
len(arr) # Length → 3

Add 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 0
arr.remove(2) # Remove by value

Dictionary Methods

Work with key-value pairs.

Create Dictionaries and Access Values

mapping = {"a": 1, "b": 2}
# Access values
mapping["a"] # By key → 1
mapping.get("a") # Safe access → 1
mapping.get("c", 0) # Default if not found → 0
# Check if exists
"a" in mapping # Is key in dict? → True

Get 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 → 2

Common Patterns

Split and Strip with Variable Spacing

Handle text where spacing is inconsistent.

text = "Hello, World!"
# Step 1: Split on comma
words = text.split(",")
print(words) # ['Hello', ' World!']
# Step 2: Remove spaces from each element
words = [s.strip() for s in words]
print(words) # ['Hello', 'World!']
# Step 3: Join with space
result = " ".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 30

Check 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.123456

Step 2: Access Date and Time Components

from datetime import datetime
now = datetime.now()
print(now.year) # → 2026
print(now.month) # → 3
print(now.day) # → 9
print(now.hour) # → 14
print(now.minute) # → 30
print(now.second) # → 45

Create 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")) # → Monday

Step 2: Create Specific DateTime

from datetime import datetime
dt = datetime(2026, 3, 9, 14, 30, 45)
print(dt) # → 2026-03-09 14:30:45

Format 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:45

Date 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 - past
print(diff.days) # → 14

Step 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 - date1
print(diff.days) # → 8
print(diff.total_seconds()) # → 691200.0

Time 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.123456

Measure Elapsed Time

Step 1: Calculate Execution Time

import time
start = time.time()
for _ in range(1_000_000):
pass
end = time.time()
elapsed = end - start
print(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) # → 1
print(queue) # → deque([2, 3])

Step 4: Check Operations

if queue:
print("Queue has items")
len(queue) # → 2

Heap (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) # → 1
print(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) # → 5

Linked 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 = None

Step 2: Create Linked List

head = Node(1)
head.next = Node(2)
head.next.next = Node(3)

Step 3: Traverse and Print

current = head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

Step 4: Insert at Beginning

new_node = Node(0)
new_node.next = head
head = new_node

Step 5: Insert at End

current = head
while current.next:
current = current.next
current.next = Node(4)

Step 6: Delete First Node

head = head.next
print(head.data) # → 1

Step 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"],
}
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 F
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 C

Step 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]) # → 1
print(matrix[1][1]) # → 5
print(matrix[2][2]) # → 9

Step 3: Modify Elements

matrix[0][0] = 10

Step 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, 4
matrix = [[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) # → 8

Step 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 20

Step 5: Variable Arguments (*args)

def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4)) # → 10

Step 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 / 0
except 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 / 0
except 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 + y
print(add(5, 3)) # → 8
square = lambda x: x ** 2
print(square(4)) # → 16

Step 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

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 np
import pandas as pd

Step 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.py
def add(a, b):
return a + b
# In another file
from utils import add
print(add(5, 3)) # → 8