Nlogk
Cheat Sheet

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():
pass
class MyClass:
def method1(self):
pass
def method2(self):
pass

❌ Don't:

def first_function():
pass
class MyClass:
def method1(self):
pass
def method2(self):
pass

Whitespace

Use one space around binary operators, maintaining consistency.

✅ Do:

num += 1
x = x * 2 - 1
c = (a + b) * (a - b)

❌ Don't:

num+=1
x=x*2-1
c=(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 * 2
result = []
return result

❌ Don't:

def main_function(data):
# Don't put code before nested function
result = []
def sub_function(x): # Wrong placement
return x * 2
return result

List Comprehensions

Use list comprehensions for simple transformations only. Prefer regular loops for complex logic.

✅ Do:

# Simple transformation
squares = [x * x for x in numbers]
# Complex logic belongs in a loop
results = []
for x in numbers:
if complex_condition(x):
y = complex_calculation(x)
results.append(y)

❌ Don't:

# Too complex for comprehension
squares = [complex_calculation(x)
for x in numbers
if 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 list
items.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 broad
print(f"Error: {e}")