Designing Fool Proof Code
There are several techniques that could be used in Python to stop the user entering invalid options. This page introduces you to some of the simplest approach to doing this.
Only Allowing Numbers
This example uses the try catch method to stop the user entering anything apart from integers, as the data type for the input is set to int the code loops if you enter anything else instead of giving you a python script error.
Allowing Specific Values
This example uses an array (List) to store the possible options a user can chose from, if what they enter is not in the array then the code repeats the question until they enter something that is.
I have combined this with using .title() set the style of the user input for example:
- .lower() - Turns anything entered into lowercase
- .upper() - Turns anything entered into uppercase
- .title() - Put a capital letter for the first letter of each word and lowercase for the remaining letters.
Length Checks For Strings
Sometimes it is useful to be able to control how many letters or characters your user is allowed to enter. Although this did not guarantee they enter the correct information it will ensure it is in theory valid data.
You can use length check with any operator to check the data provided.
< Less Than
> Greater Than
>= Greater Than or Equal To
!= Not Equal To
Equal To Specific Number
Lesson Than or Equal To
Write a python program that asks the user to enter their name and phone number. You should use suitable input sanitisation to ensure their name contains only letters of the alphabet and that their phone is exactly 11 numbers long.