KAHIBARO Bookshelves
Discord Login Register

18.2. Writing clean and readable code

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, not tmp (unless very short-lived)

Consistent naming is more important than “perfect” naming.

Constants

Values that don’t change are usually written in ALL_CAPS:

python
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_case for 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 helpful

Comment 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 * height

Practical 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_name in one place and username in another, it’s confusing
  • If you sometimes write getData() and sometimes get_data(), pick one and stick to it (prefer get_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:

  1. Names
    • Do variable and function names describe their purpose?
  2. Structure
    • Is the code split into functions instead of one long block?
  3. Formatting
    • Is indentation consistent?
    • Are there spaces around operators and after commas?
  4. Comments and Docstrings
    • Are tricky parts explained?
    • Do important functions have a short docstring?
  5. 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.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms