Validation, authentication and strings
Adding length, range, presence, type and format checks to a program, re-asking until the input is valid, logins with stored details and a limited number of attempts, and string handling with slices, case and character codes.
Validation in a program
Validation checks that input is sensible before the program uses it. It cannot check that the data is true.
- Presence check: something was entered:
text != "". - Length check:
len(text)is within limits. - Range check: a number is between two limits.
- Type check: the input is the right kind of data.
code.isdigit()is True when every character is a digit, so check it beforeint(), which would crash on letters. - Format check: the text follows a pattern, such as one @ with a full stop after it.
To keep asking until the input is valid, read once before the loop and again at the end of each pass:
n = int(input())
while n < 1 or n > 12:
print("Out of range")
n = int(input())The rest of this lesson and its 10 practice questions are in Plus.
Screen 1 of 4, free to read.
- 10 exam-style questions, marked as you go, each with a worked solution
- Anything you get wrong is saved to your flashcards