Validate structured output
Reach for each comma and return to your resting position. · 139 words
A schema specifies the expected shape of data. Suppose a program expects an object with a numeric field named count. An answer with that field set to twelve passes the type check. A negative number also passes a numeric type check. Add a range check if a count must represent a quantity of items.
Try a string containing the digits one and two. A human may read it as twelve, while a strict schema expects a number. Decide explicitly whether conversion belongs in your program. Then test zero, a negative integer, a fraction, and a missing field. A different check is needed for factual accuracy: a count of twelve can be perfectly valid in form and wrong for a shelf holding eleven books. Match the type check, the range check, and the factual check to their own failure cases.
Check your recall
Why check the range after checking the type?
Check your answer
A negative value is numeric but cannot count items in this task.
Worked exercise
Predict the two outputs. Count must be a nonnegative whole number.
def valid(count):
return type(count) is int and count >= 0
print(valid(3))
print(valid(-1))Check your reasoning
The first call prints True. The second prints False because -1 is below zero.
Sources and credits
Original KeyTouch lesson. Background reading · Microsoft · Generative AI for Beginners.