Functions, exceptions and files
Writing a function you can reuse, handling errors without hiding them, and reading a file safely.
Once you can store data, the next screening topics are functions, error handling and files. Each has one idiom worth memorising.
Functions
def net_wpm(gross, errors, minutes=1):
# Net words per minute: gross minus one word per error.
return max(0, gross - errors / minutes)
net_wpm(45, 8) # 37.0
net_wpm(45, 8, minutes=2)
Default arguments make a function flexible without many versions. Keep a function to one job and give it a one-line docstring; interviewers read the docstring first.
Exceptions
try:
n = int(text)
except ValueError:
print("Please enter a whole number")
else:
print(n * 2)
Catch the specific exception you expect. A bare except: hides real bugs and is the thing reviewers flag most often. int("abc") raises ValueError, d["missing"] raises KeyError, [1][5] raises IndexError.
Files
with open("scores.csv", encoding="utf-8") as f:
for line in f:
name, wpm = line.strip().split(",")
print(name, int(wpm))
The with block closes the file even if an error happens inside. For CSV with quotes or commas in values, use the csv module; for JSON, json.load(f) returns a dict.
A small exercise
Write a function that reads the file above and returns the name with the highest WPM. It needs a loop, a comparison, and a split. That is the shape of most take-home tasks for junior roles.
More in Programming