PythonProgrammingforN4 and 5
PythonProgrammingforN4 and 5
PythonProgrammingforN4 and 5
National 4/5
Multi-line Comments
It is good practice to insert a multi-line comment at the top of the program. This
comment should contain the name of the program, author, date and description of
what the program will do. Multi-line comments are started by 3 quotations marks
(""")and then closed with another three quotation marks (""").
1. """
2. Name: HelloWorld Program
3. Author: Mr Jack
4. Date: 10/06/2015
5. Description: This program will display "Hello World" on the screen
6. """
1. # Question 1
2. print("What is the capital city of France?")
3. answer = input()
Variable Types:
For National 4/5 Computing Science you only need to know five variable types.
Decimal Numbers.
Float 6.23, 5.00, -3.14
Floating Point Numbers
"Mesopotamia"
3.14519
True
"Y"
"SA12 PQR"
.765432
98.
"Britannia"
"#"
False
0784569412
"Daffodil"
Declaring variables:
It is good practice to create all the variables that you are planning to use at the top
of your program, just under the multi-lined comments. When declaring variables, you
first type the identifier you have chosen along with the variable type.
Code:
1. # Initialising Variables
2. name = ""
3. distance = 0
4. time = 0
5. speed = 0.0
In the example above, the user has four variables, one string, two integers and one
float.
Time_left_in_seconds
Next.in.list
Number8
Kjyg
5red
number#1
Time@start
Post code
Name&address
Ask the user for the length and breadth of a rectangle, multiply the 2
numbers together to calculate the area. Display the area back to the
user.
In this example, the program will need three variables; the length, breadth and
somewhere to store the answer (the area). Each variable will need to be given a
useful identifier and a variable type.
Program 1
The program should ask the user to enter the scores for their Maths,
English and Computing tests. The program should then add them
together then divide the total by 3 in order to calculate the average.
The average test score should then be displayed to the user.
_____________________________________
_____________________________________
_____________________________________
_____________________________________
Program 2
Ask the user to enter how much money they get paid per month, the
number should be multiplied by 12 to calculate a yearly salary. Display
the yearly salary to the user.
_____________________________________
_____________________________________
_____________________________________
1. """
2. This line will ask the user to enter their name. When the user
3. enters their name via the keyboard it will be stored in the
4. variable named ‘name’
5. """
6. print("What is your name?")
7. name = input()
8.
9. """
10. This line will ask the user to enter their age. When the user
11. enters their name via the keyboard it will be converted to an
12. integer and stored in the variable named ‘age’
13. """
14. print("What is your age?")
15. age = int(input())
Task 1a : Your first computer task will be to create a program that will
display “Hello World” on the screen. Name the program
“helloworld.py” and save it in a new folder titled “Python” where you will save all
your future programs.
Task 1b: Create a program that will ask the user for their name (input) and then
display “Hello” and then their name onto the screen (output).
Task 1c: Create a program that will ask the user a question of your choice. The
answer must then be displayed on the screen.
Once all the questions have been answered, the answers must then be displayed in
the following way.
Syntax Used:
Add +
Subtract -
Divide /
Multiply *
Equals / Assignment =
Order of Operations:
Brackets can, and should, be used to
structure your calculations out
correctly. Please remember to
structure your calculations in the
correct way, just like you do in Maths.
Code:
Answer = 4 × 3 + 2
Task 2a: Write a program that will calculate the area of a rectangular
room. All variables should be integers.
Task 2b: Write a program that will ask the user for the distance, the time and then
calculate the speed.
Tip: When carrying out a divide, you are likely to end up with a decimal number.
Think carefully about what data types should be used.
Task 2c: Write a program that will ask a pupil what test marks they received for the
Maths, English and Computing exams. The program should then calculate the
average score over the 3 tests.
Task 2d: Write a percentage calculator. A shop is having a 20% off sale. The user
will enter the full price of the product they want to buy. The program should then
display how much the product is once the 20% has been taken off, as well as display
the saving for that item.
Task 2e: Think of an equation that you are using in any of your other subjects. Write
a program that will calculate the equation for you.
Similar to the previous exercise of identifying what variables will be needed for each
program, we should now be asking
Example : Identify the inputs, process(s) and outputs for a program that will ask the
user how much pocket money they receive a week and then calculate how much
money they will receive in a year (52 weeks in a year). The program will then display
the result to the user.
Written Task:
On The Computer:
Now you have identified the inputs, processes and output of each of
the above scenarios, go onto the computer and create a working
solution for each task.
Please pay attention to the indentation that is present in an IF Statement, it will not
work without this indentation. This will be covered more on page 24.
Else
Code:
For example
Code:
Task 4a: Create a program that will ask the user their age and then,
using an IF statement, tell them if they are old
enough to drive a car?
Task 4c: Ask the user “What is the capital of France?” If the input equal “Paris” then
display the word “Correct” on the screen.
Task 4d: Ask the user what their test score was out of 70. The program should then
calculate the percentage and then if the percentage is greater than 70% then the
program should tell them they have passed.
Task 4e: Create a basic password program. The password should be defined in the
program code. The computer should then ask the user to enter the password, if the
password matches then display “Access Granted” if the password does not match
display “Access Denied”. Please remember that the password will be case sensitive.
Python is one of the few languages that will only run a program if it has been
indented properly. This forces the
Python High School
programmer to write neat and readable
code.
o English
o Maths
A line of code should be indented when it o Information Technology
is contained within a construct. In the
Business Studies
example to the right we can see that the
Mrs McCann
English is a part of Dalziel High School, as is
Maths and IT. Mrs Kerr
Mrs Flanagan
Business is a part of IT, and Mr Park and Mr
Mrs Martin
Jack are part of Computing, therefore
Computing
also part of IT and Dalziel High School.
Mr Park
Multiple lines can also be indented. The
effect of this is to run those lines of code Above: The departments belong to the school and the
staff belong to the departments, therefore the staff
when that branch is followed. belong to the school
Code:
Line 7 is not included in the IF statement due to the fact it has no indentation and will
therefore always run, irrespective of which branch is followed.
Code:
1. no_of_tickets = 0
2. ticket_price = 5
3. price = 0
4.
5. no_of_tickets = int(input("How many tickets have you bought?"))
6. price = no_of_tickets*ticket_price
7.
8. if no_of_tickets >= 3:
9. print("You qualify for the 10% discount")
10. price = price -(price/10)
11. else:
12. print("You do not qualify for the 10% discount")
13. print("The cost for the tickets is ", price)
How many lines need to be indented in order for the program to work correctly?
Answer: ________________________________
Which line(s) need to be indented in order for the program to work correctly?
Answer: ________________________________
Answer:
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
On The Computer:
Indentation / Conditional Selection
Task 5b: Create a menu system like the one below. When the user has selected which
equation they would like the program to work out, the program should ask for the
appropriate inputs, calculate, and then display the appropriate results. Feel free to
use your previous programs from the Basic Arithmetic section as reference.
Else
Else
Code:
Task 6b: Ask the user to enter the individual scores for two tests. Both tests should be
out of 100. If the user receives over 60 % in test 1 and over 50% in test 2, then the
program should inform the user that they are eligible to sit test 3.
Task 6c: Write a program that will ask the user for three
different passwords. If all 3 passwords are correct (match
the passwords in the code), then they should be granted
access to the system
Task 6d: Write a program that will ask the user if they take English, Drama and Music.
If they take 2 out of the 3 subjects, then they are eligible to attend the London trip.
Code:
In this example,
1. age = 13 if the age = 13,
2. if age >=12 and age <=18:
only lines 1 and
3. print ("You should be in High School")
4. elif age >= 5 and age <12: 2 will be
5. print ("You should be in Primary School") translated for
6. elif age <5: the processor.
7. print("You should be at nursery") Lines 3-8 will be
8. else: skipped, saving
9. print("You are an adult")
the processor
10. #continue with the rest of the program
time/effort.
Code Efficiency:
The above example can also be written using four separate If statements; both
solutions use the same amount of lines. So why use a multiple IF statement? A
Multiple If Statement is much more efficient than using separate IF statements. This
means that a multiple IF statement uses less of the processors resources because as
soon as one matching condition is found, the rest can be ignored.
When the program will repeat a section of code a set number of times.
When the program will repeat a section of code until a condition is met.
All lines that are to be contained within the loop have to be indented.
Code:
The example above will repeat 10 times, from 0 to 10. The word "Hello" will be
displayed 10 times and the value of counter will be 9. This can be confusing,
because counter starts at 0. To test this, we could also display the counter as well as
the word "Hello" as seen below.
1. # The user can specify how many times the code loops
2. print("How many times would you like the code to loop?")
3. loopNo = int(input())
4. for counter in range(0, loopNo):
5. print("Hello")
6. print("The counter value is ", counter)
On The Computer:
Task 8a: Ask the user their name, then ask them how many times they
would like their name to be displayed on the screen. The user will then
Task 8b: Using a fixed loop, display the numbers 1-20 on the screen. Excluding
comments, this program should only use 2 lines.
Task 8c: Using a fixed loop display the products of the 2 times table up to and
including 40. Again, excluding comments, this program should only use 2 lines.
-4
-8
-12
-16
-20 (This program, excluding comments, should not use more than 2 lines.)
-24
-28
-32
-36
-40
Task 8e: Using a fixed loop, convert your previous program that grades a pupils test
scores so that it works for a class of 10.
Task 8f: "99 Bottles of Beer" is a traditional song in the United States and Canada.
The same verse is repeated; each time with one fewer bottle. The song is completed
when the singers reach zero. Your task here is write a program capable of generating
all the verses of the song.
Code:
On The Computer:
Task 9a: Go back to your quiz program and put a conditional
loop around each question. The user will not be able to move
onto the next question until they have the present question
correct. You will no longer need your scoring system for this
program as the program will only end once all the answers have
been answered correctly.
Extension: Can the program count how many attempts it took the
user to get each question correct?
Extension: Can your program count how many guesses it took the user to guess
correctly? Look ahead in the notes to Pre-defined functions. Can you get the program
to generate a random number for the user to guess?
Helpful Hints
1. x = 3.0
2. if (x).is_integer():
3. print("x is an Integer!")
4. else:
5. print("x is not an Integer!")
Input Validation is when the computer checks the data that has been entered by
the user is of the correct type and within the correct range. Input Validation uses a
combination of a Boolean, a WHILE Loop with an IF Statement.
Code:
1.valid = False
2.while valid == False:
3. print("What age are you? ")
4. age = int(input())
5. if age <0 or age > 120:
6. print("Age Invalid. ")
7. print("Please enter an age between 0 and 120")
8. else:
9. valid = True
10. print("Input is valid")
Task 10b: Write a program that asks the user for a password. An error message must
be displayed if the wrong password is entered. The program should display “Your
password was successful” if the correct password is entered. All passwords will be case
sensitive. The program should repeat until the correct password has been entered
(similar to Task 4e)
Task 10c: Write a program that will ask the user their name and which year of High
School they are currently in. The program should only accept the following answers
(1st, 2nd, 3rd, 4th, 5th, and 6th).
Task 10f: Go through old programs and add in input validation to every line that asks
the user to enter a number within a specified range.
In the example above the loop will execute 10 times and ‘value’ is over written each
time the loop is executed. Line 6 is where the value is added to the total each time.
In the example above the loop will continue until a negative number is entered by
the user. The IF Statement on line 7 is essential to ensure that the negative number is
not included in the total.
Task 11b: Program and test the code on the previous page for the conditional loop
running total
Task 11c: Ask the user how many values there are, then using the fixed loop, take in
that number of values and calculate the total
Task 11d: Ask how many people were out for dinner. Ask how much each person’s
dinner was. Calculate the total and then add 10% to include a tip. Display the final
result onto the screen.
Task 11e: Julie has been training for a half marathon. He has run twice a week for 5
weeks and he is interested to see what is total distance is over that time. Write a
program that will take in the distance of each run, calculate the overall total
distance and display the distance on the screen.
Upper Case – Converts a string of characters to all upper case characters. This is
useful when you do not want the inputs to be case sensitive.
Random Number – This function will generate a random number based on a range
that is specified by the user.
Round – This function will take a value and round it to the number of decimal points
specified by the program.
Code:
Task 12b: Go back to your “Guess the number game” and get the program to
generate a random number that the user then has to guess.
Task 12c: Go back to the basic arithmetic programs and make sure that the result
of programs 2b-2e is rounded to 2 decimal places.
Task 12e: Create the variable pi = 3.141592653589793. Ask the user how many
decimal places they would like to round pi to and display the new rounded pi to
the screen.
Code:
Screen output:
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
From the example above, we can see that Loop 2 repeats 4 times inside Loop 1,
which itself repeats 3 times.
A common pit fall of nested loops is to use the same counter for each loop. It is
important to use separate counters for each loop if you are nesting one inside
another.
Data that is stored within an array must be of the same data type, an array of
integers, an array of Booleans, an array of strings….. etc.
Code:
Written Task:
Location[0] = "Edinburgh"
Location[2] = "Falkirk"
Location[3] = "Inverness"
Location[4] = "Stirling"
Location[6] = "Aviemore"
Location[7] = "Glasgow"
print(location[5]) ______________
print(location[2+2]) ______________
print(location[9-6]) ______________
print(location[-1]) ______________
On The Computer:
Once you have completed the task, please go onto the computer to
check your answers.
In the above example, the first the time loop is executed the counter = 0. This
means that the first input would be saved in studentName[0]. The second time the
loop is executed the counter = 1 therefore saving the second input into
studentName[1]. This will continue until the name of 5 students has been typed in
due to the number of times the loop repeats.
Task 14b: A class has 5 students, the program must take in 5 names (stored in an
array) and then take in 5 test scores (also stored in an array). The test is out of 150
and all scores should be validated. The pass mark is 70%. The program should then
display a list of who has passed and who has failed.
Extension: Can you make the grading more complex? Please refer to task 7a.
Task 14c: Create another quiz program, although this time, all the questions and
answers are stored in 2 separate arrays. The program should then use a loop to ask
each question from the array and check the answers. The program should keep a
score and display that score to the user at the end of the program.
Code:
The length function can also be used directly within the for loop code.
The len function can also be used to display how many characters are in a string.
1. town = "Carluke"
2. length = len(town)
3. print(town, "has", length, "characters")
On The Computer
Task 15a: Go back to tasks 14a, b, and c. Implement the Len
function when using fixed loops and arrays.
Strings can be combined to form new strings. Many programs involve manipulating
strings to produce the formatting that is required.
Code:
On The Computer:
Task 15a: Create a program that will ask the user for their first name
and then their second name. Once the user has done this, the program must “build”
a string that stores their full name. Display the user’s full name on the screen.
Task 145: Create a program that will ask the user for their first name, second name
and their year of birth. This program should then suggest a username that they could
use by taking the first initial from the first name, the whole of the second name and
the last two numbers of the year of birth. For example Brian Frew who was born in
1982 would have the following user name “BFrew82”.
Casting IF Statement
print(name[6])
Comments
Identifier
Written into the code by the programmer. Comments
have no effect on how the code operates. Instead Name given to identify a variable.
they are added to explain what each section of code
does and to make the code more readable. Indices
Integer
Constructs
The problem specification is a detailed description of An array of characters. Used for storing more than 1
what the program should do. Carried out at the character, for example words, names and sentences.
Analysis stage of the Software Development Process.
Syntax
Process
The rules that control the formatting and layout of the
The steps that the program will take to manipulate the code.
inputs to generate the outputs.
Variable
Readability
A variable is a storage location that is reserved in the
A process of making the program code easy to read memory that will store a value which is used within a
and understand. The programmer should be using program.
suitable identifiers, white space, internal commentary
and indentation.
Finished coded programs for the tasks in this book have not been included as I believe doing so
would take the challenge, fun and problem solving skills out of programming. My opinion is that
learning to program is not about copying code from a book or from a board. Programming is
learning how to analyse problems, breaking those problems into smaller, more manageable
sections, and allowing the pupils to create the solutions themselves. I have tried to adhere to this
philosophy throughout this booklet.
I have tried to include as many opportunities for customisation and choice as possible. For
example, pupils are encouraged to customise many of the programs to suit their own needs and
personality. Since programming is a creative exercise, creativity should also be encouraged while
using this booklet. If a pupil has an idea that would improve the program, encourage them to
attempt it. This will give the pupils more ownership and pride in their work. Extensions have been
added to many of the programs to allow those who are progressing well to remain challenged.
Pupils can also be challenged to come up with their own ideas and extensions if they are coping
well with the tasks.
This booklet has not been designed with a fixed duration in mind. It is at the discretion of the
teacher how long they spend on each section. As pupils do not have to work through every task
within this booklet to have a sound understanding of Python at National 4/5 level, it is up to the
teacher to decide which tasks to complete and which to omit.
I would recommend that all pupils add comments to all their programs and print at least one
example of each construct that is featured in this booklet. This will then allow pupils to have a
“programming pack” which they can use as a resource while completing more complex programs
and courseworks. This pack can also be carried with them into their Higher level studies.
The primary focus of this resource is Python and so the writing of pseudocode has not been
covered. However pupils should be encouraged to attempt this important exercise.
I have made this resource based on my experience of teaching Python in schools for the last three
years. Although the resource has been compiled by myself, I am heavily influenced by other
resources I have seen, as well as other teachers I have worked with. I have been helped and
influenced by many teachers while making this resource.
This resource can be used free of charge by any teacher or school throughout the country. Please
do not amend this resource in any way although feel free to use it as inspiration to create your
own. If you have any improvements, edits, or corrections to add to this resource then please
contact the author.
All code has been formatted for this resource by using http://www.planetb.ca/syntax-highlight-
word
The version of this resource you are using is version 2.0 has was first distributed June 2018.
Appendix A – Program Development Form
Pupil Name
Program Title
Analysis
Design
User Interface – What questions will you ask the user? How will the data be displayed back to the user?
Pseudocode / Flow Chart
Testing
6
Testing Evidence (Screenshots)
Efficient use of coding constructs– Hoe efficient is your code? How do you know this? Could you have made it more
efficient?
Robustness – Does your program have any bugs? Can your program handle unexpected inputs? How do you know?
Taking in an input
Converting an input to
integer
Converting an input to float
Basic Arithmetic
(additions, subtraction,
division and multiplication)
Simple selection (IF)
Complex Selection
(Two conditions linked with
AND or OR)
If …Then…Else
Multiple Selection (elif)
Nested Selection
Fixed Loop (FOR)
Conditional Loop (WHILE)
Input Validation
Running Total
Generating a random
number
Converting the case of a
string
Rounding a number
Nested Loop
Using an array
Length of Array / String
Concatenation