Data Validation
Data validation checks that data follows your rules before you use it, such as "a whole number from 0 to 120".
Typed answers arrive as text, so validation usually means two steps: check the text, then convert it and check the value.
Convert text and numbers
input() returns text, even when someone types digits.
int("12")converts whole-number text to an integer.str(12)converts a number to text.
age = int("12")label = "Age: " + str(age)print(age + 1)print(label)The output is 13 and Age: 12.
int("3.5") and int("twelve") raise ValueError, which stops the
program. So check the text before converting it.
Check the digits, then check the range
.isdigit() is True when the text is not empty and every character is a
digit.
print("12".isdigit())print("twelve".isdigit())print("-1".isdigit())print("3.5".isdigit())print("".isdigit())Only "12" prints True. Letters, ., - and spaces are not digits.
Once the text is digits, int() cannot fail. Then check the number's range.
score_text = "105"if not score_text.isdigit(): print("Not a whole number")elif int(score_text) > 100: print("Too big")else: print("Valid score:", int(score_text))"105" passes the digit check but fails the range check, so this prints
Too big. Digit text is never negative, so only the top limit needs a check.
See also: Reading Input, Comparisons and Logical Operators, if, elif, else, Membership Testing.
Your turn
A month must be a whole number from 1 to 12. Print Valid month if
month_text is one, and Not a month otherwise. Check the text before
calling int(), then check both limits.
Not a month
month_text = "0"# check the text, then the range, and print Valid month or Not a monthAdvanced reading
- Converting and checking numbers —
float(), negative numbers and whyint(float(text))can hide bad data. - Asking again until the answer is valid — a
whileloop that re-asks, allowed answers, and skipping bad records. - try and except — catch the
ValueErrorfromint()instead of checking first. - Regex character classes and anchors — check a whole answer against a pattern.