Best Practices

You've now covered the full Core Python track, from syntax and data types through OOP, iterators, decorators and regular expressions. This final page is a capstone checklist: a set of habits that separate code that merely works from code that is readable, maintainable, and idiomatic. Keep it as a quick reference for every script you write from here on.

1. Follow PEP 8 Style Conventions

PEP 8 is Python's official style guide. Consistent style makes code easier for you and everyone else to read six months from now.

# good: snake_case, 4-space indentation, meaningful names
def calculate_total_price(unit_price, quantity):
    return unit_price * quantity

# avoid: camelCase, cryptic single-letter names
def calcTP(p, q):
    return p * q

2. Use f-strings for String Formatting

Since Python 3.6, f-strings are the clearest and fastest way to build strings from variables — prefer them over the older % operator or .format().

name = "Sonu"
score = 95

# good
print(f"{name} scored {score} points")

# avoid
print("%s scored %d points" % (name, score))
print("{} scored {} points".format(name, score))
  • Prefer f"..." for readability and performance.
  • See Strings for a full refresher on string formatting.

3. Prefer Comprehensions, But Don't Overdo Them

List and dict comprehensions are a concise, Pythonic way to build a new collection from an existing one for simple transformations and filters.

# good: simple, readable transformation
squares = [n ** 2 for n in range(10)]
even_squares = {n: n ** 2 for n in range(10) if n % 2 == 0}

# avoid: nested, unreadable one-liner
result = [y for x in data if x > 0 for y in x.items() if y[1] is not None]
  • Use a comprehension when it reads as a single clear thought.
  • Fall back to a plain for loop once you need multiple conditions or nested loops — see Lists and Dictionaries.

4. Always Use with for File Handling

The with statement guarantees a file is closed automatically, even if an error occurs while reading or writing it.

# good: file is always closed, even on error
with open("data.txt") as f:
    contents = f.read()

# avoid: easy to forget f.close(), especially after an exception
f = open("data.txt")
contents = f.read()
f.close()
  • Use with open(...) as f: for every file you open.
  • See File Handling for the full picture.

5. Catch Specific Exceptions

A bare except: silently swallows every error, including ones you didn't anticipate (like a typo causing a NameError), making bugs much harder to track down.

# good: only catches the error you expect
try:
    value = int(user_input)
except ValueError:
    print("Please enter a valid number")

# avoid: hides every possible error, even unrelated bugs
try:
    value = int(user_input)
except:
    print("Something went wrong")
  • Catch the exact exception type you expect (ValueError, KeyError, FileNotFoundError, etc.).
  • See Exception Handling for more patterns.

6. Use Virtual Environments for Every Project

A virtual environment isolates each project's dependencies, so installing a package for one project never breaks another.

# create and activate a virtual environment
python -m venv venv
venv\Scripts\activate     # Windows
source venv/bin/activate  # macOS/Linux

pip install requests
  • Create a fresh virtual environment per project, never install everything globally.
  • Revisit Installation & Setup if you need a refresher on setting one up.

7. Write Docstrings for Functions and Classes

A docstring documents what a function or class does directly in the code, so tools like help() and IDEs can show it, and other developers (including future you) don't have to guess.

def calculate_discount(price, percent):
    """Return the price after applying a percentage discount.

    Args:
        price (float): the original price.
        percent (float): the discount percentage, e.g. 20 for 20%.
    """
    return price - (price * percent / 100)
  • Add a short docstring to every public function and class.
  • See Functions for more on defining functions well.

8. Favor Readability Over Cleverness

Python's own design philosophy values simple, explicit code over dense, clever one-liners. Run import this in any Python shell to see "The Zen of Python" — its guiding principles include lines like "Readability counts" and "Simple is better than complex."

import this  # prints the Zen of Python
  • If a one-liner needs a comment to explain itself, it's probably better split into a few clear lines.
  • Optimize for the next person reading your code, not for showing off a trick.

Congratulations! You've completed the Core Python track — from your very first print() statement all the way through classes, iterators, decorators and regex. These fundamentals are exactly the foundation you'll need for the Django, Flask, and data science tracks coming soon to this site. Hit Next below to head back to the Python hub and see what else is waiting for you.