Python from first program to best practices / Python best practices
Make Python readable and testable
Use names, functions, types, tests, and errors to make change safer.
Estimated time: 25 minutes
Learning outcome
By the end of this lesson, you will be able to take a messy Python script and make it readable, add type hints, write a simple test, and handle errors gracefully.
Why readability matters
Code is read far more often than it is written. A function you wrote last week might look like someone else's code today. Clear names, consistent structure, and comments make your future self grateful.
Good names
Compare these two:
# Bad
def f(x, y):
return x * 60 * y
# Good
def minutes_to_hours(minutes, days):
return minutes / 60 * days
The second version does not need a comment. The names explain everything.
Type hints
Python lets you add type hints that tell readers (and tools) what kind of value a function expects and returns:
def greet(name: str) -> str:
return "Hello, " + name
The name: str means name should be a string. The -> str means the function returns a string. Python does not enforce this at runtime, but tools like mypy can check it.
Writing a simple test
Create a file test_calculations.py:
from calculations import add
def test_add():
result = add(2, 3)
assert result == 5, f"Expected 5, got {result}"
Run it with:
python -m pytest test_calculations.py
If the test passes, you see a green dot. If it fails, you see what went wrong.
Handling errors
Programs break. Files get deleted, networks go down, users type letters where numbers belong. You can handle these gracefully with try and except:
try:
number = float(input("Enter a number: "))
print("Half of that is", number / 2)
except ValueError:
print("That was not a number. Please try again.")
If the user types hello, the program does not crash. It prints a friendly message and keeps going.
Common beginner mistakes
- Using single-letter variable names outside of loop counters.
i,j,kare fine for loops.x,y,zfor data are not. - Skipping tests because "the code is simple." Simple code changes in ways you do not expect. A test catches that.
- Bare
except:without specifying the error type. This catches everything, includingKeyboardInterrupt(Ctrl+C). Always useexcept SomeError:.
Practice task
Take the temperature converter from the previous lesson. Add type hints, rename variables to be clear, wrap the conversion in a function, and add a test that checks 98.6 Fahrenheit gives 37.0 Celsius.
Recap
- Use clear, descriptive names for variables and functions.
- Add type hints to document what functions expect and return.
- Write small tests with
assertto catch regressions. - Handle expected errors with
try/exceptinstead of letting the program crash.
Next step
With readable, tested code under your belt, the next lesson introduces algorithms and data structures — the tools for reasoning about performance.