

Picture by Creator
# Introduction
You might have written your first Python perform. It really works. You run it, it produces the suitable output, and you are feeling that rush of accomplishment. Then you definately have a look at it once more two weeks later and suppose: “What does this even do?”
Writing readable Python features will not be about being good or superior. It’s about writing features that talk their intent clearly, deal with their duties cleanly, and make the subsequent individual’s job simpler.
Let’s learn to write features that learn like good prose, not cryptic puzzles that readers discover tough to wrap their heads round.
🔗 You will discover the code on GitHub.
# 1. Title Your Capabilities Like You are Explaining to a Pal
Perform names are the very first thing folks learn. A superb title tells you precisely what the perform does with out requiring you to learn the code inside.
Dangerous instance:
def proc(d):
return sum(d) / len(d)
Good instance:
def calculate_average(numbers):
return sum(numbers) / len(numbers)
The perform title calculate_average makes use of a verb (“calculate”) that tells you it performs an motion, adopted by what it calculates (“common”). The parameter numbers clearly signifies it expects a set of numerical values.
The perform physique makes use of sum(numbers) so as to add all values and len(numbers) to rely them, then divides to get the typical. Anybody studying this code immediately understands what it does while not having feedback or documentation.
# 2. Use Descriptive Parameter Names
Single-letter variables would possibly save typing, however they value understanding. Parameters are your perform’s inputs, so make it apparent what you count on.
Dangerous instance:
def low cost(p, r):
return p * (1 - r)
Good instance:
def apply_discount(original_price, discount_rate):
return original_price * (1 - discount_rate)
Now anybody studying apply_discount(100, 0.2) understands you’re taking 20% off 100. The code is self-documenting. You do not want to verify the perform definition to know what arguments to move.
# 3. Hold Capabilities Quick and Targeted
Capabilities ought to do one factor nicely. In case your perform has a number of duties, it turns into exhausting to check, reuse, and perceive. So, break advanced logic into smaller, centered features.
Dangerous instance:
def process_order(objects, customer_email, discount_code):
# Calculate complete
subtotal = sum(merchandise["price"] * merchandise["quantity"] for merchandise in objects)
# Apply low cost
if discount_code == "SAVE10":
low cost = 0.10
elif discount_code == "SAVE20":
low cost = 0.20
else:
low cost = 0
complete = subtotal * (1 - low cost)
# Ship electronic mail
topic = f"Order Affirmation"
physique = f"Your order complete is ${complete:.2f}"
send_email(customer_email, topic, physique)
return complete
Good instance:
def calculate_order_subtotal(objects):
return sum(merchandise["price"] * merchandise["quantity"] for merchandise in objects)
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, complete):
topic = "Order Affirmation"
physique = f"Your order complete is ${complete:.2f}"
send_email(customer_email, topic, physique)
def process_order(objects, customer_email, discount_code):
subtotal = calculate_order_subtotal(objects)
discount_rate = get_discount_rate(discount_code)
complete = apply_discount_to_subtotal(subtotal, discount_rate)
send_order_confirmation_email(customer_email, complete)
return complete
Now every perform has a single, clear objective. The principle process_order perform reads like a recipe: calculate subtotal, get low cost, apply it, ship electronic mail, return complete.
# 4. Add Docstrings to Clarify Objective
Perform names let you know what a perform does, however docstrings clarify why it exists, what it expects, and what it returns. That is particularly useful for advanced logic or non-obvious conduct.
Good instance:
def calculate_shipping_cost(weight_kg, distance_km, is_express=False):
"""
Calculate delivery value primarily based on bundle weight and distance.
Args:
weight_kg (float): Package deal weight in kilograms
distance_km (float): Delivery distance in kilometers
is_express (bool): Whether or not to make use of specific delivery (default: False)
Returns:
float: Whole delivery value in {dollars}
Instance:
>>> 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
value = (
base_rate + (weight_kg * per_kg_rate) + (distance_km * per_km_rate)
) * express_multiplier
return spherical(value, 2)
The docstring explains what every parameter means, what kind it needs to be, and what the perform returns. Anybody utilizing this perform is aware of precisely easy methods to name it with out studying the implementation.
# 5. Use Clear Variable Names Inside Capabilities
Similar to parameters, inside variables needs to be descriptive, too. Don’t make folks decode abbreviations or guess what tmp or x represents.
Dangerous instance:
def calc_bmi(w, h):
h_m = h / 100
res = w / (h_m**2)
return spherical(res, 1)
Good instance:
def calculate_bmi(weight_kg, height_cm):
height_meters = height_cm / 100
bmi = weight_kg / (height_meters**2)
return spherical(bmi, 1)
The variable height_meters tells you precisely what conversion occurred. And as seen, the variable bmi holds the physique mass index (BMI) calculation.
# 6. Keep away from Magic Numbers; Use Named Constants As an alternative
Numbers scattered by your code are “magic”, which means their objective is unclear. Give them significant names so readers perceive their significance.
Dangerous instance:
def calculate_late_fee(days_overdue):
if days_overdue <= 7:
return days_overdue * 2
else:
return 14 + (days_overdue - 7) * 5
Good instance:
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 price construction is clear. The constants doc your small business guidelines. When charges change, you replace one clearly-named worth as an alternative of looking for mysterious numbers.
# 7. Use Sort Hints for Readability
Sort hints inform readers what sorts your perform expects and returns. This prevents confusion and catches bugs early. It’s good apply so as to add kind hints in your features.
Good instance:
def format_user_greeting(user_name: str, age: int, is_member: bool = False) -> str:
membership_status = "member" if is_member else "visitor"
return f"Hey {user_name}, age {age}. You're a {membership_status}."
The kind hints make it clear: user_name is a string, age is an integer, is_member is a Boolean with a default of False, and the perform returns a string. Your built-in growth environments (IDEs) can use this data to supply higher autocomplete and error checking.
# Conclusion
Readable features are usually not tougher to jot down. They simply require interested by your person. Each alternative you make — names, construction, feedback — both helps or hinders understanding.
The purpose will not be excellent code. It’s code that communicates clearly. Code that makes the subsequent individual say “ah, I get it” as an alternative of “what is that this doing actually?” That’s readable code, and you may write it from day one.
Within the subsequent article, we’ll learn to write clear Python lessons. Till then, preserve coding!
Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, information science, and content material creation. Her areas of curiosity and experience embody DevOps, information science, and pure language processing. She enjoys studying, writing, coding, and low! At present, she’s engaged on studying and sharing her data with the developer neighborhood by authoring tutorials, how-to guides, opinion items, and extra. Bala additionally creates partaking useful resource overviews and coding tutorials.















