Python Course 12: Robust and Secure Programming

  • Robust programming means writing programs that can cope with errors. One example would be to use data validation to avoid incorrect input.
  • Secure programming means writing programs that use security features such as passwords

You must check your validation with normal, boundary and erroneous data.

Examples

NOTE: All the following use while loops, not ifs! Why?

The following code checks that a value is entered

ans = input("Enter your choice")

while ans == "":
    ans = input("You must enter a value")

Test data: Erroneous: “” Normal: “Pizza”

The following code checks that the username is at least 6 characters long

ans = input("Choose your username")

while len(ans) <6:
    ans = input("Username must be at least 6 characters")

Test data: Erroneous: “Pizza” Normal: “Hamburger”

The following checks that someone is aged between 11 and 18

age = int(input("Enter your age: "))

while age < 11 or age > 18:
    age = int(input("Age must be between 11 and 18 "))

Test data: Erroneous: 8 Boundary: 11 Normal: 15

The following checks that someone is in a year 9 form

forms = ["9b","9h","9bh","9l","9m","9lm","9r","9w","9rw"]

f = input("Enter your form group: ").lower()

while f not in forms:
    f = input("Not a valid form group: ").lower()

Test data: Erroneous: “8qt” Normal: “9l”

Exercise

Write code to perform the following validation checks.

  1. Jockey club names cannot be more than 18 characters long. Write a validation check for these names. Test with the normal data “Ariel” and the erroneous data “supercalifragilisticexpialidocious”
  2. Modify your answer to question 1 so that blank names are also rejected
  3. Police officers in the UK are aged between 18 and 60. Write a validation check for this. Test your code with the following data: 25, 60 and 81
  4. A cafe sells the following drinks: tea, black coffee, white coffee, hot chocolate, lemonade. Write a validation check for the above drinks.

Extension

The following code demonstrate the instartswith and endswith functions

>>> s ="I never saw a purple cow"
>>> s.endswith("cow")
True
>>> s.startswith("I")
True
>>> "never" in s
True

Use them to write validation checks for the following:

This is an example of a URL: http://blue-coat.org

  1. URL check: does it end in .com or .org?
  2. Does it start with http:// or https://
  3. Simple check for email: does the string contain an ‘@’?
  4. More complex email check: does a string contain ‘@’ and end with .com or .org?

Leave a Comment