Rates — visits per member, spend per visit, items per basket — are derived by dividing one numeric answer by another. The catch is the denominator: if it can be zero, you have to handle that case before Python raises a division-by-zero error. In the example healthcare survey, we calculate annual visits per eligible household member.
The recipe
from survey import Recoder
r = Recoder(**globals())
annual_visits = r.get_value("annual-healthcare-visits") or 0
eligible_members = r.get_value("eligible-household-members") or 0
visits_per_member = annual_visits // eligible_members if eligible_members else 0
r.store_value("Visits per eligible member", visits_per_member)
How it works
Both answers are read with get_value, with or 0 guarding against blank responses, exactly as in the summing recipe.
The key line is the division. The expression annual_visits // eligible_members if eligible_members else 0 says: divide only when eligible_members is non-zero, otherwise store 0. Because 0 is falsy in Python, if eligible_members is a concise way to write "if the denominator is not zero". Without this guard, any respondent reporting zero eligible members would crash the script.
This recipe uses //, floor division, which returns a whole number. That is the right choice when the rate should be an integer count. If you want a fractional rate, use / instead and consider rounding for reporting:
visits_per_member = round(annual_visits / eligible_members, 1) if eligible_members else 0
Variations
When zero in the denominator means the rate is genuinely undefined rather than zero, storing 0 can be misleading — it will blend into your averages as a real value. In that case, store None so the respondent is excluded from rate calculations downstream:
visits_per_member = annual_visits / eligible_members if eligible_members else None
r.store_value("Visits per eligible member", visits_per_member)