Kahibaro
Discord Login Register

Writing clean and readable code

Why Clean Code Matters

Clean, readable code is easier to:

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:

Guidelines:

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:

Code Layout and Formatting

Consistent formatting makes code easier to scan.

Indentation and Spaces

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()

Following PEP 8

PEP 8 is the official Python style guide. Key ideas you’ve seen:

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:

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

# 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:

  def greet(name):
      """Print a greeting for the given name."""
      print(f"Hello, {name}!")

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:

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:

…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:

Examples:

Consistency makes patterns easier to spot.

Using Tools to Help You

You don’t need to enforce style manually. Some tools can help:

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: 13

Comments

Please login to add a comment.

Don't have an account? Register now!