Table of Contents
Why Clean Code Matters
Clean, readable code is easier to:
- Understand (for your future self and others)
- Fix (bugs are easier to spot)
- Extend (adding new features is safer)
- Reuse (you can copy ideas between projects)
Think of code as writing a clear set of instructions for another human, not just for the computer.
Naming Things Well
Good names are one of the biggest wins for readability.
Variables and Functions
Use descriptive, lowercase, snake_case names:
- Bad:
x,y,a1 - Better:
age,price_with_tax,user_input - Functions:
- Bad:
f(),do(),run1() - Better:
calculate_total(),get_user_choice(),save_to_file()
Guidelines:
- Use nouns for data:
user_name,file_path,shopping_list - Use verbs for actions (functions):
send_email(),load_data(),print_report() - Avoid abbreviations unless they are obvious: use
temperature, nottmp(unless very short-lived)
Consistent naming is more important than “perfect” naming.
Constants
Values that don’t change are usually written in ALL_CAPS:
MAX_ATTEMPTS = 3
PI = 3.14159
DEFAULT_LANGUAGE = "en"Structuring Code with Functions
Functions help break a long script into clear, named steps.
Instead of one long block:
print("Welcome")
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age >= 18:
print("Hello", name, "- you are an adult.")
else:
print("Hello", name, "- you are not an adult yet.")You can separate logic into functions:
def get_user_info():
name = input("Enter your name: ")
age = int(input("Enter your age: "))
return name, age
def describe_age(name, age):
if age >= 18:
print("Hello", name, "- you are an adult.")
else:
print("Hello", name, "- you are not an adult yet.")
def main():
print("Welcome")
name, age = get_user_info()
describe_age(name, age)
if __name__ == "__main__":
main()Benefits:
- Each function has one clear job
- The
main()function reads like a summary of what the program does - Easier to test or change individual pieces
Code Layout and Formatting
Consistent formatting makes code easier to scan.
Indentation and Spaces
- Use 4 spaces per indentation level (do not mix tabs and spaces)
- Put spaces around operators:
- Good:
total = price + tax - Bad:
total=price+tax - Put a space after commas:
- Good:
values = [1, 2, 3] - Bad:
values = [1,2,3]
Line Length
Try to keep lines at or under 79–100 characters. If a line is too long, break it:
message = (
"Hello, this is a long message that we break into multiple "
"parts so that it is easier to read."
)Blank Lines
Use blank lines to group related code:
def get_user_name():
return input("Enter your name: ")
def greet_user(name):
print(f"Hello, {name}!")
def main():
name = get_user_name()
greet_user(name)
if __name__ == "__main__":
main()- Blank line between function definitions
- No unnecessary empty lines scattered everywhere
Following PEP 8
PEP 8 is the official Python style guide. Key ideas you’ve seen:
snake_casefor functions and variables- 4-space indent
- Spaces around operators and after commas
- Short-ish lines
You don’t need to memorize it, but knowing it exists helps: search “PEP 8” when you’re unsure.
Writing Helpful Comments
Comments explain why, not just what.
When to Comment
Good times to add comments:
- Explaining why something is done in a non-obvious way
- Giving context or assumptions
- Marking tricky or easily-misunderstood sections
Example:
# Using a small sleep to avoid hitting the server too often
time.sleep(0.5)Avoid comments that simply repeat the code:
# Add 1 to x
x = x + 1 # <- this comment is not helpfulComment Style
- Use
#for single-line comments - Keep comments short and close to the code they describe
# Ask the user how many items they want to order
quantity = int(input("How many items? "))If you find you need long comments to explain code, that’s a hint the code itself might need to be simplified or split into functions.
Docstrings for Functions
Docstrings describe what a function does, its inputs, and outputs.
def calculate_area(width, height):
"""
Calculate the area of a rectangle.
Parameters:
width (float): The width of the rectangle.
height (float): The height of the rectangle.
Returns:
float: The area (width * height).
"""
return width * heightPractical tips:
- At minimum, one short sentence is already useful:
def greet(name):
"""Print a greeting for the given name."""
print(f"Hello, {name}!")- Use docstrings for functions you expect to reuse or share
Avoiding Repetition (DRY Principle)
DRY = “Don’t Repeat Yourself”.
If you copy-paste similar code, consider using a function or a loop.
Instead of:
print("Welcome, Alice")
print("Welcome, Bob")
print("Welcome, Charlie")You can write:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(f"Welcome, {name}")Or, if you repeat a process:
def greet(name):
print(f"Welcome, {name}")
greet("Alice")
greet("Bob")
greet("Charlie")Benefits:
- If you need to change the greeting, you change it in one place
- Less chance of introducing small, inconsistent mistakes
Handling Complexity
Even small programs can become confusing when they grow. To keep complexity under control:
Keep Functions Small
Aim for functions that do one clear thing. If a function:
- Is very long
- Has many different responsibilities
- Is hard to explain in one sentence
…split it into smaller functions.
Use Clear Structure
Typical main script layout:
import sys # imports at the top
def helper_function():
# helper functions next
...
def main():
# main logic
...
if __name__ == "__main__":
main()Consistent structure makes it easier to know where to look.
Consistency Over Perfection
You will see different styles in tutorials and code examples. The most important rule:
- Be consistent within your own project
Examples:
- If you use
user_namein one place andusernamein another, it’s confusing - If you sometimes write
getData()and sometimesget_data(), pick one and stick to it (preferget_data()in Python)
Consistency makes patterns easier to spot.
Using Tools to Help You
You don’t need to enforce style manually. Some tools can help:
- Code formatters:
black,autopep8, or built-in formatters in editors (VS Code, etc.)- They automatically reformat your code to follow common style rules
- Linters:
flake8,pylint, etc.- They point out possible mistakes and style issues
For a beginner, enabling “Format on Save” and basic linting in your editor is usually enough to learn good habits.
Practical Checklist for Clean Code
When you finish a small script or function, quickly ask:
- Names
- Do variable and function names describe their purpose?
- Structure
- Is the code split into functions instead of one long block?
- Formatting
- Is indentation consistent?
- Are there spaces around operators and after commas?
- Comments and Docstrings
- Are tricky parts explained?
- Do important functions have a short docstring?
- Repetition
- Did you copy-paste code that could be turned into a loop or function?
You don’t need to be perfect. Apply a few of these ideas at a time, and your code will become cleaner and more readable as you practice.