GCSE Computer Science
Programming 4
good coding practice and subprograms
Name:
Teacher:
1|Page
Validating User Input
Validation is the automatic checking of entered data to ensure that it is reasonable. It is relatively
easy to program validation checks.
There are various types of validation check:
• Presence: data can’t be empty
• Length: eg telephone number must be at least 8 digits
• Range: eg age between 11 and 18
• Lookup: eg year group in [U4, L5, U5…]
• Type: integer, float, string…
Exercise 1
Validation – length check
Write a program that asks the user to input a password and then uses a length check to make sure
the password is at least eight characters long. If it is shorter than eight characters the user is asked to
enter a different password.
Exercise 2
Validation – presence check and range check
Write a program that asks the user to enter their name and age. It should use a presence check to
make sure that a name has been entered and a range check to the age. If no name has been entered
the user is prompted to enter a name again with an appropriate message. If the age is outside the
range 0 to 100, the user should be asked to confirm if this is correct and if not re-enter it.
Exercise 3
Validation – lookup check for characters in a list
Write a program that asks the user to select from a menu of options by typing in a letter:
S to save
L to load
Q to quit
P to print
The program should continue displaying the menu and user entry prompt until the user chooses to
quit. If the user enters anything other than the 4 valid letters, an error message should be displayed.
2|Page
Type checks are more difficult as the input command always returns a string. You only know that
erroneous data has been entered when you try to convert it to integer or real and the program
crashes. To avoid this, you can use the try command:
While True:
numberStr = input(“Enter a number to see its times table”)
try:
number = int(numberStr)
except:
print(“you must enter an whole number”)
else:
break
The full syntax of the try command is:
try:
# code to try
except <type of error>:
# error code
Except <type of error>:
# error code
else:
# non-error code
Error types include ZeroDivisionError and ValueError
Exercise 4
Validation – type check
Write a program that asks the user to enter their age and checks that they have entered an integer. It
should display a message asking them to enter a number if they have not done so.
Exercise 5
Write a program that asks the user to enter an email address and then checks the string entered to
make sure it contains an ‘@’. If it does not, the user is prompted again to enter an email address.
Extension: what other checks can be made that would apply to all e-mail addresses?
Exercise 6
Try command: divide by zero error check
Write a program that asks the user for two numbers, divides the numbers and displays the answer. If
the program generates a divide by zero error, display a message to explain.
Extension exercise
Write a program that asks a user for a password and then gives an assessment of its strength:
Less than 8 characters: very weak
More than 8 characters but only alphabetic (all upper case or all lower case): weak
More than 8 characters with only alphabetic but a mixture of cases: moderate
More than 8 characters with uppercase, lowercase and numeric : strong
More than 8 characters with upper/lowercase, numeric and non-alphanumeric: very strong
Hint: research string methods like .isalpha() and .isupper()
3|Page
Verifying User Input
Checking that data is correct is called verification and can be much more difficult than data
validation. It is sometimes achieved by
entering the data twice and checking that the two match, for example, when you change
your password
checking against other data in a database, for example when you phone and quote your
customer number, you may be asked to confirm the first line of your address
Good Coding Practice
The most important thing about any code that is written is that it works. Efficiency is also important,
but not as importance as effectiveness.
However people must read code as well as machines. To help a human understand code that is
written, we should follow some guidelines:
Use indentation
Add comments
Use meaningful variable names
Use ‘white space’ to split the code up into blocks
Indentation
Indentation means adding ‘tabs’ in front of every line of code which is part of a block so that it is
clear which commands form part of a block.
These blocks could be IF statements, FOR loops or subprograms.
Here is some indented pseudocode
FOR i = 1 TO 100 DO
SET print_number TO true
IF i is divisible by 3 THEN
SEND "Fizz" TO DISPLAY
SET print_number TO false
ENDIF
IF i is divisible by 5 THEN
SEND "Buzz" TO DISPLAY
SET print_number TO false;
ENDIF
IF print_number
SEND i TO DISPLAY
ENDIF
END FOR
4|Page
Here is the same code which has not been indented.
FOR i = 1 TO 100 DO
SET print_number TO true
IF i is divisible by 3 THEN
SEND "Fizz" TO DISPLAY
SET print_number TO false
ENDIF
IF i is divisible by 5 THEN
SEND "Buzz" TO DISPLAY
SET print_number TO false;
ENDIF
IF print_number
SEND i TO DISPLAY
ENDIF
END FOR
Exercise 7
Why is the indented code easier to read?
Because it is easier to see that which code is in which sub program or loop and also that it will be
More organized as a result
Comments
Comments are pieces of text inside of a program which are not run. Their purpose is simply to inform
the reader of the purpose of a line or section of code.
Here is some Python code without comments. Do you know what it does?
x=1
y=1
for i in range (1,100):
z=x+y
print(z)
x=y
y=z
5|Page
Here is the same code with comments and white space
# this program generates the first 100 numbers of the Fibonacci sequence
# by Mr Bartram
# started 1/6/2015, last updated 31/6/2015
# initialise the variables
x=1
y=1
# loop 100 times
for i in range (1,100):
# print one number in the series
z=x+y
print(z)
x=y
y=z
Your programs should always start with 3 comments similar to the program above.
Exercise 8
List two different people who might need to view your code at some point and explain why
comments would be useful to them.
1) People who known some level of programming but doesn’t understand your code. You can
display in such a way that you could explain one by one, therefore making it clearer.
2) People who don’t know programming. With comments, you’re allowing a step by step guide
to everything, meaning that it will be clearer and more consise
Variable Names
We need to store data in a variable. As the programmer, we define the names of the variables.
Variables can be given any name you want within the syntax rules of the programming language but
they should always be descriptive and explain the data they will store. Someone should be able to
look at a variable and take an educated guess as to its purpose.
6|Page
Exercise 9
Consider a program in which we want to store and use a person’s forename. Below are two examples
of variable names. Fill out the table stating whether the variable is good or bad and explain your
decision.
Example Poor/Good Why it is poor or good?
stuff poor To general, doesn’t reflect the actual purpose of the program
forename Good Details what the purpose of the variable is about
DoB Good Can see what the purpose of the program according to the initials
A too simplistic acronym, can’t understand what the program is
m Poor
about
Errors & Testing
Errors (or bugs) happen all the time in programs both during development and even when a program
has been released to the public.
Exercise 10
What is a program error?
Programming errors are where the code outputs a value that is not fitting to the expected value
Types of Error
There are three main types of error
Error Explanation
Where the written code does not meet the rule of the rules of the language
Syntax
and therefore cannot be understood by the computer
The code is syntactically correct and will run. However the outcome is not
Logic
what was expected/required
The code is syntactically correct and will run. However the code causes the
Runtime
program to crash.
7|Page
Exercise 11
Complete the quiz on FreeLearning
Test Plans
A test plan is a document given to a tester (a person who sits with the finished program and checks
that it works as expected).
The document is simply a table with a list of tests on it. Each test will state
A description of the purpose of the test
The specific data that will be used such as
o ‘Hello’
o 2
o False
The result that is expected from the test
The actual result when the test was performed
Whether the program passed or failed the test
A template for this test document is on the shared drive. Use it for all your testing.
Test Data
Each feature or functional of the program should, where possible, be tested with
normal data
boundary data
erroneous data.
Exercise 12
Write down a definition for each of the types of test data we can put into a program
Test type Explanation
Data that is in the boundary and is expected
Normal
The boundary of data excepted. For example. 1-50 range, 1 and 50 would
Boundary be boundary valuese
Data that is not expected and out of the boundary
Erroneous
8|Page
Exercise 13
Give examples of valid, invalid and boundary data for these scenarios.
An A grade is given to marks between 70 and 80.
Boundary Boundary
Invalid Valid Invalid
(still valid) (still valid)
asdf 70 77 80 df
The amount of battery charge is given as a percentage between 0% and 100%.
Boundary Boundary
Invalid Valid Invalid
(still valid) (still valid)
asdf 0% 69% 100% as
Age range for people allowed to view a 15 film.
Boundary Boundary
Invalid Valid Invalid
(still valid) (still valid)
15 61 infinity 0
asdf
Exercise 14
Here is a Python program.
# exercise 14
# by A Programmer
# Created on 5/5/2004
questions = ["1+1 =?", "2*6=?", "25-6=?"]
answers = [2,12,19]
count = 0
name = input("Enter your name")
age = int(input("Enter your age (5-11 only)"))
gender = input("Enter your gender (male or female only)")
for i in range (0,len(questions)):
usersAnswer = int(input(questions[i]))
if usersAnswer == answers[i]:
print("That was correct")
count = count + 1
else:
print("That was incorrect")
print(count)
Create a test plan for this program using the template. Copy the program from the shared area and
test it.
Extension: amend the program to resolve the faults you have found. Carry out the same tests on your
improved program.
9|Page
Sub Programs
As programs get larger – keeping them as one single set of instructions can make the program
confusing and complex.
Large problems can be decomposed into smaller parts. This is true for real life as well. You can
consider “getting through the day” as one single problem. However this can be broken down into sub
problems:
Getting up
Washing
Eating breakfast
Getting to school
Registering
Learning
Break times
Travelling home
Eating dinner
Doing homework
Getting ready for bed
Some of these may be broken down further into smaller parts. In a computer program, each part is a
sub-program. There are two types of sub-program
functions: subprograms that take input, perform operations and return a result
procedures: subprograms that take input and perform operations
Defining a Procedure
A procedure definition has three parts:
Name: what the procedure is called
Parameters: the values that the procedure will use
Commands: what the procedure does
In pseudocode, a procedure is defined like this:
PROCEDURE name (parameter1, parameter2… )
BEGIN PROCEDURE
commands
END PROCEDURE
In Python, a procedure is defined like this:
def name (parameter1, parameter2…):
commands
For example:
def printMultiples(value, upTo):
for x in range (1,upTo+1):
print(x, ‘times’, value, “=”, x * value)
10 | P a g e
Running a Procedure
A subroutine (function or procedure) will not work unless it is called.
In pseudocode and Python, you call a procedure like this:
procedureName(argument1, argument 2)
The arguments are the values that will be passed into the procedure. They must be listed in the same
order as the procedure definition, so:
printMultiples(2,7)
would call the procedure call printMultiples and set value to 2 and upTo to 7.
Defining and calling functions
Functions are very similar to procedures but they return a result.
In pseudocode, a function is defined like this:
FUNCTION name(parameter1, parameter2…)
BEGIN FUNCTION
commands which must include RETURN
…
END FUNCTION
In Python, a function is defined in exactly the same way as a procedure but at least one of the
commands must be return.
For example:
def listMultiples(value, upTo):
list = []
for x in range (1,upTo+1):
list.append(x * value)
return list
A function returns a value so it is called in a different way, either:
variable = functionname(parameters…)
o for example, x = listMultiples(2,7)
command(functionname(parameters)
o for example, longlist.append(listMultiples(2,7)
Subprograms are usually defined at the start of a program immediately after any import commands
and the initial comments (purpose, programmer name and date). It is good practise to use a #main
program comment after the subprograms to make it clear where the main program starts.
11 | P a g e
Exercise 15
Advantages of subprograms
Explain what you think the advantages are of using sub-programs? Think about real life, why is it
useful for a major task – like running a school – to be broken up into smaller tasks?
So that the lines of codes would be decreased, making programming much more quicker
So that people can easily understand the logic of every different part of the program
So that programmers can double check any logical flaws are in said program
Exercise 16
Copy this program from the shared area and run it.
def procedure_one(myName):
print("Hello",myName)
# main program
procedure_one(“Edward”)
This will run procedure_one and pass the argument “Edward” into the subprogram as the parameter
myName.
Run the procedure a few times passing different names into the file.
Exercise 17
Write a procedure called name_age in the same Python file as the previous exercise.
Use parameters to pass a name and age into the procedure.
The procedure should display this information appropriately on the screen.
Run the procedure several times passing different names and ages.
Exercise 18
Write a procedure called square in the same Python file. Use a parameter to pass into the
procedure the length of a side and it should display the area of the square.
Run the procedure several times passing different sizes of box.
12 | P a g e
Exercise 19
Write a procedure called numbers in the same Python file. Use parameters to pass two numbers
into the procedure.
The procedure should then count from the first number to the second number.
Exercise 20
Amend your program so that it displays a menu offering the 4 options above and an option to quit.
The program should run until the user chooses to quit. Each time it runs, it should ask the user for
the data appropriate to the menu option and call the appropriate procedure.
Exercise 21
Copy this program from the shared area and and run it (ammended
# outputs a number
def display(number,answer,type):
print("This number {0} has been {2} the answer is {1}".format(number,answer,type))
# squares a number
def cubed(number):
ans = number * number*numbers
return(ans)
# main program
amount = int (input("Please enter number : "))
for next in range(1,amount):
answer = cubed(next)
display(next,answer,"cubed")
Explain what this program does.
This program asks for a number then find the square of the number, afterwards sending it all to
display.
Explain why the two subprograms are used in different ways.
So that one sub program will be handling one task
Amend the program to include another subprogram that calculates the cube of the number and
displays it.
13 | P a g e
Exercise 22
Subprogram will often run even if some of the parameters are not specified. .To achieve this, you
have to provide a default parameter value in the subprogram definition.
Copy this program from the shared area and and run it
def myFunction(name = “Fred”, surname = “Bloggs”, age = 21):
print("My name is {0} {1} and I am {2}".format(name, surname, age))
Explain what happens when these function calls are executed in the #main program:
myFunction("George","Wales",0)
Will print “My name is George Wales and I am 0”
myFunction("Amelia","Jones")
Will send “ My name is Amelia Jones and I am 21” to display
myFunction("Vicky")
Will send “My name is Vicky Bloggs and I am 21” to display
myFunction()
Send “My name is Fred Bloggs and I am 21” to display
Exercise 23
Create a basic calculator program which allows the user to
Enter two numbers
Chose an option from (+, -, *, /, ^)
o Each one of these options needs to have a subprogram associated with it
o The subprogram will have two parameters
o Using these parameters, the subprogram must output a value (so if the + option was
chosen, the sum of the two numbers would be output)
After a calculation has been performed, the user must be given the option to run another
calculation or quit
Hand in a test plan and evidence that the testing has been carried out as well as clear annotated
code.
14 | P a g e