Python Code Style Guide for DSA Examples
Python Code Style Guide
This guide explains how to write clean, PEP 8 compliant, and beginner-friendly Python code for DSA examples.
The main goal is to keep Python solutions simple, readable, and easy to understand for students and new contributors.
Why This Guide Is Needed
DSA examples are easier to learn when the code follows one clean style.
This guide helps contributors with:
- Clear class and function names
- Meaningful variable names
- PEP 8 compliant formatting
- Useful comments and docstrings
- Time and space complexity annotations
- Input and output examples
- Edge case handling
1. Naming Conventions
Python uses snake_case for functions and variables, and PascalCase for classes.
Class Naming
Use PascalCase for class names. Describe the algorithm or data structure clearly.
Good
class Node:
pass
class BinarySearchTree:
pass
Avoid
class node:
pass
class binarySearchTree:
pass
Function Naming
Use snake_case for function names. They should describe what the function does.
Good
def binary_search(arr, target):
return -1
def merge_sort(arr):
pass
Avoid
def binarySearch(arr, target):
return -1
def MergeSort(arr):
pass
Variable Naming
Use meaningful snake_case variable names. Avoid single-letter variables unless they are simple loop iterators (i, j).
Good
left = 0
right = len(arr) - 1
mid = left + (right - left) // 2
Avoid
a = 0
b = len(arr) - 1
c = (a + b) // 2
2. Formatting and Indentation
Use consistent indentation of 4 spaces. Do not use tabs.
Good
if arr[mid] == target:
return mid
Avoid
if arr[mid] == target: return mid # Inline statements reduce readability