1. Simplicity and Clarity

Keep It Simple: Avoid unnecessary complexity. Each function should do one thing and do it well.

Descriptive Naming: Use clear, descriptive names for functions and variables. Avoid abbreviations unless they are widely understood.

Type Annotations: Use type hints to clarify what types of arguments a function expects and what it returns.

def calculate_area(radius: float) -> float:

return 3.14 * radius * radius

#clcoding.com

2. Avoid Hardcoding

Use Constants: Define constants for values that shouldn't change. Avoid magic numbers.

Parameterization: Make functions flexible by passing parameters instead of hardcoding values. python

PI = 3.14159

def calculate_circumference(radius: float, pi:

float = PI) -> float:

return 2 * pi * radius

#clcoding.com

3. Readability

Docstrings: Include a docstring that explains what the function does, its parameters, and its return value.

Consistent Indentation: Stick to 4 spaces per indentation level.

Avoid Long Lines: Break lines at 79 characters where possible.

def calculate_bmi(weight: float, height: float) -> float:

"""

Calculate the Body Mass Index (BMI).

:param weight: Weight in kilograms.

:param height: Height in meters.

:return: BMI value.

"""

return weight / (height ** 2)

#clcoding.com

4. Testing and Error Handling

Input Validation: Check for invalid inputs and handle them gracefully.

Unit Tests: Write tests for each function. Ensure edge cases are covered.

def divide_numbers(numerator: float, denominator: float) -> float:

if denominator == 0:

raise ValueError("Denominator cannot be zero.")

return numerator / denominator

#clcoding.com

5. Performance

Efficiency: Avoid unnecessary computations. Optimize for performance if the function will be called frequently or handle large data sets.

Avoid Global State: Don’t rely on or modify global variables

def is_prime(n: int) -> bool:

if n <= 1:

return False

if n <= 3:

return True

if n % 2 == 0 or n % 3 == 0:

return False

i = 5

while i * i <= n:

if n % i == 0 or n % (i + 2) == 0:

return False

i += 6

return True

#clcoding.com

6. DRY Principle

Don’t Repeat Yourself: Reuse code by abstracting common functionality into separate functions or modules.

def get_positive_input(prompt: str) -> float:

value = float(input(prompt))

if value <= 0:

raise ValueError("Input must be a +ve number.")

return value

#clcoding.com

## 0 Comments:

## Post a Comment