Code Clarity
& Naming
Learn to write clear variable names, avoid shadowing built-ins, and keep functions small and focused for Python code that reads like a story.
Why Naming Matters
You spend far more time reading code than writing it. Research shows developers spend roughly 70% of coding time understanding existing code. When names are unclear, that cost multiplies.
student_countscThree Pillars of Code Clarity
Anatomy of a Good Name
The Naming Rules
i, j, k in short loops.calculate_average() not average().get_ as a prefix, use it everywhere for the same concept. Don't mix fetch_ and retrieve_.list, str, type, input, id, or sum.What Is Shadowing?
When you assign a value to a name that Python already uses as a built-in, you "shadow" it: your local name hides the original, making the built-in unreachable in that scope.
Descriptive vs. Abbreviated Names
| Abbreviated | Descriptive | |
|---|---|---|
| User data | d |
user_profile |
| Temperature | t |
celsius_temp |
| Process items | proc() |
validate_orders() |
| Counter | cnt |
retry_count |
| Return value | ret |
formatted_output |
Keep Functions Small
A function should do one thing, do it completely, and do it only. If you need a comment like # now handle the other case inside a function, it is doing too much.
The Clarity Checklist
Example 1: Better Names
def calc(a, b): r = a * b * 0.08 return r
def calculate_sales_tax(price, quantity): tax_rate = 0.08 tax_amount = price * quantity * tax_rate return tax_amount
Example 2: Fixing Shadowing
list = [90, 85, 78] sum = 0 for i in list: sum += i # Later... TypeError! chars = list("hello")
scores = [90, 85, 78] total_score = 0 for score in scores: total_score += score # Works perfectly chars = list("hello")
Example 3: Splitting a Large Function
def process_student(name, scores): # validate if not name or not scores: return None # calculate average total = 0 for s in scores: total += s avg = total / len(scores) # assign grade if avg >= 90: grade = "A" elif avg >= 80: grade = "B" else: grade = "C" # format report return f"{name}: {grade} ({avg:.1f})"
def calculate_average(scores): return sum(scores) / len(scores) def assign_letter_grade(average): if average >= 90: return "A" if average >= 80: return "B" return "C" def format_student_report(name, scores): avg = calculate_average(scores) grade = assign_letter_grade(avg) return f"{name}: {grade} ({avg:.1f})"
Decomposition Flow
Common Mistakes
0.08 or 365 without a named constant. Assign them to UPPER_CASE names.usr_dt_proc_fn are worse than long names. Abbreviations save typing but destroy readability.list, input, type as variable names. This causes silent bugs that surface later.Summary Table
| Principle | Avoid | Prefer |
|---|---|---|
| Variable naming | x, d, tmp |
user_age, data, temp_file |
| Function naming | do_stuff() |
send_welcome_email() |
| Built-in safety | list = [...] |
items = [...] |
| Constants | 3.14 |
PI = 3.14 |
| Function size | 50+ lines | 5-15 lines, one responsibility |
Question 1 of 5
Which variable name best describes a list of student exam results?
Question 2 of 5
What happens if you write sum = 10 and later call sum([1, 2, 3])?
Question 3 of 5
A function named data() is problematic because:
Question 4 of 5
def handle_order(order): # validate if order["qty"] <= 0: return "invalid" # calculate total total = order["price"] * order["qty"] # apply discount if total > 100: total *= 0.9 # format receipt return f"Total: ${total:.2f}"
How many separate responsibilities does this function have?
Question 5 of 5
Which of the following is the best way to replace a magic number?