Codzy

Code quality

Code is read far more often than it is written. PEP 8 is Python's official style guide: 4-space indentation, variable and function names in snake_case, classes in PascalCase, constants in UPPER_CASE, lines that aren't too long. Choose names that say what things do: average(scores) rather than f(l).

A docstring (text in triple quotes right under the def) explains what a function is for. Free tools help you: Ruff or Flake8 spot problems, and Black reformats the code automatically. Also keep your functions short, each with a single responsibility.

# Hard to read:
def f(l):
    t=0
    for x in l: t+=x
    return t/len(l)

# Clean (PEP 8, clear names, docstring):
def average(scores):
    """Return the average of a non-empty list of numbers."""
    total = sum(scores)
    return total / len(scores)

print(f([10, 20]), average([10, 20]))
print(average.__doc__)

Start the lesson