Coding Style
Naming Conventions
Use CamelCase
for class names and snake_case
for functions and variable names.
✅ Do:
class MyClass:def my_function():total_sum = 42
❌ Don't:
class myclass:def MyFunction():MyVariable = 42
Indentation
Use 4 spaces per indentation level. Never use tabs.
✅ Do:
def function():if condition:do_something()
❌ Don't:
def function():if condition:do_something() # mixing spaces
Line Breaks
Break lines before binary operators for better readability.
✅ Do:
total = (first_variable+ second_variable+ third_variable)
❌ Don't:
total = (first_variable +second_variable +third_variable)
Blank Lines
Use two blank lines between top-level items, one within classes.
✅ Do:
def first_function():passclass MyClass:def method1(self):passdef method2(self):pass
❌ Don't:
def first_function():passclass MyClass:def method1(self):passdef method2(self):pass
Whitespace
Use one space around binary operators, maintaining consistency.
✅ Do:
num += 1x = x * 2 - 1c = (a + b) * (a - b)
❌ Don't:
num+=1x=x*2-1c=(a+b)*(a-b)
Nested Functions
Place nested functions directly after the first line of the main function, before any other code.
✅ Do:
def main_function(data):def sub_function(x):return x * 2result = []return result
❌ Don't:
def main_function(data):# Don't put code before nested functionresult = []def sub_function(x): # Wrong placementreturn x * 2return result
List Comprehensions
Use list comprehensions for simple transformations only. Prefer regular loops for complex logic.
✅ Do:
# Simple transformationsquares = [x * x for x in numbers]# Complex logic belongs in a loopresults = []for x in numbers:if complex_condition(x):y = complex_calculation(x)results.append(y)
❌ Don't:
# Too complex for comprehensionsquares = [complex_calculation(x)for x in numbersif complex_condition(x)]
Default Arguments
Never use mutable objects as default arguments.
✅ Do:
def my_function(items=None):if items is None:items = []items.append(1)return items
❌ Don't:
def my_function(items=[]): # Bug: shared listitems.append(1)return items
Context Managers
Use context managers (with
statement) for managing resources.
✅ Do:
with open('file.txt', 'r') as f:content = f.read()# file automatically closes
❌ Don't:
f = open('file.txt', 'r')content = f.read()f.close() # Might not close if error occurs
Error Handling
Be specific with exceptions and keep try blocks small.
✅ Do:
try:value = int(user_input)except ValueError:print("Please enter a valid number")else:process_number(value)
❌ Don't:
try:value = int(user_input)process_number(value)save_to_database(value)except Exception as e: # Too broadprint(f"Error: {e}")