Computer Programming 1 (Python) • Debugging, Testing & Code Quality

Style Conventions & Comments — I can follow basic style conventions (indentation, naming) and write clear comments/docstrings at my level.

Write Python code that humans can read, understand, and maintain with consistent style and clear documentation.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

In the earliest days of computing, programs were written in raw machine code — sequences of ones and zeros that only the computer needed to understand. Programmers punched their instructions onto cards, and since storage was expensive, they used extremely short variable names and crammed code together with no spacing. As computers became more powerful and programs grew larger, a serious problem emerged: nobody could read each other's code. Even the original author would struggle to understand their own program just weeks later. This readability crisis drove the computing community to develop style conventions — agreed-upon rules for formatting and naming — and the practice of writing comments and documentation directly inside source code.

1972 • The C Language & Early Conventions

Dennis Ritchie created the C programming language, which introduced curly braces and indentation patterns that influenced decades of style guides. Early programmers began debating tabs versus spaces.

1991 • Python Is Born

Guido van Rossum released Python, a language that made indentation part of the syntax itself. Readability was a core design goal from day one, unlike most languages before it.

2001 • PEP 8 Published

PEP 8 (Python Enhancement Proposal 8) was published by Guido van Rossum, Barry Warsaw, and Nick Coghlan. It became the official style guide for Python code, covering indentation, naming, spacing, and comments.

2005 • PEP 257 — Docstring Conventions

PEP 257 formalized conventions for writing docstrings — special strings that document what functions, classes, and modules do. This made Python uniquely self-documenting among programming languages.

2010s • Automated Linters & Formatters

Tools like pylint, flake8, and Black emerged to automatically check and enforce style conventions. Modern editors can highlight style violations in real time as you type.

Python's creator, Guido van Rossum, famously said that "code is read much more often than it is written." This insight drives everything in this lesson. The central question is simple but powerful: how do you write code that is not just correct, but also clear and understandable to anyone who reads it — including your future self?

SECTION 2

Core Principles of Clean Code Style

Good code style rests on a few foundational ideas. These principles aren't arbitrary rules — they exist because decades of software development have proven that consistent, well-documented code saves enormous amounts of time and prevents bugs. Think of style conventions as the grammar and punctuation of programming: your code will still "run" without them, but nobody will want to read it.

1

Consistency

Pick a style and stick with it throughout your entire program. Mixing styles — like using camelCase in one function and snake_case in another — forces readers to decode your patterns instead of understanding your logic.
2

Readability Over Cleverness

A shorter line of code is not always better. Writing clear, explicit code that any classmate could understand is more valuable than a one-liner that takes five minutes to decode.
3

Self-Documenting Names

Variable and function names should describe their purpose. A name like student_grade tells you everything, while x tells you nothing.
4

Comments Explain Why, Not What

Good comments explain the reasoning behind your decisions, not what the code literally does. The code itself shows the "what" — your comments should reveal the "why."
5

Follow the Community Standard

Python's official style guide is PEP 8. Following PEP 8 means any Python programmer in the world can read your code immediately, because you're all speaking the same visual language.
✦

KEY TAKEAWAY

Think of style conventions like the rules of the road. Traffic lights, lane markings, and speed signs aren't suggestions — they're shared agreements that let millions of drivers navigate safely together. Similarly, PEP 8 conventions let thousands of Python programmers read and contribute to each other's code without confusion. Your code is your communication to other developers — and to your future self.

SECTION 3

Seeing the Difference: Good vs. Bad Style

The best way to understand why style matters is to see the same program written two ways — one with poor style and one following PEP 8 conventions. The diagram below places them side by side so you can compare readability at a glance. Notice how the properly styled version uses descriptive variable names, consistent 4-space indentation, and helpful comments to make the logic crystal clear.

❌ POOR STYLE✅ PEP 8 STYLEdef c(l): t=0 for i in l: if i>=90: t=t+1 return tx=[85,92,78,95,88,91]print(c(x))⚠ Single-letter function name "c"⚠ Variable "t" — what does it count?⚠ Only 2-space indent (PEP 8 = 4)⚠ No spaces around operators⚠ Zero comments or docstrings⚠ "l" looks like "1" in many fonts⚠ Magic number 90 unexplaineddef count_a_grades(scores): """Return the number of A grades (90 or above) in a list of scores.""" a_count = 0 # Check each score against the A threshold for score in scores: if score >= 90: a_count += 1 return a_countstudent_scores = [85, 92, 78, 95, 88, 91]print(count_a_grades(student_scores))✓ Descriptive function name✓ Docstring explains purpose✓ 4-space indentation (PEP 8)✓ Spaces around operators✓ Comment explains the "why"✓ Meaningful variable names✓ snake_case naming convention
The left panel shows code with poor naming, inconsistent indentation, and no documentation. The right panel shows the same logic following PEP 8 conventions — descriptive names, 4-space indentation, a docstring, and a helpful inline comment. Both programs produce the same output, but only one is easy to read and maintain.

