Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PythonProgrammingforN4 and 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

Python Programming

National 4/5

Written by David Jack,


Kings Park Secondary
Contents
What is Python? ......................................................................... 3
Why use Python? ....................................................................... 3
Downloading & Installing Python ............................................ 3
Creating and saving a program using the text editor ........ 4
Adding Comments ................................................................... 5
Variables ..................................................................................... 6
Input / Process / Output ......................................................... 11
Converting a variable type / Type Casting ........................ 13
Basic Arithmetic Operators / Process ................................... 14
Identifying Input / Process / Output ..................................... 16
Conditional Selection (IF) ....................................................... 18
Using the equals operator...................................................... 19
Indentation ............................................................................... 21
Complex Selection (AND/OR) ............................................... 24
Multiple Selection (Else IF) ...................................................... 26
Repetition (Iteration) ............................................................... 28
Fixed Loops (For)...................................................................... 29
Conditional Loops (While) ...................................................... 31
Helpful Hints .............................................................................. 32
Input Validation ....................................................................... 33
Running Total ........................................................................... 35
Pre-Defined Functions............................................................. 37
Nested Loops ........................................................................... 39
Arrays......................................................................................... 41
Arrays and Fixed loops ........................................................... 43
Length of Array – Len Function ............................................. 45
String Manipulation (Concatenation) .................................. 46
Glossary..................................................................................... 47
Teacher Notes.......................................................................... 49

Python Programming National 4/5 Computing Page 2


What is Python?
Python is a freely available, multi-platform, high level programming language that is
used to develop software throughout the world. Python was first released in 1991
and has been steadily growing in popularity ever since.

Why use Python?


 Free to download
 Easy to install
 Works on almost every computer
 Comes preinstalled in all Raspberry Pi’s
 Extremely readable, indentation is
enforced and all code is coloured.
 Uses less code than other languages to
carry out similar constructs
 Vast number of useful libraries
 Useful error messages
 Can be used for
o Object-Oriented programming
o Imperative programming
o Scripting language
o Functional programming
o Procedural programming
o Event driven programming
 Used widely in Universities and industry
 Easy transition onto other languages like
Java and C++

Downloading & Installing Python


To install Python on your computer, please visit https://www.python.org/downloads/
or ask your network manager to do so. I would recommend downloading the
newest version of Python that is available to you.

These notes have been written using Python 3.4.

Python Programming National 4/5 Computing Page 3


Creating and saving a program using the text editor
Definition:
Python IDLE stands for Integrated
Development and Learning
Environment. This is the text editor that
we will be using to write all of our
programs. There are other text editors
that can be used with Python, but this
one comes bundled with the language
itself. It has many useful features that include

 Multi-window text editor


 Syntax highlighting
 Auto-completion
 Smart indent
 Integrated debugger

To create a new program, go to “File” in the IDLE and


select “New File”, or alternatively use the short-cut
Ctrl+N. This will bring up a blank window where you
can then write your code.

Saving a Python program:


When saving a Python program, please save it into a folder titled “Python Programs”
to keep all your programs
organised. All Python programs
should end in “.py”. This then
allows the computer to identify
it as a Python program. It is also
important to give it a meaning
name, “Program1.py” is not a
meaningful name. Give it a title
that describes the function of
the program “Speed
Calculator.py”, “Quiz with
grading.py”. This will help you
to identify the programs in the
future.

Python Programming National 4/5 Computing Page 4


Adding Comments
Definition:
As programs grow and expand they can
become very complicated to read. Many
programs can have over a thousand lines
of code. This then makes it hard to
understand exactly what the program is
doing.

When writing code, it is important to add


