BLOCK BAD
INPUT
Learning
Objective
Students will be able to:
know how to recognise, avoid and fix out of bounds
errors
how to block bad input to the program
USING INDEX NUMBERS
You can print, edit and delete a single element of a
list by giving the index number.
Index number can be included in code:
Or can be input by the user:
USING INDEX NUMBERS
But only some numbers will work. If the list have 4
items, they are numbered 0 to 3.
If index number is bigger than 3, crash
Error message:
This is called as out of bound error.
Length of a list
The function len( ) will tell you the length of a string or a list.
Type this in the Python Shell
len(“hello”)
You will see the integer 5, because the string hello has five
characters
Now try these commands
What numbers are allowed?
If we know the length of a list, we know what numbers are allowed.
Number range from 0 to n-1
If a list have 10 items, index numbers go from 0 to 9
if a list have 100 items, index numbers go from 0 to 99
Program to print this information
Activity
Validation
What is the user still makes a mistake? The progarm will crash
A program which does not crash is called a robust program. The
user might input bad data, but the program will not crash
To make sure your program is robust, you can add a command
that blocks bad input. This is called a validation check.
If ..... Else
An if structure begins with a logical test. Test if the number input by the user
is smaller than the length of the list
If the test is True, carry out command
If the test is False, show and error message
While loop
Alternative
A while loop ask for input until the value matches the
requirement of the program
The program just now uses the relational operator >= which
means greater than or equal to
You will get an out of bound error if you enter a number:
That is greater than the length of the list
That is equal to the length of the list
Thank You