Notice that the right-side version is slightly longer, but dramatically easier to understand. The function name count_a_grades tells you exactly what the function does without even reading the body. The docstring at the top provides a one-sentence summary. The inline comment explains why we're checking against 90. This is the difference between code that works and code that communicates.

SECTION 4

How Style Conventions Work in Python

Indentation: Python's Structural Foundation

Unlike most programming languages where indentation is cosmetic, Python uses indentation to define code blocks. If you indent incorrectly, your program won't just look bad — it will crash with an IndentationError. PEP 8 specifies exactly 4 spaces per indentation level. Do not use tabs, and do not use 2 spaces. Every time you enter a new block (after if, for, while, def, etc.), indent 4 more spaces.

Naming Conventions: snake_case and Beyond

PEP 8 defines clear naming conventions for different elements in your code. Variables and functions use snake_case — all lowercase letters with underscores separating words, like total_score or calculate_average. Constants (values that never change) use UPPER_SNAKE_CASE, like MAX_ATTEMPTS or TAX_RATE. Class names use PascalCase (also called CapWords), like StudentRecord. You probably won't write classes yet in this course, but knowing the pattern helps you read other people's code.

Spacing and Whitespace Rules

PEP 8 also governs whitespace — the spaces around operators, after commas, and between sections. Put one space on each side of assignment operators (x = 5, not x=5) and comparison operators (if x >= 10, not if x>=10). Put one space after each comma in function arguments and lists. Use two blank lines before and after function definitions to visually separate them. These rules may seem small, but they add up to make your code dramatically easier to scan.

Comments: The Three Types

Python supports three forms of documentation. Inline comments start with # and appear on the same line as code or on their own line above. Block comments are one or more lines starting with # that describe a section of code. Docstrings are special strings enclosed in triple quotes ("""...""") placed as the first statement in a function, class, or module. Docstrings are unique because Python can access them at runtime using the help() function, making them a built-in documentation system.

SECTION 5

The Complete Naming & Commenting Reference

Choosing good names is one of the hardest and most important skills in programming. A well-chosen name eliminates the need for a comment entirely. The table below summarizes the PEP 8 naming conventions you should use at this level, with examples of good and bad choices.

ElementConventionGood ExampleBad Example
Variablesnake_caseplayer_healthph or PlayerHealth
Functionsnake_casecalculate_gpacalcGPA or f
ConstantUPPER_SNAKE_CASEMAX_RETRIESmaxRetries or mr
ClassPascalCaseBankAccountbank_account or bankaccount
Boolean variableStart with is_ or has_is_validvalid or flag
Loop counterMeaningful or i, j, kfor row in grid:for r in g:

PEP 8 naming conventions for common Python elements

ANATOMY OF A WELL-DOCUMENTED FUNCTIONdef calculate_average(grades): """Calculate the average of a list of grades. Args: grades: A list of numeric grade values. Returns: The mean average as a float. """ # Guard against dividing by zero if len(grades) == 0: return 0.0 total = sum(grades) average = total / len(grades) return average← snake_case function name← DOCSTRINGTriple-quoted string as thefirst line inside the function← INLINE COMMENTExplains WHY, not what← Descriptive variable names
This diagram labels the key components of a well-documented Python function: a snake_case function name, a docstring with Args/Returns sections, an inline comment explaining the reasoning behind the zero-check, and descriptive variable names like total and average.
💡

When Are Short Variable Names OK?

Single-letter names like i, j, and k are acceptable as loop counters in simple, short loops where the meaning is obvious. Similarly, x and y are fine for coordinate values. The key rule is: the smaller the scope, the shorter the name can be. But in anything more than a 2-line loop, prefer descriptive names.

SECTION 6

Worked Example: Refactoring Messy Code

Let's walk through the process of taking a working but poorly styled Python program and refactoring it — rewriting it to follow PEP 8 conventions and adding proper documentation. Refactoring means changing how code looks without changing what it does.

📝

Original Messy Code

def f(n): r=[] for i in range(2,n+1): p=True for j in range(2,i): if i%j==0: p=False if p: r.append(i) return r print(f(20))

