ANI

How to write readable python functions even if you are a beginner

How to write readable python functions even if you are a beginner
Photo by the Author

The obvious Getting started

You wrote your first one Python work. It works. You run it, it produces the right result, and you feel the rush of accomplishment. Then you look back two weeks later and think: “What did this do?”

Writing readable Python is not about being smart or advanced. It's about writing tasks that give their purpose clearly, manage their cleaning responsibilities, and make the next person's job easier.

Let's learn to write works that read like good prose, not a cryptic puzzle that students find difficult to wrap their heads around.

🔗 You can find the code on GitHub.

The obvious 1. Mention your duties as if you were explaining them to a friend

The word Work is the first thing people read. A good name tells you exactly what the function is without requiring you to read the code inside.

Bad Example:

def proc(d):
    return sum(d) / len(d)

A good example:

def calculate_average(numbers):
    return sum(numbers) / len(numbers)

Job name calculate_average It uses a verb (“count”) that tells you it's doing an action, followed by what it counts (“measure”). The parameter numbers clearly indicate that it expects an array of values.

The work function uses sum(numbers) Adding all the values ​​again len(numbers) to calculate, then divide to get the ratio. Anyone who reads this code will immediately understand what it does without the need for comments or documentation.

The obvious 2. Use descriptive words for parameters

One-book alternatives can save typing, but they are expensive to understand. Input parameters for your function, so make it clear what you expect.

Bad Example:

def discount(p, r):
    return p * (1 - r)

A good example:

def apply_discount(original_price, discount_rate):
    return original_price * (1 - discount_rate)

Now anyone can read apply_discount(100, 0.2) Understanding that you take 20% out of 100. The code is self-aware. You don't need to check the function definition to understand what arguments to pass.

The obvious 3. Keep tasks short and focused

Jobs must do one thing well. The more responsibilities your job has, the harder it is to evaluate, reuse, and understand. So, break down a complex idea into smaller, focused tasks.

Bad Example:

def process_order(items, customer_email, discount_code):
    # Calculate total

    subtotal = sum(item["price"] * item["quantity"] for item in items)

    # Apply discount

    if discount_code == "SAVE10":
        discount = 0.10
    elif discount_code == "SAVE20":
        discount = 0.20
    else:
        discount = 0
    total = subtotal * (1 - discount)

    # Send email

    subject = f"Order Confirmation"
    body = f"Your order total is ${total:.2f}"
    send_email(customer_email, subject, body)

    return total

A good example:

def calculate_order_subtotal(items):
    return sum(item["price"] * item["quantity"] for item in items)


def get_discount_rate(discount_code):
    discount_rates = {"SAVE10": 0.10, "SAVE20": 0.20}
    return discount_rates.get(discount_code, 0)


def apply_discount_to_subtotal(subtotal, discount_rate):
    return subtotal * (1 - discount_rate)


def send_order_confirmation_email(customer_email, total):
    subject = "Order Confirmation"
    body = f"Your order total is ${total:.2f}"
    send_email(customer_email, subject, body)


def process_order(items, customer_email, discount_code):
    subtotal = calculate_order_subtotal(items)
    discount_rate = get_discount_rate(discount_code)
    total = apply_discount_to_subtotal(subtotal, discount_rate)
    send_order_confirmation_email(customer_email, total)
    return total

Now each job has a single, clear purpose. The priority process_order The task reads like a recipe: Calculate the target, get a discount, use it, send an email, return the amount.

The obvious 4. Add docstrings to describe the purpose

Job Names tell you what the job does, though DocStrings describe why it exists, what it expects, and how it returns. This is especially helpful for complex behavior or abstract behavior.

A good example:

def calculate_shipping_cost(weight_kg, distance_km, is_express=False):
    """
    Calculate shipping cost based on package weight and distance.

    Args:
        weight_kg (float): Package weight in kilograms
        distance_km (float): Shipping distance in kilometers
        is_express (bool): Whether to use express shipping (default: False)

    Returns:
        float: Total shipping cost in dollars

    Example:
        >>> calculate_shipping_cost(5.0, 100, is_express=True)
        45.50
    """
    base_rate = 2.50
    per_kg_rate = 1.20
    per_km_rate = 0.15
    express_multiplier = 2.0 if is_express else 1.0

    cost = (
        base_rate + (weight_kg * per_kg_rate) + (distance_km * per_km_rate)
    ) * express_multiplier
    return round(cost, 2)

The docstring describes what each parameter means, what type it should be, and how the function returns. Anyone who uses this function knows exactly how to call it without learning the implementation.

The obvious 5. Use clear words that change internal functions

Just like parameters, internal variables must be self-defining, too. Don't make people decide on abbreviations or guess what tmp or x represents.

Bad Example:

def calc_bmi(w, h):
    h_m = h / 100
    res = w / (h_m**2)
    return round(res, 1)

A good example:

def calculate_bmi(weight_kg, height_cm):
    height_meters = height_cm / 100
    bmi = weight_kg / (height_meters**2)
    return round(bmi, 1)

Diversity height_meters He tells you exactly how that happened. And as it turns out, flexibility bmi Holds a body mass index (BMI).

The obvious 6. Avoid magic numbers; Use named Constants

The numbers scattered throughout your code are “magic”, meaning their purpose is unclear. Give them meaningful words so that students can understand their importance.

Bad Example:

def calculate_late_fee(days_overdue):
    if days_overdue <= 7:
        return days_overdue * 2
    else:
        return 14 + (days_overdue - 7) * 5

A good example:

def calculate_late_fee(days_overdue):
    DAILY_FEE_FIRST_WEEK = 2
    GRACE_PERIOD_DAYS = 7
    BASE_FEE_AFTER_GRACE = 14
    DAILY_FEE_AFTER_GRACE = 5

    if days_overdue <= GRACE_PERIOD_DAYS:
        return days_overdue * DAILY_FEE_FIRST_WEEK
    else:
        days_after_grace = days_overdue - GRACE_PERIOD_DAYS
        return BASE_FEE_AFTER_GRACE + (days_after_grace * DAILY_FEE_AFTER_GRACE)

Now the money structure is clear. Conthaans write the rules for your business. When values ​​change, you update a single value with an exact name instead of searching for fuzzy numbers.

The obvious 7. Use Types of Clarity

The kind of plans he tells the students What types of work do you expect and return. This prevents confusion and catches bugs early. It's a good practice to add type hints to your tasks.

A good example:

def format_user_greeting(user_name: str, age: int, is_member: bool = False) -> str:
    membership_status = "member" if is_member else "guest"
    return f"Hello {user_name}, age {age}. You are a {membership_status}."

Type hints make it clear: user_name rope, age number number, is_member a boolean with a default of Falseand the function returns a string. Your integrated development environments (ODES) can use this information to provide better autocompete and error testing.

The obvious Lasting

Readable works are not difficult to write. They just need to think about your user. Every choice you make – words, structure, comments – helps or hinders understanding.

The goal is not a complete code. It is a code that communicates well. Code that makes the next person say “Ah, I get it” instead of “what exactly does this do?” That's readable code, and you can write it from day one.

In the next article, we will learn how to write pure Python classes. Until then, keep coding!

Count Priya C is a writer and technical writer from India. He likes to work in the field of statistical communication, programming, data science and content creation. His areas of interest and expertise include deliops, data science and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, he is working on learning and sharing his knowledge with the engineering community through tutorials, how-to guides, idea pieces, and more. Calculate and create resource views and code tutorials.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button