TK Study

Software Engineering › Learn step by step › Python, SQL and pseudocode

Item 417 of 426 · Python, SQL, pseudocode and CSS patterns, 24 of 33

Python validation function pattern

Code pattern

Jump to a topic
  1. Exam format, question types and command words (46)
  2. Year 11: Programming Fundamentals (69)
  3. Year 11: The Object-Oriented Paradigm (33)
  4. Year 11: Programming Mechatronics (29)
  5. Year 12: Secure Software Architecture (57)
  6. Year 12: Programming for the Web (59)
  7. Year 12: Software Automation (35)
  8. Year 12: The Software Engineering Project (47)
  9. Diagrams and modelling tools (18)
  10. Python, SQL, pseudocode and CSS patterns (33)

See every item in the sequence

Definition

Loop until the input is valid, using try/except for the conversion and if for range checks.

Example

while True: try: n = int(input()) ... except ValueError: ...

Found in: syllabus, course specifications, sample exam and familiarisation guidelines, school notes, past SDD papers.

Where you'll use it in the test

Syllabus area: Code patterns.

Question types it can appear in

  • Python: Input validation (sample Q18b, fam Q9b)

Where it has appeared in the paper

Secure Software Architecture (Part B, C). Part letters follow each paper’s own layout.

Related past questions

How to use it

A model sentence

General advice, built from the definition and example above

Code pattern: “Loop until the input is valid, using try/except for the conversion and if for range checks.” Then apply it: while True: try: n = int(input()) ... except ValueError: ...

In a short answer, give the definition in your own words first, then tie it to the situation in the question. Do not copy the example above unless it fits the scenario.

Official worked answer

Sample exam Q18b (3 marks): Developing secure code (Python input validation) (3 marks): official criteria and sample answer

Criteria

3: Correct function in Python to check whether a username satisfies the rules. 2: Partially correct function. 1: Some understanding of the problem and Python.

Sample answer

def validate_username(username): valid = True

 # length check
 if len(username) < 8:
      valid = False
 elif (not username[0].isupper()):
      valid = False
 elif (not username[-2].islower()):
      valid = False
 elif (not username[-1].isdigit()):
      valid = False

 return valid

Open the question page

Go deeper

Check yourself

Write or say the “Python validation function pattern” pattern from memory: the syntax and what it does.

Reveal the answer

Loop until the input is valid, using try/except for the conversion and if for range checks.

Example: while True: try: n = int(input()) ... except ValueError: ...

Could be tested as: Python.