Refactoring Step by Step

  1. 1

    Step 1 — Understand What the Code Does

    Before renaming anything, read through the code and figure out its purpose. The function takes a number n, loops from 2 to n, and checks whether each number is divisible by any smaller number. If not, it's added to a list. This function finds all prime numbers up to n.
    Purpose identified: find prime numbers up to a given limit.
  2. 2

    Step 2 — Rename the Function

    Replace the cryptic name f with a descriptive snake_case name that tells the reader exactly what the function does.
    def find_primes(limit):
  3. 3

    Step 3 — Rename Variables

    Replace each single-letter variable with a meaningful name. r becomes primes (the list of results). i becomes candidate (the number being tested). p becomes is_prime (a boolean flag). j becomes divisor.
    All variable names now describe their purpose.
  4. 4

    Step 4 — Fix Indentation and Spacing

    Change from 2-space indentation to 4-space indentation. Add spaces around all operators: i%j==0 becomes candidate % divisor == 0. Add blank lines between logical sections. Add a space after commas in range(2, limit + 1).
    Code now follows PEP 8 whitespace rules.
  5. 5

    Step 5 — Add Docstring and Comments

    Add a docstring as the first line inside the function, describing what it does, its parameter, and its return value. Add an inline comment above the inner loop to explain why we test divisibility. The final refactored code looks like this:
    def find_primes(limit): """Return a list of all prime numbers up to limit. Args: limit: The upper bound (inclusive) to search. Returns: A list of prime integers. """ primes = [] for candidate in range(2, limit + 1): is_prime = True # Test if any smaller number divides evenly for divisor in range(2, candidate): if candidate % divisor == 0: is_prime = False if is_prime: primes.append(candidate) return primes print(find_primes(20))
✦

KEY TAKEAWAY

Refactoring is like editing a rough draft of an essay. Your first draft gets the ideas down; your second draft makes those ideas clear to your reader. In programming, your "first draft" makes the computer understand you. Refactoring — renaming variables, fixing spacing, adding docstrings — makes humans understand you too.

SECTION 7

Good Comments vs. Bad Comments

Not all comments are helpful. In fact, bad comments can be worse than no comments at all because they can mislead the reader. A comment that says something obvious wastes the reader's time, while a comment that contradicts the code creates dangerous confusion. The table below compares effective and ineffective commenting strategies.

PatternBad Comment ❌Good Comment ✅Why
Stating the obviousx = x + 1 # add 1 to xattempts += 1 # user failed, allow retryThe code already says what happens. The comment should say WHY.
Explaining magic numbersif score >= 90: # check scoreif score >= A_THRESHOLD: # 90% per syllabusBetter yet, use a named constant and explain the source.
Outdated information# Returns the sum (actually returns average now)Update or remove the comment when code changes.Stale comments are worse than no comments.
Section separators############# FUNCTIONS ############## --- Input validation ---Minimal, clean separators help; decorative ones clutter.
Justifying decisions(No comment at all)# Using bubble sort because n < 20 (efficiency not critical)Explains the trade-off behind an algorithm choice.

Comparing effective and ineffective commenting patterns

📌

THE GOLDEN RULE OF COMMENTS

Before writing a comment, ask yourself: "Could I make this code clear enough that the comment is unnecessary?" If you can rename a variable or simplify logic to eliminate the need for a comment, do that first. Comments should fill gaps that code cannot — explaining business rules, design decisions, or non-obvious behavior.

SECTION 8

From Basic Style to Professional Code Quality

The conventions you're learning now are the foundation for professional software development practices. As you advance, you'll encounter more sophisticated tools and standards that build directly on these basics. Understanding where the journey leads can motivate you to build strong habits now.

ConceptWhat You Learn NowWhat Professionals Use
FormattingManually follow PEP 8 (4-space indent, spacing)Auto-formatters like Black instantly reformat entire codebases
Style checkingRead PEP 8 and self-reviewLinters (pylint, flake8) flag violations automatically
DocumentationSimple docstrings and inline commentsFull API docs auto-generated from docstrings using Sphinx
Type hintsDescribe types in docstringsType annotations like def add(a: int, b: int) -> int:
Code reviewAsk a friend to read your codeFormal pull request reviews on platforms like GitHub

How basic style skills scale into professional practices

The key insight is that every professional tool automates what you're learning to do manually. By understanding why these conventions exist — not just blindly following them — you'll be ready to use advanced tools effectively. A programmer who understands PEP 8 can configure a linter; a programmer who doesn't understand style principles will just be confused by the warnings.

💡

Try It: Use help() on Your Own Functions

After defining a function with a docstring, type help(your_function_name) in the Python shell. Python will display the docstring you wrote. This is exactly how professional documentation tools work — they extract your docstrings and turn them into web pages, PDFs, and searchable reference guides.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

A classmate writes a function called def DoTheThing(x, y): and argues that it's fine because the program runs without errors. Explain two specific PEP 8 violations in the function signature and why they matter for readability.
Show answer
There are two PEP 8 violations. First, the function name DoTheThing uses PascalCase instead of the required snake_case — it should be something like do_the_thing. In Python, PascalCase is reserved for class names, so using it for a function misleads other programmers about what the name represents. Second, the name is vague — "the thing" gives no clue about the function's purpose. A descriptive name like calculate_distance would communicate its purpose instantly. Similarly, x and y are acceptable only if the function actually works with coordinates; otherwise, descriptive parameter names should be used.

