01 / 20
abc x1 ✓

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.

Python

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.

✓ Readable
student_count
✕ Cryptic
sc

Three Pillars of Code Clarity

1 Clear Names
Variables and functions reveal their purpose at a glance.
2 No Shadowing
Never re-use a name that Python already uses as a built-in.
3 Small Functions
Each function does one thing and does it well.

Anatomy of a Good Name

total_student_score What scope? "total" → aggregate What entity? "student" → domain noun What data? "score" → measurement modifier + noun + quantity = self-documenting

The Naming Rules

1
Use intention-revealing names. The name should answer why this variable exists, what it stores, and how it is used.
2
Avoid single-letter names except for trivial loop counters like i, j, k in short loops.
3
Use nouns for variables, verbs (or verb phrases) for functions: calculate_average() not average().
4
Be consistent. If you use get_ as a prefix, use it everywhere for the same concept. Don't mix fetch_ and retrieve_.
5
Never shadow built-ins. Avoid naming variables 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.

Built-in Scope list = <class 'list'> sum = <built-in> str = <class 'str'> Your Code list = [1, 2, 3] SHADOWS list("hello") TypeError! Fix: numbers = [1, 2, 3]

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.

1
One level of abstraction. Don't mix high-level logic (orchestration) with low-level details (string parsing) in the same function.
2
Aim for 5-15 lines. If a function exceeds ~20 lines, look for sub-tasks you can extract.
3
Name reveals intent. If you can't name the function with a clear verb phrase, it probably does too many things.

The Clarity Checklist

1
Read the name aloud. Does it make sense to someone unfamiliar with the code? If not, rename it.
2
Check for built-in collisions. Type the name in a Python REPL. If Python returns something, pick a different name.
3
Count function responsibilities. Can you describe the function in one sentence without "and"? If not, split it.
4
Review naming consistency. Are you using the same prefix pattern for similar operations across the file?
5
Measure function length. Count the lines. If it exceeds 20, look for extraction opportunities.

Example 1: Better Names

✕ Before
def calc(a, b):
    r = a * b * 0.08
    return r
✓ After
def calculate_sales_tax(price, quantity):
    tax_rate = 0.08
    tax_amount = price * quantity * tax_rate
    return tax_amount

Example 2: Fixing Shadowing

✕ Shadows built-in
list = [90, 85, 78]
sum = 0
for i in list:
    sum += i

# Later... TypeError!
chars = list("hello")
✓ Safe names
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

✕ Too many responsibilities
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})"
✓ Single responsibility each
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

process_student() split calculate_average() assign_letter_grade() format_report() Testable alone Reusable Easy to name Each function: one name, one job 5-15 lines ★ verb-phrase name ★ single return type

Common Mistakes

✕ Magic Numbers
Using raw numbers like 0.08 or 365 without a named constant. Assign them to UPPER_CASE names.
✕ Over-Abbreviated
Names like usr_dt_proc_fn are worse than long names. Abbreviations save typing but destroy readability.
✕ Shadowing Built-ins
Using list, input, type as variable names. This causes silent bugs that surface later.
✕ God Functions
One massive function that validates, computes, formats, and saves. Each of those should be its own function.

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

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?