comments at regular intervals in order to improve the readability of the code.
Comments are ignored by the computer and only benefit those who are reading
through the code. Comments allow the programmer to explain to the reader what
the program is doing, how the program is doing it, as well and highlighting important
sections of the code. Comments can also be used as a tool to remind the
programmer of how their code works

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. """

Single Line Comments


Single line comments can be added to the code using a hash (#) symbol. These
should be used to explain certain aspects of the code and to highlight a different
sections.

1. # Question 1
2. print("What is the capital city of France?")
3. answer = input()

Python Programming National 4/5 Computing Page 5


Variables
Definition:
A variable is a storage location that is
reserved in the memory that will store a
value which is used within a program. It can
change throughout the process of the
program. All variables should be given a
data type and a suitable identifier (name)
that describes its contents. When variables
are created, they are only able to store one particular type of data.

Variable Types:
For National 4/5 Computing Science you only need to know five variable types.

Integer Wholes Numbers 1, 200, -128, 5

Decimal Numbers.
Float 6.23, 5.00, -3.14
Floating Point Numbers

Individual letters &


Char "Y", "N", "O", "1", "@"
symbols

Collection of Characters "Hello", "Mr Jack",


String
(Array of characters) "Computing"

Boolean Either be True or False True, False

Python Programming National 4/5 Computing Page 6


Written Task: Variable Types
Look at the following values on the side of the table. Opposite each enters
its correct variable type.

Value to be stored Data Type


inside the variable Boolean, Integer, Float, Char or String

"Mesopotamia"

3.14519

True

"Y"

"SA12 PQR"

.765432

98.

"Britannia"

"#"

False

0784569412

"Daffodil"

"34 Main Street"

Python Programming National 4/5 Computing Page 7


Naming Variables
Definition:
When naming variables in Python, there are some rules
that programmers must follow

 Must begin with a letter (a-z, A-Z) or underscore (_)


 Other characters can be letters, numbers or _
 Case Sensitive
 Can be any (reasonable) length
 There are some reserved words which you cannot use as a variable name
because Python uses them for other things.

There are also some best practices that


programmers should try to abide by :-

 Choose meaningful name instead of short


name
o student_no is better than sn.
 Maintain the length of a variable name
o Roll_no_of_a_student is too long
 Be consistent
o student_no or StudentNo
 Include units if possible to avoid confusion
o age_in_years
o length_in_meters

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.

Python Programming National 4/5 Computing Page 8


Written task: Suitable identifiers
Look at this table of variable names and put a tick beside those that
are good, useful variable names and state what is wrong beside those
that are not.

Variable name Any Problems?


height

Time_left_in_seconds

Next.in.list

Number8

Kjyg

5red

number#1

Time@start

Post code

Name&address

Identifying how many variables a program needs


In order to identify how many variables a program will need, it is a good idea to look
at the Problem Specification and underline the information that the program needs
to store.

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.

Python Programming National 4/5 Computing Page 9


Written Task: Identifying Variables
Using the following program specifications, please state how many
variables will be needed for the program. Suggest suitable names and
variable types for each program.

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.

Number of Variables _________

Names & Data types _____________________________________

_____________________________________

_____________________________________

_____________________________________

_____________________________________

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.

Number of Variables _________

Names & Data types _____________________________________

_____________________________________

_____________________________________

_____________________________________

Python Programming National 4/5 Computing Page 10


Input / Process / Output
Definition:
All programs involve taking
in information from the user
(input), manipulating that
information (processing)
and then displaying
information back to the
user (output).

In order to write even the


most basic programs in
Python, we need to know
how to take in information from the user (via the keyboard), how to manipulate that
information (using the processor), and how to display information to the user, via the
monitor.

Code for input:

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())

Code for Output:

1. print("Hello World! ")


2. print("Hello ", name, " it is nice to meet you.")
3. print(name, " is ", age, " years old")

Python Programming National 4/5 Computing Page 11


On The Computer: Inputs & Outputs

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).

For example “Hello Pamela”.

Task 1c: Create a program that will ask the user a question of your choice. The
answer must then be displayed on the screen.

Task 1d: Create a program that asks multiple questions


What is your name?

What is your age?

What is your favourite colour?

Once all the questions have been answered, the answers must then be displayed in
the following way.

Your name is Pamela


Pamela is 15 years old
Pamela’s favourite colour is purple.

Python Programming National 4/5 Computing Page 12


Converting a variable type / Type Casting
Definition:
Sometimes it is essential to change the data
type of a variable throughout a program. For
example, when asking the user to enter a
number from the keyboard, the default data
type is string (as keyboards work in ASCII and
Unicode). You may want to convert that data
to an Integer or a Float throughout the process
of the program. This is called “Type Casting”.
This can be carried out fairly easily using the
following code.

Code: Above: Casting demonstrated in Java

1. # Convert an input to an integer.


2. print("Please enter a number using the keyboard")
3. number = int(input())
4. print(number)
5.
6. # Convert an input to a float.
7. print("Please enter a number using the keyboard")
8. number = float(input())
9. print(number)
10.
11. # Covert an integer to a float
12. number = 5
13. new_number = float(number)
14. print(new_number) #output will be 5.0
15.
16. # To convert an integer to a string
17. number = 16
18. new_string = str(number)

Python Programming National 4/5 Computing Page 13


Basic Arithmetic Operators / Process
Definition:
Due to the processing power of computers, they are
ideal for carrying out basic and complex arithmetic.
Not only are computers more accurate but they are
must faster than humans. Most programs will need
to carry out at least one calculation.

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.

B → Brackets first (parentheses)

O → Orders i.e. Powers and Square Roots, Cube Roots, etc.)

DM → Division and Multiplication (start from left to right)

AS → Addition and Subtraction (start from left to right)

Code:
Answer = 4 × 3 + 2

is very different from


Answer = 4 × (3 + 2)

Python Programming National 4/5 Computing Page 14


On The Computer: Basic Arithmetic

Task 2a: Write a program that will calculate the area of a rectangular
room. All variables should be integers.

Area = length X breadth X height

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.

Speed = Distance ÷ Time

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.

Average score = total score ÷ number of subjects

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.

Discount = Final Price * 20%

Final Price = Item Price - Discount

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.

Python Programming National 4/5 Computing Page 15


Identifying Input / Process / Output
Definition:
As programs become bigger and more
complicated, it is good practice to
identify the inputs, process and outputs
before attempting to code the program
on the computer. This is also part of your
National 5 assessment.

Similar to the previous exercise of identifying what variables will be needed for each
program, we should now be asking

 What variables will be input?


 What process should be applied to these variables?
(often a calculation or a decision)
 Which variables will be used to display the final information to the user?

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.

Input Process Output

Pocket_Money (Float) Annual_total = Pocket_Money * 52 Annual_total (Float)

Written Task:

Task 3a: Identify the inputs, process(s) and outputs for


a program that will ask the user to enter the price of an
apple and then the number of apples that are being
purchased. The program should then display the total
onto the screen.

Input Process Output

Python Programming National 4/5 Computing Page 16


Task 3b : Identify the inputs, process(s) and outputs
for a program that will ask the user how many people
were having a meal, and the total price of the meal.
The program will then add 10% onto the meal bill to
cover the tip and calculate how much each person
at the table has to pay.

Input Process Output

Task 3c: Identify the inputs, process(s) and


outputs for a program that will ask the user
how much money they would like to borrow
from the bank. The program should then ask
the user to enter how many months they
would like to repay the loan. The program
should then add 15% interest onto the amount
borrowed and then inform the user how much
their monthly payments will be.

Input Process Output

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.

Python Programming National 4/5 Computing Page 17


Conditional Selection (IF)
Definition:
IF Statement allows the program to make a decision based on certain condition(s).
This can be based on a user input or a variable changing value. All IF Statements
have a condition that can either be True or False. For example, in a game “IF the
forward key is pressed by the user THEN move the character forward”.

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.

If <condition = true> then

Run this code

Else

Run alternative code

Making Comparisons / Boolean Logic:


When comparing values you can use the following operators.
== Equals to
> Greater Than
< Less Than
>= Greater than or equals to
<= Less than or equals to
!= Not equal to

Code:

1.# Simple IF/ELSE Selection


2.if age >= 17:
3. print("You are old enough to drive")
4.else:
5. print("You are too young to drive")
6.
7.# It is possible to use the IF part without the ELSE
8.if money >= 15:
9. print("You have enough money to buy a ticket")

Python Programming National 4/5 Computing Page 18


Using the equals operator
Definition:
The ‘equals’ symbol (=) can be used in 2 different
ways. To change the value of a variable, or to
test/compare a value of a variable.

 When you want to change the value of a


variable you only need to use one equals.
 When you want to compare the value of a
variable you need to use two equal signs.

For example

 Make age equal the value 18


 Does age equal the value 18?

This is a common mistake and can be easily fixed.

Code:

1. # Assigning the value "David" to the variable name


2. name = "David"
3.
4. # Checking the contents of the variable name to see if
the variable name matches the word "David"
5. if name == "David":
6. print("Hello David!")
7.
8. # Assigning the value 5 to the variable number
9. number = 5
10.
11. # Checking the contents of the variable number to see if
the variable value matches the number 5
12. if number == 5:
13. print("The number in the variable is 5")

Python Programming National 4/5 Computing Page 19


On The Computer:
Conditional If Statement / Using the Equals Operator

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 4b: Create a program that will ask the


user their age and then, using an IF statement,
tell them if they are old enough to buy
alcohol?

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 Programming National 4/5 Computing Page 20


Indentation
Definition:
Please look at the example of an If Statement below. Please
notice that line 2, 3, 5 and 6 have been indented using the TAB
key.

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:

1. if age > 17:


2. print("You are old enough to drive")
3. print("You should look into buying a car")
4. else:
5. print("You are too young to drive")
6. print("You should look into buying a bike")
7. print("Thank you for using this program")

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.

Python Programming National 4/5 Computing Page 21


Written Task: Indentation
The code below is a program that asks the user to enter how many tickets
they have bought for a show. If they have bought three or more tickets,
the program should give them a 10% discount. The code below has not been
indented properly.

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: ________________________________

What happens if some/all of those lines are not indented?

Answer:
_________________________________________________________________________

_________________________________________________________________________

_________________________________________________________________________

On The Computer:
Indentation / Conditional Selection

Python Programming National 4/5 Computing Page 22


Task 5a: Create a program that will ask the user 10 general knowledge questions and
tell them if they are correct or incorrect?

Extensions: Add a scoring system to


the quiz and get the program to
display the final score at the end of
the quiz. Refer back to program that
contain basic arithmetic.

Look ahead at the “pre-defined


function section” (page 39), using the
Upper function can you make you program non-case sensitive?

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.

Tip: Pay close attention to the indentation.

The Equation Program

Please select an option from the following menu


1. Calculate the speed
2. Calculate the distance
3. Calculate the time
4. Calculate the area of a rectangular room
5. Exit Program

Python Programming National 4/5 Computing Page 23


Complex Selection (AND/OR)
Definition:
Selection (If Statements) can be split into two
categories:-

Simple Selection is when there is only one


condition, which we have looked at
previously.

Complex Selection is when there are two or


more conditions. When using Complex selection the conditions can be linked using
either AND or OR.

AND: Means that both the conditions need to be true

If <condition 1 is true> AND <condition 2 is true>……AND <condition


5 is true> then

Run this code

Else

Run alternative code

OR: Means that only one of the conditions need to be true

If <condition 1 is true> OR <condition 2 is true>……OR <condition 5


is true> then

Run this code

Else

Run alternative code

Code:

1.# Complex Selection Example 1 using AND


2.if age >=12 and age <=18:
3. print("You should be in High School")
4.
5.# Complex Selection Example 2 using OR
6.if answer == "Paris" or answer == "paris":
7. print("Correct")

Python Programming National 4/5 Computing Page 24


On The Computer:
Task 6a: Write a program that will ask the user for a pupil’s name and
age. If the pupil is between the ages of 4 and 11 the program should
then tell the user that they should be in Primary school. If the pupil is
between the ages of 12 and 17 then the program should tell the user that they should
be in High School.

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.

Python Programming National 4/5 Computing Page 25


Multiple Selection (Else IF)
Definition:
Multiple selection allows the programmer to combine two or more If Statements
together. This is much more efficient than having a long list of separate IF
Statements.

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.

As programmers, we should be trying to make our programs as efficient as possible.

1. age = 13 If this solution was


2. if age >=12 and age <=18:
programmed using
3. print ("You should be in High School")
4. if age >= 5 and age <12: four separate IF
5. print ("You should be in Primary School") statements, then
6. if age <5: every line would
7. print("You should be at nursery") need to be
8. if age > 18: translated and sent
9. print("You are an adult") to the processor,
10. #continue with the rest of the code
even though a
solution has already
been found.

Python Programming National 4/5 Computing Page 26


On The Computer:
Task 7a: Create a program that will ask the user what percentage they
received in a recent exam. Your program will then tell the user which
band their mark falls under.

Greater than or equal to 90 they get a A

Greater than or equal to 70 they get a B

Greater than or equal to 50 they get a C

Greater than or equal to 40 they get a D

Less than 40 they Fail

Task 7b: Go back to your quiz program


and add a grading system. This will display
a different message, depending on what
score they received, similar to the grading
program you have just completed.

Python Programming National 4/5 Computing Page 27


Repetition (Iteration)
Definition:
Repetition (also known as iteration) allows
the programmer to repeat sections of code.
This means that the programmer will not
have to type up similar code over and over
again, therefore resulting in time saved and
less syntax errors. When a loop runs, it goes
through its block of code and at the end it
jumps back to the top.

Two different kinds of repetition exist:

Fixed Loop (For Loop)

When the program will repeat a section of code a set number of times.

Conditional Loop (While Loop)

When the program will repeat a section of code until a condition is met.

Java Programmers Punishment

Python Programming National 4/5 Computing Page 28


Fixed Loops (For)
Definition:
A For Loop (Fixed Loop) will repeat for a set amount of
times and allows the code to carry out repetitive lines
of code. The number of times a section of code has to
be repeated is normally specified by the programmer.

Every For Loop has a loop counter. In the example


below, it has been named “counter”, although it can
Fixed loop demonstrated in Scratch.
take on any identifier. This counter is an integer and its
value will increase by 1 every time a loop has completed.

All lines that are to be contained within the loop have to be indented.

Code:

1. # For Loop to display "Hello" 10 times


2. for counter in range(0, 10):
3. print("Hello")

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. # For Loop to display the value of the counter


2. for counter in range(0, 10):
3. print("Hello")
4. print("The counter value is ", counter)

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

Python Programming National 4/5 Computing Page 29


type in a number, the loop will run that many times and display the user’s name each
time the loop completes.

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.

Task 8d: Using a fixed loop, display the following:

-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.

“99 bottles of beer on the wall, 99 bottles of beer.


Take one down, pass it around, 98 bottles of beer on the wall.”

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.

Python Programming National 4/5 Computing Page 30


Conditional Loops (While)
Definition:
A While Loop (conditional loop) will repeat a
section of code while a condition is true. If that
condition is never made False, then the loop
while continue to repeat.

All lines that are to be contained within the loop


have to be indented.

In the example below, the user will be asked the


question "What is the capital of France?"
until they type in either "Paris" or "paris".

Code:

1.# While loop


2.answer = "" # Gives the variable answer a blank value
3.while answer != "Paris" and answer != "paris":
4. print("What is the capital of France?")
5. answer = input()

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?

Python Programming National 4/5 Computing Page 31


Task 9b: Write a program where the user has to guess a number
that has been defined within the code. If the user guesses too
high, the program should suggest they should guess lower. If the
user guesses too low, the program should suggest they should
guess higher. The program should display a congratulations
message when the user guesses the correct number.

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?

Advanced Task (outwith the scope of N5)


Task 9c: Write a program that will convert a decimal number into binary
code.

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!")

Python Programming National 4/5 Computing Page 32


Input Validation
Definition:
If incorrect data is entered into any
program, then inaccurate data will
be produced by the program. It is
the programmer’s job to restrict
users so they can only enter valid
data into the program.

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.

Input Validation is used in most program to control the user’s inputs.

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")

Figure 1: Garbage in, garbage out

Python Programming National 4/5 Computing Page 33


On The Computer:
Task 10a: Program the example provided in the previous page.

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 10d: Write a program that will ask the user


their name, gender and age. Validate gender so
only “male” or “female” can be entered.
Validate age to make sure that age is not below
zero or age is greater than 120.

Task 10e: Write a multiple choice question for your quiz


where the user should be restricted to only answering “a”,
“b”, “c” or “d”.

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.

Python Programming National 4/5 Computing Page 34


Running Total
Definition:
It is often the case where the programming will need to
keep a running total of all the values that are being
entered by the user. This can be done by using either a fixed
loop or a conditional loop. If you know how many values
there are then use a fixed loop, otherwise use a
conditional loop and get the loop to end when a
certain value is entered.

Code Fixed Loop:

1. # Running Total Fixed Loop


2. total = 0
3. for counter in range (1, 11):
4. print("Please enter value", counter)
5. value = int(input())
6. total = total + value
7.
8. print("The total is ", total)

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.

Code Conditional Loop:

1. # Running Total Conditional Loop


2. total = 0
3. value = 0
4. while value >=0:
5. print("Please enter value")
6. value = int(input())
7. if value >=0:
8. total = total + value
9.
10. print("The total is ", total)

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.

Python Programming National 4/5 Computing Page 35


On The Computer:
Task 11a: Program and test the code on the previous page for the
fixed loop running 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.

Python Programming National 4/5 Computing Page 36


Pre-Defined Functions
Definition:
Pre-defined functions are built into Python to perform
some standard operations. The programmer does not
need to know the steps involved in the function. They
simply apply the pre-defined function and obtain the
desired value.

There are lots of pre-defined functions built into


Python, but the four that you will need to use in National 5 Computing Science are:-

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.

Lower Case – Converts a string of characters to all lower case characters.

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:

1. # Convert a string to upper case characters


2. name = "david"
3. name = name.upper()
4. print(name)
5.
6. # Convert a string to lower case characters
7. school = "KINGS PARK SECONDARY"
8. school = school.lower()
9. print(school)
10.
11. # Generate a random number between 10-100
12. import random
13. number = random.randint(10, 100)
14.
15. # Round a number
16. print(round(3.14159265359, 2))

Python Programming National 4/5 Computing Page 37


On The Computer:
Task 12a: Go back to your quiz program and make it so the questions
are no longer case sensitive.

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 12d: Write a program that will generate


a “lucky dip” ticket for The National Lottery.
The program should generate 6 numbers
between 1 and 59. You’ll need to make sure
that the program doesn’t select the same
number twice.

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.

Python Programming National 4/5 Computing Page 38


Nested Loops
Definition:
The placing of one loop inside the body of another loop is
called nesting. When you "nest" two loops, the outer loop
takes control of the number of complete repetitions of
the inner loop. While all types of loops may be nested,
the most commonly nested loops are FOR loops.

Code:

1.for counter1 in range (0, 3): # Loop 1


2. for counter2 in range (0, 4): # Loop 2
3. print(counter1, " ", counter2)

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.

Python Programming National 4/5 Computing Page 39


On The Computer:
Task 13a: Five pupils are tracking how many calories they have eaten
that day for breakfast, lunch and dinner. Using nested loops, can you
ask all 5 pupils to enter how many calories they had for each meal, total them up for
the day and then display the results to the screen?

Task 13b: Write a program, using nested loops, that will


display the 2 times table. It should look exactly like the
diagram to the right. Once you have done this, place it
inside a nested loop so the program will display the 2, 3,
4, 5, 6, 7, 8, 9 and 10 times tables. If done correctly this
can be programmed in 3 lines.

Advanced Task (need a good understanding of Mathematics)


Task 13c: The Fibonacci
sequence is said to be
“Gods equation”. Can you
write a program that can
display the first 100 numbers
in the Fibonacci sequence?

0, 1, 1, 2, 3, 5, 8, 13, 21, 34,


55, 89, 144, 233, 377, 610,
987, 1597, 2584, 4181, 6765,
10946, 17711, 28657, 46368,
75025, 121393……

Python Programming National 4/5 Computing Page 40


Arrays
Definition:
Often a program will have to
store lots of information at
the one time, for example,
when a teacher is entering in
the names of all their pupils. It
is unrealistic to have a
separate variable for each of
the names (StudentName1,
StudentName2….etc).

Arrays allow the programmer


to store more than one piece
of data within a single data
structure.

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.

Arrays must be given a suitable identifier just like a variable.

Each piece of information stored in an array needs to be given a number so that it


can be uniquely identified. This number is called an “indices” or an “index”, this
number has to be placed inside square brackets [ ]. The index always starts at zero.

Code:

1. studentName = [""]*5 # Creates an empty array of 5 string


2. studentName[0] = "Jane"
3. studentName[1] = "Paul"
4. studentName[2] = "Steven"
5. studentName[3] = "George"
6. studentName[4] = "Lisa"
7.
8. # The array can also be created with the following line
9. studentName = ["Jane", "Paul", "Steven", "George", "Lisa"]

Written Task:
Location[0] = "Edinburgh"

Python Programming National 4/5 Computing Page 41


Location[1] = "Motherwell"

Location[2] = "Falkirk"

Location[3] = "Inverness"

Location[4] = "Stirling"

Location[5] = "Fort William"

Location[6] = "Aviemore"

Location[7] = "Glasgow"

What data type does the array “Location” store? ______________

How many pieces of data are stored in “Location”? ______________

What would be displayed on the screen after the following commands?


print(location[2]) ______________

print(location[5]) ______________

print(location[2+2]) ______________

print(location[9-6]) ______________

And what do you think might happen if you try:


print(location[8]) ______________

print(location[-1]) ______________

On The Computer:
Once you have completed the task, please go onto the computer to
check your answers.

Python Programming National 4/5 Computing Page 42


Arrays and Fixed loops
Definition:
A For Loop is an arrays best
friend for one reason; the
counter! As we should
remember from the note on For
Loops (page 31), each For Loop
has a counter and every time
the loop is completed the
counter increases by one. This is
extremely useful when
populating (adding information to) and displaying information from arrays.

Allowing the user to populate an arrays


This allows the program to ask the user a question multiple times and saving the
inputs into different indices of the array. As the counter increases by one each time,
it is perfect to use as a reference for the indices.

1. # Populating an array using a fixed loop


2. studentName = [""]*5
3. for counter in range(0, 5):
4. print("Enter the name of Student ", counter)
5. studentName[counter] = input()
6.

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.

Displaying information from an array


This allows the information of an array to be displayed onto the screen one item at a
time again using the counter as the reference for the indices.

1. # Displaying data from an array using a fixed loop


2. for counter in range(0, 5):
3. print("Student ", counter, "'s name is", studentName[counter])

Python Programming National 4/5 Computing Page 43


On The Computer:
Task 14a: Create a program that will ask for five numbers to be
entered into an array. Once all 5 numbers have been added the
program should display them back to the user.

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.

Advanced Task (outwith the scope of N5)


Task 14d: Create a program that populates
an array with 100 random numbers between
0-100 (See pre-defined functions, page 39).
Once the array has been populated, count
how many of the random numbers are over
80. Print the contents of the array along with
the amount of numbers over 80 to the screen
so you can check your answer. Once you
have completed this program, you have Count Occurrences being demonstrated in Visual Basic.
Counting how many times the number 25 appears
sucessfully written the standard algorithm within the array.
“Count Occurrences”.

Python Programming National 4/5 Computing Page 44


Length of Array – Len Function
Definition:
It is often useful to get Python to tell us the
length of an array. This can be useful when
using a fixed loop along with an array as it
can inform the fixed loop how many times
it needs to repeat.

In order to get the length of an array we


use the Len function.

Code:

1. studentName = ["Simon", "Hayley", "Ben", "James", "Lauren"]


2. lengthOfArray = len(studentName)
3. print("The array has ", lengthOfArray, " values")
4.
5. for counter in range (0, lengthOfArray):
6. print(studentName[counter])

The length function can also be used directly within the for loop code.

5. for counter in range (0, len(studentName)):


6. print(studentName[counter])

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.

Python Programming National 4/5 Computing Page 45


String Manipulation (Concatenation)
Definition:
Strings are stored in the computer’s memory in
a very similar way to arrays. A string can be
thought of as an array of characters, each
letter is stored in its own index. The first
character is given the index [0].

Strings can be combined to form new strings. Many programs involve manipulating
strings to produce the formatting that is required.

Code:

1. # Displaying one character of a string


2. name = "Jessica"
3. print(name[2]) # 's' will be displayed on the screen
4.
5. # Combining two strings
6. Full_Name = First_Name + " " + Last_Name
7.
8. # Counting how many characters are in a string
9. No_of_letters = len("Kings Park Secondary")
10.
11. # Print the first three characters of a string
12. print(Full_Name[0:3])

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”.

Python Programming National 4/5 Computing Page 46


Glossary
Algorithm Programming constructs are the basic elements,
commands, and statements used in various
A step-by-step list of instructions that, when followed programming languages.
in order, will solve a problem, perform a calculation
etc. Concatenation

Array Joining two or more strings to create a new string.

An array is a data structure that holds a fixed number Efficiency


of values of a single type. The length of an array is
established when the array is created. After creation, An efficient program is a program that fulfils the
its length is fixed. problem specification while using as little of the
computers resources as possible.
Binary
Float
A mathematical system used by all digital devices,
including computers, to represent numbers/data. A variable type used for storing decimal numbers.
Float is short for “Floating Point Numbers”.
Boolean
Floating Point
The Boolean data type is a data type, that can consist
of one of two values (usually denoted True and False), Representing decimal numbers as two sequences of
indented to represent the truth values of logic bits. One representing the mantissa, the other an
and Boolean algebra. exponent which determines the position of the point.

Casting IF Statement

Changing the type of a variable. For example See “Selection”


changing the float (10.0) to an integer (10).
Index
Char
The index refers to an individual location within an
The char data type can hold one symbol. Either array. For example to access the data stored in index
alphabetical (a-z), numerical (0-9) or punctuation (<, 6 in an array title “name” could be done by using the
>, ?, /, :, @, #, etc.). following code.

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

Condition See “index”. Same thing, different terminology.

A condition is a piece of code that will return True or Input


False depending on the values used. For example,
(4<5) would return True, (4==5) would return False. Information/data that is being sent into the program.
Similar to asking a True or False question. Used in
Input Validation
Selection and Conditional loops. Can be joined
together using AND or OR. A standard algorithm used to make sure that the data
supplied to the program by the user is of the correct
type and within the correct range.

Integer
Constructs

Python Programming National 4/5 Computing Page 47


An Integer is a variable type for storing whole Recursion
numbers.
See “Recursion”
Iteration
Selection
The repetition of a process. Also see “Loops”.
If Statements
Loops
IF Statement allows the program to make a
Conditional Loops – While decision based on certain condition(s). This
can be based on a user input or a variable
A way for computer programs to repeat changing value. All IF Statements have a
various steps until a condition(s) set by the condition that can either be True or False.
programmer.
Multi Selection
Fixed Loops – For
When an IF Statement can have multiple
A way for computer programs to repeat outcomes and multiple conditions. Each
various steps for a set number of times set by section of the Multi Selection is linked using
the programmer. “Else If”, or “elif”.

Output Complex Selection


Information/data that the programmer send to the When more than one condition is used within
user via an output device (monitor, speakers). an IF statement. Conditions need to be linked
with either an ‘AND’ or an ‘OR’.
Populating
Nested Selection
Adding data into an array.
An IF Statement embedded within another IF
Pre-Defined Functions
Statement.
A function that has been pre-made for the
Standard Algorithm
programmers to use, normally built into the
programming language although can be exported An algorithm is a list of steps. A standard algorithm is
via external libraries. For N5 you need to know about an algorithm that appears in many different programs
Random(), Round(), Upper() and Lower(). with a similar structure.

Problem Specification String

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.

Python Programming National 4/5 Computing Page 48


Teacher Notes
These notes have not been written as a tutorial. While working through this booklet, it is expected
that pupils will still be taught and helped by a classroom teacher rather than left to work through
the booklet on their own.

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

(Describe in your own words what this program has to do)

Input  Process  Output

Input Process Output

Design

User Interface – What questions will you ask the user? How will the data be displayed back to the user?
Pseudocode / Flow Chart

Testing

Test Input Expected Output Actual Output Comments


Normal Test Data
1

Extreme Test Data


3

Exceptional Test Data


5

6
Testing Evidence (Screenshots)

Test Case 1 Test Case 2

Test Case 3 Test Case 4

Test Case 5 Test Case 6


Evaluation

Fitness for purpose– How does it meet the program specification?

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?

Readability – Is your program readable, what makes it so?


Appendix B – Construct Checklist
Programming Construct Program Name Date

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

You might also like