Question 2: BASIC

Rewrite the following variable declarations to follow PEP 8 naming conventions: myFirstName = "Alice" MAXIMUM_score = 100 PlayerLives=3 is_Running = True
Show answer
The corrected declarations are: my_first_name = "Alice" (variables use snake_case, not camelCase). MAXIMUM_SCORE = 100 (if this is a constant that never changes, use all uppercase; if it's a regular variable, use maximum_score = 100). player_lives = 3 (snake_case, with a space around the equals sign). is_running = True (consistent snake_case with no unexpected capitalization). Note how every corrected version uses lowercase with underscores and includes spaces around the = operator.

Question 3: INTERMEDIATE

The following function works correctly but has multiple style problems. Identify at least four violations of PEP 8 and rewrite the function properly with a docstring. def c(L): s = 0 for i in L: if i>0: s=s+i return s
Show answer
The four main violations are: (1) the function name c is not descriptive; (2) the parameter L uses an uppercase letter, which PEP 8 discourages for variables; (3) the indentation is 2 spaces instead of 4; (4) there are missing spaces around operators (i>0 and s=s+i). The corrected version: def sum_positive(numbers): """Return the sum of all positive numbers in the list.""" total = 0 for value in numbers: if value > 0: total += value return total — this version uses descriptive names, 4-space indentation, proper spacing, and a concise docstring.

Question 4: APPLIED

You are building a program that converts temperatures between Celsius and Fahrenheit. Write a complete, PEP 8-compliant function called celsius_to_fahrenheit that includes: (a) a proper docstring with Args and Returns sections, (b) a named constant for the conversion factor, (c) descriptive variable names, and (d) at least one inline comment explaining a design choice.
Show answer
Here is a complete solution: # Conversion constants from the standard formula SCALE_FACTOR = 9 / 5 OFFSET = 32 def celsius_to_fahrenheit(temp_celsius): """Convert a temperature from Celsius to Fahrenheit. Args: temp_celsius: Temperature in degrees Celsius. Returns: Temperature in degrees Fahrenheit as a float. """ # Using named constants instead of magic numbers for clarity temp_fahrenheit = (temp_celsius * SCALE_FACTOR) + OFFSET return temp_fahrenheit This solution demonstrates several PEP 8 principles: the function name is snake_case and descriptive, the docstring clearly states the input and output, the constants SCALE_FACTOR and OFFSET use UPPER_SNAKE_CASE and replace magic numbers, and the inline comment justifies the design choice of using named constants.

Question 5: CRITICAL THINKING

Consider this comment: # Loop through the list placed above for student in roster:. Now consider this comment: # Skip students who dropped after the withdrawal deadline placed above if student.status != 'withdrawn':. Explain why one comment is useful and the other is not, connecting your reasoning to the principle that good names reduce the need for comments. Then propose a scenario where even the second comment could be eliminated through better naming.
Show answer
The first comment (# Loop through the list) is useless because the code for student in roster: already says exactly that. The descriptive variable names student and roster make the comment redundant — it violates the principle of explaining "why" rather than "what." The second comment is valuable because it adds context the code alone doesn't convey: the withdrawal deadline is a business rule from outside the program, and a reader wouldn't know why we're filtering withdrawn students without it. However, even this comment could potentially be eliminated through better naming. If you defined a helper function like def is_enrolled_after_deadline(student): or created a filtered list called active_students = [s for s in roster if s.status != 'withdrawn'], the name itself would carry the explanation. This illustrates the deep principle that the best comment is code that doesn't need one — but when business logic is involved, a brief explanatory comment is still appropriate.

SUMMARY

Lesson Summary

Summary

Python's official style guide, PEP 8, establishes the conventions that make Python code universally readable. The most important rules to remember are: use 4-space indentation for every code block, name variables and functions in snake_case with descriptive words, use UPPER_SNAKE_CASE for constants, and always put spaces around operators and after commas. These conventions aren't just about aesthetics — they directly reduce bugs and make collaboration possible.

For documentation, use docstrings (triple-quoted strings) as the first line inside every function to describe its purpose, parameters, and return value. Use inline comments sparingly to explain why you made a decision, not what the code literally does. Remember that the best code is self-documenting — well-chosen names can eliminate the need for many comments. Finally, refactoring — rewriting working code for clarity — is a normal, essential part of the programming process, not a sign that you did something wrong the first time.

Varsity Tutors • Computer Programming 1 (Python) • Style Conventions & Comments