Python Programming Guide (1)
Python Programming Guide (1)
CODING
FOR
BEGINNERS
USING
Version 1.0
Programming
Champion
Clear instructions
and easy to follow
Python Essentials
Key Words
Print a variable
Concatenated Strings
Length of a String
Conditional Logic
Convert String to an Integer
Decide to run a block
Equal too?
Less than?
Convert to Lowercase
Greater than?
Decide between many blocks 1st letter of each word to uppercase
Functions
Count from 10 to 1 Creating a function
Repeat while true
3 Conditional Statements
34 Conditional Statements Explained
36 Branching with if
37 Branching with if, else and elif
39 Nesting Statements
40 Using Logic with if Statements
43 End of Chapter Quiz
4 Loops
46 Loops and Iteration Uncovered
47 While Loops
48 Breaking and Continuing While Loops
49 While/else Loops
50 Looping While True
51 More to do with While
52 The For Loop
53 Using Break and Else with For
54 Nesting Loops
56 Mopping up Loops... For Now
58 End of Chapter Quiz
5 Lists, Tuples & Dictionaries
60 Getting Started with Lists
62 Slicing Lists
63 Adding Items to Lists
65 Removing Items from Lists
66 List Methods
68 Other Things to do with Lists
69 Tuples
70 Dictionaries
72 2D Lists
75 End of Chapter Quiz
7 Glossary of Terms
1 Getting Started with Python
Lots of Programs
There are over 100 different programs that have been coded to help you understand the theoretical and practical side to programming
in Python. It's advisable that when you work through these with your teacher that you create a new file each time and copy the code
down. This will get you use to to typing in key Python commands, whilst also learning the syntax and semantics of the language.
Code it yourself
Across this guide you will find a range of "code it yourself" activities. These activities have been designed specifically for the chapters
you are working in, however you can always go that extra mile and revisit these if you want to add advance features in.
Solutions
Each of the "code it yourself" activities have a solution, which has been included at the back of the guide. However this is there for you
to check your work, dont be tempted to peak unless you have exhausted all other help options as listed below.
Getting Started
To get started you will need the following resources:
Access to a computer (Windows, Mac, Linux)
A copy of the Python IDLE software or access to an online version
This guide or any Python programming guide.
Determination and resolve
Need Help?
Learning to code, is the closest thing we have to a super power, but mastering it, well this takes time. If you make mistakes don't worry
this is too be expected, this is simply how you learn. If you get stuck try some of these tricks:
Ask a friend sitting next to you (Not across the room)
Ask your teacher for help
Do some research, a simple google search can produce lots of hits
Take to the forums and ask for help there. (Refer to the back for some good ones)
Talk to a rubber duck. No Joke, look up a method known as rubber duck debugging.
Before you get started on your programming journey, let me give you a few words that I want you to remember. From experience you
cant learning coding over night, it takes time and lots of practice. You are going to make a lot of mistakes, but this is simply how you
are going to learn. Stick with it, don't give it up, ask for help and give help where you can. The programming community is one of the
most supportive communities that I have personally enjoyed when learning to code myself. Once you grasp the concept of
programming and can instinctively create programs, you will feel like you have a new super power.
6
Computer Programming & Python
A computer program is a set of instructions that a computer follows to complete a task. “Coding” or “programming” means writing step-
by-step instructions that tell the computer what to do – and this is exactly what you are going to be learning how to do using this guide.
You probably don’t realise it, but we are surrounded by computer programs – many devices and gadgets we use each day are controlled by
them. These machines follow step-by-step instructions written by a computer programmer.
Games consoles allow us Washing machines can In cars the speed, internal
Mobile phones allow us Smart appliances like
to play games, control the water temperature, cameras and
to communicate and speakers, lights and
communicate with others, temperature the amount audio, as well as
install apps that all heating can control the
as well as managing of water needed and spin calculating the amount of
perform different family home remotely via
graphics and sound speeds in each cycle. fuel remaining can all be
functions. mobile devices.
controlled.
Computers might seem like very smart machines, but in reality, they are just boxes that follow instructions very quickly and accurately. As
intelligent humans, we can get them to carry out different tasks by writing computer programs (which are just a list of instructions).
Computers can only follow these instructions if they are written in a language they understand.
There are lots of programming languages around that computers understand - it’s up to you to pick the
best one. Some popular examples are: HTML, Java, Python, C#, Ruby; but there’s heaps more! We will
be learning Python – the world’s most popular programming language. You can create your own
computer program by learning a programming language – which is exactly what you will be learning in
class and hopefully at home too.
What is Python?
Python is one of the worlds most popular and fastest growing high-level programming languages. Its not just
popular with software engineers, but also scientists, accountants, mathematicians, data analysts and kids.
Python is used everywhere from artificial intelligence to home automation due to its flexibility and its
powerful feature set. The idea of Python was to create a language that was easy to read and one that was
simple to use, which is why its great for beginners. Python can be used everywhere:
Hacking Automation
There are so many key features to Python, here are to name a few:
Python its free - Its open source
Python is easy to learn - Has a very simple Syntax
Python is easy to read and understand - Uses simple English and punctuation Python 3.X is not
Python is portable - Works on a range of different hardware and software platforms backwards compatible
Python is high-level - Automatic memory management with Python 2.7
Python is Versatile - Can be used in a Procedural or object-orientated style.
Python is "The whole package" - The basic library of Python is huge and rich in features
Python is rich in resources - There are so many resources online to help with your projects
7
Online Development Envionments
The giveaway is in the name, online development environments run completely online and their is no installation required. Off courses, you will
need a good and stable internet connection and you may find that performance is slightly slower as the code you enter is being processed on a
server rather than your own computer, however this is not a bad thing as online development environments come with some other useful
features.
There are so many different online development environments so in this guide we have chosen one, which is repl.it
3 Select "Python " from the drop down list and click "Create Repl"
4 That's it, you are ready to go. You can jump to the page "Writing your first program"
8
Installing Python
Before you can use Python and start programming, you will need to install a Python interpreter on your computer and the standard Python
library. There are many different versions of Python that you can download, its always advised that you download the latest version.
1 Open your web browser, and type the following address in https://www.python.org/downloads/
2 Download the latest version of Python to your computer, by clicking this button.
9
5 Check all "Optional Features" options, then click Next
6 Change the location of the installation location. By default this will be quite long.
10
The Interpreter
You have now completed the installation of the Python Interpreter and the libraries needed to create programs written in Python. The
interpreter is used for processing text based programs. You can also run snippets of code and test these for errors. Before we start introducing
you to the code, lets meet the interpreter that you have installed.
I know this may not look very cool and you may even think this looks a lot like command prompt (well basically it is but for Python), but this is
fundamental to getting your code to work. Once you have learnt the basics of Python you can eventually create graphical user interfaces.
The Python shell is the application we are going to use to create your programs, as its easier to run the code you have created. All your code
should be stored in a separate file, so you can retrieve your programs at any time. python programs will have a .py extension at the end of
them.
There are alternatives to
the Python IDLE that you
ca n ac tu a lly ty p e python code can download for free. A
You
t in to th e sh ell if you wish too, simple google search will
straigh
w o n t b e ab le to retrieve the find you a few.
but you
la te r u se sho u ld you close it.
code for
There are so many good python interpreters that you can download and install on your computer. Below are a couple of some you can
download at home for free. You may even use some of these at your school.
11
Compiler vs Interpreter
You may have heard of both of these names before, but whats the difference?
Interpreter
The interpreter translates each line of code of a high level language into an instruction, which is then executed before it moves on to the next
line. Interpreted programs are easier to debug as code can be adapted whilst the program is running. Each line gets converted into byte code,
which the runs through a virtual machine that can process the instructions.
Compiler
A compiler will convert a high level programming languages, such as Java into object code/ machine code which can then be executed by your
computers CPU, using the executor. The compiler is another piece of software that also understands the syntax of the programming language,
if there are any mistakes in your code, then the entire program will not run.
A compiler and interpreter do the same thing, they both take high level languages and convert these into machine code, however there are
some key differences as shown below:
Translate each line of code at a time Translates all code at the same time
Runs slower as it has to translate the code every time the Faster when compiled, but takes time to ompile the code
code runs in the first place.
Python for the most part is an interpreted language, however before it gets turned into Byte code, it needs to be compiled first. But unlike
compiled code an executable file will be produced.
12
Writing Your First Program
Right, so we have now spoken about what Python is and its interpreter, now its time to actually create our first program.
Using the Python IDLE program, click "File" from the menu bar and select "New File", or on your keyboard press Ctrl + N to open a new file.
This will open up a text editor, like the one below. This is very similar to notepad, but the difference is that its expcting Python code and will
use syntax colour coding. Click "File" again from the top menu and click "Save" or Ctrl + S, give the file a remerable file name and save it in an
easy to reach location.
Now that your program file has been saved, you are ready to write your first program. In the text file write the following
line of code:
print("Hello World!")
Once you have written the above line of code, click "Run" in the menu bar. You will be asked to save the file, click "Ok"
and the below screen will appear.
You can see that " Hello World!" has been outputted to the screen. You did this by using the print
function in Python to do this. Any time you want to print something out to the screen, then this is the
command you need to use.
13
Annotating Your Code & Escape Strings
When you code in any programming language, it is extremely important that
you explain what your code is doing. The easiest way to achieve this is to use Comments are ignored
comments or annotations. By explaining your code, you make your code more by the interpreter; they have no
readable, which is important when you are sharing your code with another impact on your code what so ever.
developer or on an online community.
You should strive to use comments throughout your code and as we progress
thought this guide, you will be expected to use them.
Output:
You have seen two Python programs, now it’s time to try it yourself. Create a Python program that prints out your name on to the
screen. You can use the previous programs as a guide, but try doing without looking.
Escape Strings
There are are a number of different ways that you can use escape strings to format the output of your code. You can use the below
techniques within side your quotation marks to manipulate some of the text formatting on output.
Output:
Hello Below is a list of
World common character and
Output: string literals, which
Hello World are used in Python:
\n – newline
Output: \t – tab
Hello \v – vertical tab
World \b - backspace
Output:
HellWorld
14
The Separator & End Parameter
There will be times in your program when you will want to use the separator(sep) or end parameter to adjust the way in which your
code is displayed and outputted to the console screen. Each of these are used and explained further below:
The end parameter joined the "Hello" and "World!" together into one single output statement in the console screen.
Create a python program that tells the story of the three little pigs and the big bad wolf. Your code must run correctly with no
errors.
What level are you?
Novice Level – Your story will be written across multiple lines of code
Adept Level – Your story will be written across multiple lines of code with full annotation
Master Level - You story will be written across multiple lines of code with full annotation and the use of the end parameter
Output:
ABC
A-B-C
A-B-C!
In this program, practice everything you have learnt so far. Create a program that uses a range of different print statements that
are made up of different arguments and use the sep and end parameters on these.
What level are you?
Novice Level – Create your program using at least one of the sep and end parameters.
Adept Level – Create your program using at least two of the sep and end parameters
Master Level - Create your program using at least three of the sep and end parameters with full annotation.
15
End of Chapter Quiz
(Getting Started with Python)
Welcome to the first end of chapter review, below are some questions that you should go ahead and answer. Check the answers with you
peers and teacher.
1. What are the two ways that we can annotate our code?
2. When we want to produce some output to the screen, what pre-built function do we use?
5. What is the purpose of the sep="---" in the below code? What is the output of the below code?
16
2 Variables and Data Types
Another way to look at variables, is imagine a box, that can store only one value. Like the below example. The only thing is we need to
tell our boxes what tyep of data they must hold and thats where data types come in.
A variable is like a
named box, you can
change what it holds,
but you cant change its
name.
Used in conjunction with variables, data types allow us to provide a classification on the type of data that can be stored in a variable. The
different data type that can be used with Python to create variables are as follows:
Integers (int)
An int is short for an integer which is a whole number such as 0,1,2,3,4,5,6,7,8,9 etc. They can be both signed (negative) and unsigned
(positive).
Float
A float, which is short for floating point number is a way of storing a number, which has a decimal place such as 3.2, 6.8, 7.1 etc.
Character
A character is a data type that can hold single letter, symbol or number such as ‘A’, ‘b’, ‘@‘, ‘$’, In Python Characters
‘1’ etc. A simple char will use at least 1 byte (8 bits) of storage space. are not a data type
we use, instead we
Strings just use the string
Strings are very powerful and used to not only store words, but are used to store a combination of
data type.
words and numbers. Strings are useful when you want to capture information that is made up of a
mixture of alphanumeric data.
Boolean
Boolean in many languages is known as bool, which is represented in either has two states; true or false. You may see that this
data type is used with binary numbers, this again reflects the two states of Boolean. 0 = false and 1 = true.
18
Creating Variables
In this section of the guide, we are going to create variables in python to store a range of data, but first there are few things you need to
know about how you give variables names. When variables are created, you practically give them any name you want, eg; name, total,
houseNo, age, etc. Variables are very flexible with names, however there are some golden rules to creating them:
A Variable name consists of any combination of alphabets, digits and underscores. Some compiler allows variable names whole length
could be up to 247 characters. Still it would be safer to stick to the rule of 31 characters. Please avoid creating long variable name as it
adds to your typing effort.
All variable names must begin with a letter of the alphabet or an underscore( _ ). For beginning programmers, it may be easier to begin
all variable names with a letter of the alphabet. The first character must not be a number or any special symbol
After the first initial letter, variable names can also contain letters and numbers. No spaces or special characters, however, are
allowed.
Uppercase characters are distinct from lowercase characters. Using all uppercase letters is used primarily to identify constant variables.
You cannot use a Python keyword (reserved word) as a variable name.
Remember a variables
value can change, which is
why we use them so we
can keep track of the
information they store.
Output:
5
Our number is 5
In this program, we created a variable called "number" and assigned it a value of 5. We then printed this out to the screen on
its own and then printed it again with some pre written text.
Output:
5
10
In this program, we changed the value of the variable after we printed our the first value. This is something that is worth doing if you
know that you are not going to need the value of that variable again.
19
Program 7: Having Multiple variables
Create a new python file and type in the below code. Save it and run it.
Output:
Hello my name is Joshua I am age 10
I am 1.4 meters in height
In this program, we have used 3 different variables, all of which have been given different data. We are storing a name (string), an
age (Integer) and a height (float) into our variables. But remember all variables are created as strings, so whilst we have values
that are integers and floats, they are not treated as such.
In this program, demonstrate what you have learnt so far about variables. How many can you create? Can you store a range of
different data types? Can you print these out with pre written text in your program and use annotations?
What level are you?
Novice Level – You will have created 4 different variables using a range of different data types and printed out to the console
Adept Level – You will have created 6 different variables using a range of different data types and printed out to the console
Master Level - You will have created 6 different variables using a range of different data types and printed out to the console, 2 of
these will also have their values chnaged after they have been printed. You will also use pre written text with your variables.
In python multiple variables can be created and be given a common value all on the same
In Python a variable line. You can also do this with different values too. The programs below, will show you
d
must be assigned an how to do this.
be given an initial
value! Remember when using
strings, they must be
inside either single or
double quotation
Program 8: Multiple statements on one line
Create a new python file and type in the below code. Save it and run it. marks!
Output:
888
Value 1 3.5
In program 8, you created 3 variables. In a single line of code (lines 2 and 6) you gave all 3 variables a value. This is an efficient
way of coding, the less lines of code you have the faster your program will run.
Refer back to the last activity, where you created a range of variables to store data. In this activity we are going to clean the
program up a bit, by putting the statements onto one line.
What level are you?
Novice Level – You will have assigned an initial value to two variables on the same line.
Adept Level – You will have assigned an initial value to all variables on the same line, with full annotation.
Master Level - You will have assigned an initial value to all variables on the same line, with full annotation and in your print
statements you will have used both the end and sep parameter.
20
Getting User Input
Right so far, you have learnt how to create variables and print these out to the screen. However most of the time when you use variables,
you will need the data to come from the user rather than it already being placed into the code. In this section, we are going to get the data
from the user and store this in variables. In order for us to do this, we are going to need to use the input() function.
Output:
Whats your name?
Isaac
Hello, Isaac
Input from user
Whats your name?
Isaac
Hello, Isaac
In this program, you have been shown two ways in which you can gather input from the All values stored in
user. Method 1, uses a print statement first to print the welcome message. Line 5, we are variables via user input by
creating our variable and we are using the input() function to tell the program, we need an default is stored as a string
input from the user. In Line 6, we print this back out to the user, like we have done in variable. To use another
programs 5 to 8. In method 2 on line 9, we create our variable first and use the input() data type you need to use
function, however we can put our welcome message/ instruction in here. Again the user
casting, which is covered
will be required to enter something into the console screen. In line 10 we print this out to
the screen.
on page 23.
Now that you know how to declare variables, allow user input, and being able to print the value of variables out to the console
screen. It’s time to create your own python program that captures user information. Your program will need to capture the
following information from the user:
First name
Surname
Age
House number
1st line of address
Town
County
Postcode
You can use previous programs to help you complete this program.
21
Variable Arithmetic
Variable arithmetic is no different to doing any other form maths, instead all we are doing is using variables to store the values and
coding our programs to do all the working out. There are several types of arithmetic we can do:
Addition + 10 + 2= 12
Multiplication * 10 * 2 = 20
Output:
Addition: 10 + 2 = 12
Subtraction: 10 - 2 = 8 You can use \t inside
Multiplication: 10 x 2 = 20 quotation marks which adds an
Division: 10 / 2 = 5.0 invisible tab to the format of
Floor Division: 10 / 2 = 5 your output.
Modulo: 10 % 2 = 0
Exponent: 10 ^2 2 = 100
In this program, we have used all the different arithmetic operators that are available to us in Python. You can see from the
output each one produces a different result. You can change the values of a and b to different values to get different results.
Try changing the 10 and the 2, to floats and see what results you get.
Program 11: Storing the Result
In this program you are going to learn how to get two variables that use arithmetic and store the result in a whole new variable to be
used at a later date. Create a new Python file and copy the below code.
Output:
The Sum is 12
In this program, we have done something new. We have created a variable that stores the results of two variables that have been
added together. We did this by creating our variable which we called 'sum' and we assigned that value of num1 + num2 and then
stored the result.
22
Using Shorthand Operators
We have looked at how to do some mathematical exercises in python using a range of different operators. However there are quicker
ways we can perform these, by using shorthand operators.
/= a /= b a=(a/b)
But, how do we store the value in 'a' or 'b' if we are using
them? The table to the right shows how we do this. %= a %= b a=(a%b)
Program 12: Assigning values
Create a new Python program and copy the code into your new
program. Save and run your code.
Output:
Assigned values: a = 8 b = 4
Add & Assign: a = 12 (8 + 4)
Subtract & Assign: a = 8 (12 - 4)
Multiply & Assign: a = 32 (8 * 4)
Divide & Assign: a = 8.0 (32 / 4)
Modulo & Assign: a = 0.0 (8 % 4)
Output:
If you have
20
pea pods
and
8
peas in each pod, then
you have
160
peas in all the pods.
This program does the same thing as program 11, however we are using multiplication here instead of addition. The issue with this
program is that the output is very untidy and there quite a few lines of code. This code can be easily simplified to make it more
efficient.
Using program 11: Peas in a pod, try and reduce the lines of code and tidy up the formatting of the output, which you can see is
not very presentable.
What level are you?
Novice Level – You will have reduced the program by 3 lines of code and have tidied up the output
Adept Level – You will have reduced the program by 6 lines of code and have tidied up the output
Master Level - You will have completely re written the program to be as efficient as possible, using a range of programming
techniques that have been covered in this guide.
23
Program 14: Using Brackets
Create a new python and copy the below code. Save and run it after you have done it to see the results.
Do First
BIDMAS BODMAS
Brackets Brackets
Indices Order
Output:
100 Division Division
-16
Multiplication Multiplication
Don't forget your BIDMAS/BODMAS!
Addition Addition
In line 2 (10+10) is calculated first, as these are in brackets and Do Last
then this is multiplied by 5, giving us our final answer of 100. Subtraction Subtraction
Line 5, we have not used brackets and instead the program is working it out as 2*10 = 20 then taking 20 away from
4, giving us a negative number.
Create a program that stores, 3 numbers in 3 different variables. You are to find the mean average of those numbers and print this
out to the user. Your output should look like the below example:
Output:
The mean average of 54 is: 18
Create a program that prints out the below. You should only use one variable and the exponent mathematical operator.
Output:
128 64 32 16 8 4 2 1
Create a program that converts Celsius to Fahrenheit. The formula to this is:
Output:
32C is 89.6F
24
Casting Variables
As mentioned on the previous pages that by default any data you store in a variable is stored as a string data type. The reason for this is
due to a process called "Dynamic Typing". In other languages such as C++ or Java, the programmer at the time of coding their
variables has to specify the data type they are storing in those variables. This is so the program can reserve the correct amount space in
main memory to store those variables, this is called "Static Typing". In Python the amount of space that has been assigned to the
variables is a dynamic process and removes the limitations of using fixed amounts of memory to store data.
However there will be times where you will need data in your program to be stored as an integer or a float data type so that it can be
used for mathematical operations.
So far the mathematical operations we have done have used variables where the values have been assigned to them already. So we will
need to get the user to enter these values, but there is a catch to this which we will explore.
This program does the same thing as program 11, however we are using multiplication here instead of addition. The issue with this
program is that the output is very untidy and there quite a few lines of code. This code can be easily simplified to make it more
efficient.
Concatenation is the
technique of joining more than
one string together. Like the
Output: program to the left
Please enter the first number to add: 5
Please enter the second number to add: 5 Input from user
The sum is 55
Well that's because when a user enters anything into a variable, by default its stored as a string . What we have done is taken two
string variables and put them together not add them. This is a process known as concatenation. This however, is no good to us, we
need to store these as either integers or floats.
Create a calculator program that asks the user to enter two numbers, which are to be added, divided (Including Floor Division),
multiplied, subtracted and the use of the modulus mathematical operator. You should print out each answer.
What level are you?
Novice Level – You will have completed the program above, referring back to previous exercises.
Adept Level – You will have completed the program above, using some short hand operators and full annotations
Master Level - You will have completely the program above using all short hand operators and full annotation, with your code
being as concise as possible.
25
Comparing Variable values
There may be times, when you need to compare the value of two different variables. In this section we are going to explore how we do
this using comparable operators. You maybe familiar with this concept already from your maths lessons, but just to recap:
Equality Inequality
16 == 16 14 != 16
The equality operator (==) will compare the The inequality or not equal to operator (!=)
true true
value of two operands (values/ variables) and will return true when both values are not the
12 == 16 16 != 16
will return a true a value if they are both the same. If they are both the same they will the a
false false
same in value. If they are not, then a false false value will be returned.
value will be returned.
== Equal to (Equality)
Output:
Equality 0 == 0 True
Equality A == a False A-Z uppercase characters have
Inequality 0 != 1 True ASCII values 65 - 90 and a-z
Greater than 0 > 1 False lowercase have ASCII code
Less than 0 < 1 True values 97-122.
Greater or Equal to 0 >= 1 False
Less or Equal to 0 <= 1 True
In this program, we created 5 variables and we compared them against each other using the comparable
operators above. However you are probably wondering how uppercase 'A' and a lowercase 'a' are not the same.
This is because 'A' and 'a' have different values and you will learn about this when you look at ASCII tables.
Create a program that compares the following values together. Make a note of the result:
Y and y
B and B
300 and A
a and 52
26
Logical Operators
You are already familiar with AND, OR and NOT logic, when you looked at logic gates, but here is a reminder on the how logic works
and how we can implement this using a programming language.
The OR logical operator is different however, it only needs one of its operands to have a true
a b a or b
value in order for the whole logical operation to return true. If neither of the operands contain a
true value then the whole operation will become false.
false false false
false true true Lets look at a real world example, Harry must do his homework (a) OR eat his dinner(b), so he
can go out and play. If you use the table to the right, Harry can only go out and play if the a or b
true false true columns have a true value. If both the a and b column have true values, then the final value will
be true.
true true true
a b a and b
The AND Logical operator, will only return true, when both of the operands are true. If either
one of the operands contain a false value then the operation will return a false value. false false false
for example if harry wants to go out and play he must do his homework (a) AND eat his dinner false true false
(b). So he must do both in order for the statement to produce a true output.
true false false
a not a
true true true
false true The NOT operator is a single input operator, that when used will return the inverse value of the operand. So if
variable a contains a true value and then we use the not operator, then the value would become false. for
true false
example if our variable 'a' holds a true value and we then use the not operator, it will come become false.
Output:
AND LOGIC)
a and a = True
a and b = False
b and b = False
OR Logic
a or a = True
a or b = True
b or b = False
NOT Logic
a = True not a= False
b = False not b= True
Create a program that prints out the AND, OR and NOT truth tables. For a guide on what these should look like use the tables
above. Try replacing the true and false values by using ones and zeros instead.
27
The ASCII Table
As you have learnt in your previous lessons that computers can only understand numbers, so in order for them to understand characters
like 'A' or '#' or even commands such as delete or backspace, they have to be assigned a special code, this is where ASCII comes in.
ASCII, which stands for American Standard Code for Information Interchange, gives each character a unique numerical code so that it
can be processed by the CPU. There are 128 unique codes, but only codes from 32 - 127 are used.
The ASCII table provided below is a simplified version, however you can get extended tables which show the binary, octal, hexadecimal
and html code for each character. No mater what table you use, the codes remain the same across all programming languages.
Dec Char Dec Char Dec Char Dec Char Dec Char Dec Char
32 Space 48 0 64 @ 80 P 96 ` 112 p
33 ! 49 1 65 A 81 Q 97 a 113 q
34 " 50 2 66 B 82 R 98 b 114 r
35 # 51 3 67 C 83 S 99 c 115 s
T 116
The values of 'Y' and
36 $ 52 4 68 D 84 100 d t
37 % 53 5 69 E 85 U 101 e 117 u 'y' have two different
38 & 54 6 70 F 86 V 102 f 118 v values, therefore are
39 ' 55 7 71 G 87 W 103 g 119 w treated differently by
40 ( 56 8 72 H 88 X 104 h 120 x the CPU.
41 ) 57 9 73 I 89 Y 105 i 121 y
42 * 58 : 74 J 90 Z 106 j 122 z
43 + 59 ; 75 K 91 [ 107 k 123 {
44 ' 60 < 76 L 92 \ 108 l 124 |
45 - 61 = 77 M 93 ] 109 m 125 }
46 . 62 > 78 N 94 ^ 110 n 126 ~
47 / 63 ? 79 O 95 _ 111 o 127 [DEL]
Output:
The ASCII value of ' A ' is 65
The ASCII value of ' a ' is 97
The value of 97 in ASCII is: n
Pythön is interesting
In this program, we created a variable called 'c' and assigned the value 'A'. Using ASCII has 128 unique
the ord() function, we are taking the character stored in our variable and values, however Unicode
converting it to its decimal value in ASCII. Then we changed the value of the has over 140,000 values
variable to 'a' and used the same function. Did you noticed that this produced consisting off, emojis,
different values? symbols and text.
Using the char() function on line 10, we were able to type in our decimal value
to print out the corresponding ASCII character, in this case we printed out the
value 'n'
On line 13, we use the \x as a string escape sequence, the value after the x which
F6 is a hexadecimal value for the Unicode symbol of 'ö'
Using the code above for guidance, print out the the decimal values for the following string "QWERTY". Once you have
completed this then, print out the ASCII character values for 65,105,114,80,111,100,115 in one complete string.
28
Code It Yourself - Activity 15
You have just brought a flat, which needs new carpet. You have a copy of the floor plan (below), that shows the measurements
in each room, which has been measured in feet.
Sample Output:
DEN: Please enter the Length of the den: 10
DEN: Please enter the width of the den: 15
The den in total is 13.93m2
The den will cost £153.15 if the carpet was £10.99 per m2
Extension Activity
Add a section to your code, that allows the customer to checkout by entering their personal details including delivery address.
You must ask the user to enter their payment details including card number (16 digits) expiry date (4 digits) security code (3
digits).
29
End of Chapter Quiz
(Variables & Data Types)
You have now reached the end of the second chapter. Below are some questions that you should go ahead and answer. Check the answers
with you peers and teacher.
1. List the different data types that you can use in Python and provide an example of what data they can store.
5. Referring back to the ASCII table why are the values 'D' and 'd' different characters?
30
6. Whats the difference between AND, OR and NOT logic. Provide examples.
7. If A = TRUE , B = FALSE, what is the output if the expression is A AND B? Explain your answer.
8. What is the result when using the below operators with the following variable values:
A=4 B=2
A**B A+B
A%B A*B
A//B A-B
9. What is the difference between using a single forward slash / to a double forward slash (//) when performing variable arithmetic?
11. Below are some variable names. Highlight which ones are acceptable and in a different colour highlight the ones that are not
acceptable.
31
Page left intentionally blank
32
3 Conditional Branching
Conditional statements are used when we want to run specific block of code when a certain condition has been met. We can implement a
conditional statement by using the following methods:
IF statement
IF Else statement
Elif (Else if) statements
These statements can alter the flow of the program, which is ideal when you want your program to perform specific tasks. In this section
we are going to look at the different types of statements to see what impact they can have on our code.
IF Statement
With an IF statement we just test the condition, which is the value stored in a variable and if the result is positive then the code block in the
if statement will execute. If a false value is returned the program carries on as normal. for example:
if Harry is 13 or over:
print ("He can play Fortnite")
So in order for the above statement to be true and for the message to print out Harry must be 13 or order. If he is not 13. the program will
simply ignore the print out message and proceed with the rest of the code.
IF Else Statement
The IF Else statement will made up of two code blocks, unlike if, which was has one. If the
If condition is true
condition is true the 1st code block is executed. If the value is false then the second code
Condition
block is executed. Here is an example:
34
Elif (else if) statement
With an else if statement we can check for for multiple conditions. The first condition
will be tested, if the result is false, then the program will proceed to test the second
condition. It will keep doing this until either the condition is true or until it has tested true
all conditions and run the else code due to all conditions being false. Condition Statement 1
1
if Harry eats his dinner:
print("He can go out and play") false
elif Harry does his homework:
print ("He can do some programming in Python") true
elif Harry does his chores: Condition Statement 2
print ("He can play some games") 2
else: false
print("He has to tidy his room")
true
In this example we will first test if Harry has eaten his dinner, if he has not the Condition Statement 3
statement will return false and now the program will check the next condition. In this 3
case the program will check if Harry has done his homework. If he has the condition
will return true and run that code block. One finished it will jump to the code after false
true
the else if statement. else
Think of the if, elif and else as a conveyor belt system. Starting with IF, working its way down as it
checks the condition. If the condition is false, then it moves to the next stage of the control structure.
IF
else
Indentation
When you go to write your own if statements in Python, indentation is so important. Code that has the same level of indentation
is treated as the same code block from top to bottom. If you do no ident your code when using not only just if statements, but
loops and functions, you will run into Syntax error. Indented code looks like this:
You can indent your code easily by using the tab button on your keyboard, which looks like this:
35
Branching with If
In this section we are going to look at branching with the simple if statement to test a variety of different conditions.
Have you noticed that we have used comparable operators to check if the value of score is greater than 70? What
would the ouuput be if you changed the number to a lower value or if you changed it to 70?
Using the above program as a guide, create a program that asks the user to enter a number. If the number is less than or equal to
50, then tell the user they entered a number 50 or lower.
Output: Output:
You have passed the exam You didn't pass the exam
So we have two copies of the same program, the only difference between them is that we have changed the value on line 2 of the score
variable. This is so we can demonstrate how different code blocks are executed when the value of score is different.
A shop which sells pre-owned console games, would like a small program written that asks the customer to enter their first
name, surname and age. If the customer is below the age of 18, the shop cant sell any games rated 18. Create a program that
determines if an 18 game can be sold to the customer.
What level are you?
Novice Level – Demonstrates that they complete the above program to a good standard, but needs further development around
making the code presentable and efficient.
Adept Level – Partly annotated code, with some code efficiency and demonstrates some of the the programming techniques
covered.
Master Level - Full annotations throughout the program, with concise code that has been written efficiently and demonstrates all
the covered programming techniques.
36
Branching with If, Else and Elif
In this section we are going to look at branching with if, else and elif.
Output:
You have passed with a pass grade
Output:
Welcome to an example menu
Option 1:
Option 2:
input
Option 3:
Option 4:
Please enter an option: 1
This is option 1
Create a program for a cinema booking system. Give the user a choice of going to watch 5 different films. They are to select
which film they would like to watch. When they select the film they would like to show you should show them, the cost of the
film per ticket and the different showing times. You should annotate your code throughout.
Output:
Welcome to Mr Oliver's calculator
Do you want to
add(+)
subtract(-) input
multiply(x)
divide(/)
What would you like to do: +
Please enter a number: 5
Please enter a second number: 5
The answer is 10
37
Code It Yourself - Activity 19
A local shop is having a promotion. If you spend over £10.00 they will give you £1 of the cost of your shopping. If you spend
£20.00 they will give, you £2.50 off your shopping. If you spend over £50.00 they will give you £7 off. Create a program that
asks the user to enter the total cost of the shopping to show which discount should be applied.
Sample Output:
How much was the cost of the shopping? £24.99
The total discount will be £2.50, bringing the total cost to £22.49
Write a program that asks the user to enter a number between 1 and 12, whcih based on the number entered will show the
corresponding month for that number.
Sample Output:
Please enter the month number: 5
The month is May
Extending your program further from activity 20, adapt your program so that it asks the user to enter three numbers for year,
month number, and date (e.g. 2001, 5, 11) and outputs the date in the form 5th November 2001.
Sample Output:
Please enter the year: 2022
Please enter the month number: 5
Please enter the day: 4
In this activity you are you are going to create a program which compares the cost of buying a mobile outright with a sim only
and buying it on contract. The program will tell the user which is the better option at the end.
Sample Output:
What phone are you looking at: iphone
How much does the phone cost to buy: 999.00
How much is the sim only contract per month: 6.00
Okay, so your phone on contract will cost £1232 over 24 months. The cost of buying your phone plus the sim only deal for 24
months will cost £1143, You will save £89 buying the phone outright and going on sim only.
38
Nesting Statements
Nesting is a term when we insert one statement inside another. For example you might create a conditional statement and insert a loop or
another conditional statement. This is what nesting looks like:
Syntax of Nesting
Create a new python program, copy the below code, save it and run it.
Be aware that nesting too many
statements inside of each other
can get confusing and may cause
syntax errors if you are not
careful.
Output:
Please enter a number between 1 - 50: 32 input
Your number is between 26 and 50
Output:
Do you want some pasta?y input
Great, let me cook you some
What type of pasts did you want: Penne(p), Fusilli (f), Orzo(o)p
Great Penne Pasta it is!
39
Using Logic with IF statements
We have already covered the fundamentals of logic in the last chapter, where we compared two variable values. In this section we are going
to look at doing the same, but using conditional statements.
Output:
Did Harry do his homework? (y/n) y
input
Did Harry eat his dinner? (y/n) y
Well done Harry you can go out to play
So we have looked at implementing both the AND statement and the OR statement using a conditional
if statement. Nice work! lets explore further...
40
Program 30: Using NOT
This program we are going to tell our program to print out the 1st statement as long as the
value is not an equal to n. Create a new program, copy the below code, save it and run it.
Output:
Did Harry do his homework? (y/n) y
Well done Harry you can go out and play
input
Our program above, will only print out the first statement, as long as a lowercase 'n' has not been entered by the user. However if an
uppercase 'N' has been entered the first statement will execute, which means that our program does not work as we would expect it
too. we can easily fix this, by changing the line of code on line 3 to this:
Output:
Please enter a number between 0 and 20: 5 input
Your number was 5
In this task you are going to create a small menu program. You are going to present the user with 3 different categories; Drinks,
Sandwiches and Snacks. When the user selects one of these categories, you will show the different options available in each one.
Sample Output:
Pick an option below:
1. Drinks
2. Sandwiches
3. Snacks
Option: 2
We have the following items:
Ham and Cheese
Halal Chicken Salad
Prawn An Mayo
Cheese and Pickle
41
Code It Yourself - Activity 24
In this activity you are going to create a multiple choice quiz. You can choose which ever subject you want for the questions.
Sample Output
4. In Harry Potter, how many houses are there at Hogwarts?
a. 2
b. 3
c. 4
d. 5
Answer: c
Well done that is correct! You get 1 point. You have 3 points.
You scored a total of 3 points out of 5. Thats not bad, you could do better next time.
Go Further
If the user gets a score of 5 points, giving him 100%. Give them the choice to play the Bonus question. If they say yes, give them
one last question which is worth 2 points. The user has to type the answer in rather than select multiple choice. Show the final
score with or without their bonus score.
Sample Output
Well done you got 5 out of 5 points. Do you want to play the bonus question (y/n): y
Bonus Question:
Which company holds the record for most tyres manufactured in a year?
Your Answer: Lego
That's the correct answer!
You have a total score of 7 out of 7. Well done.
42
End of Chapter Quiz
(Conditional Statements)
You have now reached the end of the third chapter. Below are some questions that you should go ahead and answer. Check the answers with
you peers and teacher.
1. What is the difference between a conditional statement that uses an “if/else” statement and one that uses an “if/elif” statement?
< >
<= >=
!= ==
5. What is the result of each of the following expressions given the following variable assignments ? (True/ False)
x=4 y=5 z =4
x>y x != y
x<y x >= z
x == y x <= z
43
6. Refer to the flow chart below for question 6.
Start 6a. What is the Python code equivalent of the diamond flowchart symbol in the program
above?
examScore = 95
Output
False "Excellent" 6c. What would the output of the program be if the value of the variable examScore was
set to 85?
End
7e. What boolean operand has been used in this program and what does this mean?
8. Is the use of the else statement mandatory when creating an if/elif statement? Explain your answer.
9. Explain how the character 'P' and 'p' are different. How could different letter casing effect a if statement?
44
4 Loops
Sequence
Selection
Iteration
In programming a loop is a block of code that will keep repeating itself over and over again
until a condition has been met. Every time a loop is repeated is known as pass through or an
iteration.
Loops are the third and final control structure to programming. In python there are two
types of loops, which we will cover in-depth.
WHILE Loop
A While loop will repeat a statement while a condition remains true. Think of a while
loop as an if/else statement, but one that will repeat. Here is an example of the syntax for
a while loop
Code Block There is no guarantee that a while loop will ever run. When the condition is tested, if the
the result comes back as false then the loop is completely skipped and the code
immediately after the loop will be executed.
This type of loop has so many different uses, which we will explore later in this chapter.
FOR Loop
A for loop is a loop that can be used to repeat something for a fixed number of times. It
can also be used to cycle through lists, tuples and sets, which we will cover in the next
chapter. The syntax for a for loop looks like the following: Last
Element?
for (expression):
statement to be executed No Yes
You might have noticed that in the syntax examples above, indentation has been applied, just like we saw with if-statements. Again, this
indentation holds a special meaning in Python. In loops, the block of code that is indented holds the statements that need to be executed
over and over while the loop is running. As soon as the loop conditions are met, the indented code stops running, Python jumps out of
the loop and will then process the rest of the code in the program.
46
While Loops
In this section were are going to explore the full use of the while loop and discover the different ways in which it can be used to repeat
code.
Program 32: The While Loop
In this program, we are going to create a variable and give it the value of 11. This is so that the loop we have created on line 3,
can at least execute the one time. On line 3, while the value stored in number remains 10 or higher, the code block on line 4
will keep repeating. Create a new program, copy the below code, save it and run it.
Output:
Please enter the number 10 or lower: 15 Be careful whe
n creating
Please enter the number 10 or lower: 9 loops, if you ar
e not you
Great work number is lower than 10 could end up c
reating an
infinite loop
Loop Counters
A loop counter is used to control the amount of iterations a loop performs. Loop counters can be used to
increment the iterations of a loop or can be used to decrement a loop . A common identifier for counters are used
with variable names called I, j, and K etc.
Output:
If you wanted Please enter the number you want to count up too: 5
to count
backwards, all 1
you need to do
subtract 1 from is 2
your counter,
rather than ad 3
d 1.
4
5
Create a grading program that asks the user to enter a grade. While the grade is below 70% display the message “That’s not
good enough try again”. Your program should count the amount of times the loop had to repeat.
Sample Output
What was your exam score? 52
What was your exam score? 65
What was your exam score? 76
Well done, you passed the exam. This loop iterated 3 times.
Create a program that counts back from 10, when then counter reaches 0, the program should say "blast off!". Look at
program 33 for hints on how to complete this.
47
Breaking and Continuing While Loops
Program 34: Breaking out of the loop
There are time, where you will need to stop the loop from repeating, this can easily be achieved by using a break command. In
the below program we are going to use the same code as program 33, but we are going to insert a break command into our code
block.
Output:
Please enter the number you want to count up too: 20
The break statement in Python
1
terminates the current loop and
2
resumes execution at the next
3
4 statement.
5
No matter what number the user enters into the program, it will only go up until the value of 5. Once this
value has been reached the loop will stop cycling.
Output:
Please enter the number you want to count up too: 5
1 Both the break and continue
2 command can be used in the wh
ile
4 loop and for loop.
5
We used the same program as 33 and 34, but we tweaked it slightly. You will have noticed we have moved
some of the lines around, for example the counter is now at the top of our code block in our while loop. This
is to stop our loop from not cycling correctly. On line 7 we have implemented the continue command, which
will be executed when the loop counter reaches 3. Try moving the code about to see what happens.
Create a program that asks the user to enter the following information: First name, Surname, Age, 1st Line of Address, Town,
County, Postcode, Email address and phone number. After they complete this, your program should show the information to
them so that they can check it. Ask the user if they are happy with the information, if they are not then you will need to get
them to reenter their details. If they are then just say thank you for entering their details.
48
While/else Loops
Both the while loop and for loop can have optional else blocks added as well. The else part of the loop will be executed when the loop
when the sequence of the main block of code has been exhausted. Lets take a look at how we do this using the while loop.
Look at the below code, create a new program, copy the code, save it and run it.
Output:
Please enter the temperature outside: 31
Air Conditioning has been turned on.
Please enter the temperature outside: 32
The air conditioning is already on
Please enter the temperature outside: 17
Air conditioning has been turned off
Output:
I've thought of a number between 1 and 10. Try to guess it. If you use the break command to
Guess the number: 6 exit the loop, then the else sect
ion
You got it wrong will not run.
Guess the number: 3
Well done. Press any key to exit.
After you have copied down the code from program 38. Edit the code so that it can do the following:
Count the amount of attempts it has taken the user to guess the number and print this out
Change the range of the generated number to 1 to 20.
Tell the user if their guess it lower or higher than the generated number
limit the amount of attempts that user can take to 10. After 10 attempts, if they don't have the correct number, then its game over!
49
Looping While True
As previously stated that the while loop will only execute while the condition remains true. If the condition is false this is when the else
block would be executed, which will either be immediately or after a few iterations of the loop. This is why it's important that your while
loop has been structured in the correct way to prevent logical errors with your program. Let's look at an example of this.
Output:
Did Harry, complete his homework? (y/n): n
Did Harry eat his dinner? (y/n): n
Okay so this program has no syntax errors, but does have logical errors. As a
Dinner Homework a AND b
result this program will not run correctly. The code between lines 4 and 5 will
only run when the loop is true. The loop will only run true as long as the values
false false false
of homework and dinner remain as a lowercase 'n'. Refer to the table on the
right to see how this would work, if you were to change values you will never false true false
get the output you would hope for. Look at program 40 for the correct
solution. true false false
Create a new file, copy the below code, save it and run it. Try removing the break command what happens?
Output:
Did Harry, complete his homework? (y/n): y
Did Harry eat his dinner? (y/n): n
Eat your dinner and do your homework Harry
Did Harry, complete his homework? (y/n): y
Did Harry eat his dinner? (y/n): y
Great, well done Harry you can go and play Xbox
is also known as
ue loop and False
A while tr Did you know that True
finite loop. ords that
an in are the only Python keyw
tter.
start with an uppercase le
This program checks to see if the user has entered the correct password. Add a while command that loops repeatedly prompting for the
password while an incorrect password is entered. When the correct password is entered the program displays “Access granted”.
50
More to do with While
Program 41: While with OR
In this program, we have used a while loop with OR, where the loop will true as long as one of the conditions we are looking for is true. In
this example, we are looking for either a lowercase 'y' or an uppercase 'Y'. Copy the below code, save it and run it.
Output:
This program is Please enter any location of your choice: Asgard
good reminder Please enter the name of a fictional character: Gandalf
Please enter the a species of animal: Hamster
of how to use
What power do they have: Telekinesis
string
Once upon a time in the lands of Asgard lived a magical creature called Gandalf ,they were the
concatenation most magical type of Hamster their power was Telekinesis .
Do you want to try again? n
Thank you for playing
Output:
The none keyword is not the same as
Do you want to calculate area or Perimeter. Enter a or p: n
giving a variable the value of false or
Do you want to calculate area or Perimeter. Enter a or p: A
Area 0. Its like creating an empty cell in a
Area = 20000 table and leaving it blank.
Create a variable called total and assign it a value of 0. Ask the user to enter a number, store the value of this number in the total
variable. Ask the user again if they would like to enter a another number, while they keep asking yes, keeping adding the value entered
to the total variable. When the user selects no, then your program should show how many times the loop executed as well as shwoing
the total value stored in the variable total.
51
The For Loop
In this section, we are going to look at the for loop and how we can use this to cycle over a particular block of code for a certain amount of
time. The for loop is a very powerful loop and we will explore this further in the next chapter when we look at collection in Python, which
consist of; Lists, Tuples, Sets and dictionaries. In this section we are going to show you how to create simple for loops.
Output:
0
1
2
3
The range function can be made up of 3 parts, start position, the stopping position and how many steps it increments between start and
stop. The syntax looks like this: for a in range (start, stop, step)
In this program , we are going to show how to use both the start and stop, as well as the start, stop and step with the for
loop. Create a new program, copy the below code, save it and run it.
'a' is the name of our variable
Output: which we have created in the
1
for loop. It is used to store
2
3 the integer value of the
4 current position in the loop:
0 - Position 1
1 1 - Position 2
Starts at 1, goes up to maximum value of 11 (But doesn't print 11), 3 2 - Position 3
increments by 2 steps Start Stop 5 3 - Position 4
Step
7
9
52
Using Break and else with For
Just like the while loop, you can also use the break and continue commands to either exit the loop or to skip over iterations. In this section
we will look at how to do this.
We do this by taking the number entered by the user and we use the modulus arithmetic operator to see if the remainder of the division
between the entered number and the position of the loop equals to 0. If the number is not equal to 0, it will continue to iterate through
the loop up to the number entered (remember user number - 1). If there is no 0 to be found, then the number entered is a prime number.
Copy the below code into new file, save it and run it. Test it on numbers that you know to be prime numbers and ones you don't.
Output:
Please enter a number to check: 10
10 is not a prime number
2 x 5 = 10
Like the while loop, the for loop will execute once the loop
Please enter a number to check: 5 has been exhausted. Remember if a break command is used,
5 is a prime number then the else block will not be executed.
Look the code snippet above, edit this program, so that when the loop iterates and the loop is equal to the position of 'h' that you
break out of the loop.
53
Nesting Loops
We have covered the term nesting when we covered if statements on page 34. In fact nesting in loops is really important and is important
when facing complex programming challenges. In fact you have already been nesting with loops, by placing if statements inside both for and
while loops. You just haven't put a loop inside a loop yet, which is what this section is about.
In programming the first loop, is always known as the outer loop. The loop that has been nested inside the outer loop is known as the inner
loop. As you can see from the example below, you can see where our outer and inner loops are.
The same
Outer Loop Inner Loop applies to
while loops
too
Create a new file, copy the below code, save it and run it. Try playing around with the Yes Repeated 5
values in the range function. i=i+1
times?
No
Yes
Repeated
j=j+1
12 times?
Output: No
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
k=i*j print k
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
Sample Output:
Code It Yourself - Activity 32 A12345
B12345
Create a program that prints out a mini grid system, like the example given to C12345
the right. Look at the previous two programs to help you find the solution. D12345
54
Like the for loop, we can also nest the while loop too. When we nest our loops, we are still creating an outer and inner loop, as we can see
from the example below.
Outer Loop
Inner Loop
Create a new file and copy the code below, save it and the run it.
Condition
2
Statement
Output:
1 Outer loop is executed only once
1 Inner loop is executed until to completion
2 Inner loop is executed until to completion
Did you know that
2 Outer loop is executed only once
the For loop is faster
1 Inner loop is executed until to completion
2 Inner loop is executed until to completion than a while loop? So
use a for loop where
you can!
Output:
2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number
Using nested while loops create the multiplication tables starting with the ones timetable working up to the tens. It should look
something like the below:
Sample Output:
1-2-3-4-5-6-7-8-9-10-11-12
2-4-6-8-10-12-14-16-18-20-22-24
3-6-9-12-15-18-21-24-27-30-33-36
4-8-12-16-20-24-28-32-36-40-44-48
Hint: You can achieve this by writing only 8 lines of code.
55
Mopping Up Loops... for now
We are now reaching the point with what we can do with a loop, without bringing in extra features that we have not covered yet. In this
section, we will cover a few good things to know that will make your programming with loops easier and manageable for future projects to
come.
Program 52: The Pass Statement
We are use to using the break and continue statement that we have used in other programs, but there is one other statement type that we
can use, which is called the pass statement.
The pass statement allows you to handle the condition that may be inside a loop, without the loop being impacted in any way. This is
useful as we can use the pass statement to act as a placeholder when working on new code, or if you want to structure you program in a
certain way, but are not ready to code this yet.
Output:
Number is 0
Number is 1 u can use the pass
Yo
ith if
statement w
Number is 2
Number is 3 too.
Number is 4 statements
Loop Finished
In this example, we have used the pass statement inside a if statement. When the loop cycles and our variable number is now equal to the
value of 3, the if statement will execute however, the pass statement will have no impact on the flow of the loop like we would expect
from the break and continue commands.
Output:
H
a
y
P
o
t
t
e
The End
Program 54: Skipping Over Multiple Values
We can skip over multiple values when we use our For loop, to do this we just need to add conditional logic into our if statement.
Using the key word OR, we can say when the value equals to "a" or "t" then apply the continue coomand.
Output:
H
m
s
e
r
The End
56
Code It Yourself - Activity 34
In this activity you are going to create a cinema booking system. Your python program, should do the following:
Display a menu
Show at least 3 different film times for at least 3 films.
Print out the cinema seating plan, clearly showing where the screen is situated
Display Prices for the cinema
Allow customers to book their tickets.
A summary of the film the user is seeing, the total cost and confirmation of their seat numbers.
Sample Output
***********************************
Welcome to the Cinema Booking System
***********************************
Sample Output
***********************************
Ticket Bookings
***********************************
---------------------------------------------------------------------
The Screen
---------------------------------------------------------------------
A 1 2 3 4 5 6 7 8 9 10 11
B 1 2 3 4 5 6 7 8 9 10 11
C 1 2 3 4 5 6 7 8 9 10 11
D 1 2 3 4 5 6 7 8 9 10 11
E 1 2 3 4 5 6 7 8 9 10 11
F 1 2 3 4 5 6 7 8 9 10 11
You could use the program you created for code it yourself activity 18 and then build from that if helps.
Go Further
Edit the code so that you print out multiple seating plans for different size cinema screens. You could allocate one film per
screen. In addition, add conditional checks in to your program so if that a user tries to book a seat that does not exist give them
an error message letting them know they have made a mistake.
57
End of Chapter Quiz
(Loops)
You have now reached the end of the fourth chapter. Below are some questions that you should go ahead and answer. Check the answers with
you peers and teacher.
2. What is the difference between the while loop and the for loop?
3a. What does the above code do? What does it display?
3b. What loop is the outer loop and what loop is the inner loop? What does each loop do?
58
For question 4 use the above program:
5a. Beside each line of code above explain what the code does.
5b. How do you change a print statement so that it does not signal the computer to write on a new line?
5c. What is the purpose of the code on line 8? What do we call it? Why do we need it?
6. Consider the code snippet below, what is the purpose of the range function?
59
7. What does the pass command do?
60
5 Lists, Tuples & Dictionaries
Output:
[]
['Jaguar', 'Leopard', 'Tiger', 'Lion', 'Puma']
[1, 5, 9, 10, 12]
['Dog', 2.5, '#', 8]
This was then printed out to the screen. You will have noticed that we can store any
type of data into our string. The items in the list are
separated by using
commas
0 1 2 3 4
Output:
['Cat','Dog', 'Rabbit', 'Fish']
Cat
Dog
Rabbit
Fish
Output:
Cat
Dog
Rabbit
Fish
Create a list with eight different names in it. Then print these out a single string like the below example:
Output:
My name is Harry Potter
My name is John Snow
60
Program 58: Negative Indexing
In the previous program, we were able to print the items of in our list, by specifying which index number we wanted to use. However we can
use something called negative indexing to also specify which index of the list we want to deal with. Create a new file, copy the code below,
save it and run it.
Output:
Fish
Fish
0 1 2 3
Negative indices are popular as they are faster, but are used when programmers don't know the length of any list, but want to access the last
index. Using negative index number can achieve this result.
Output:
Stop before position -5 index
Fish
Rabbit
Dog Decrement by 1
Cat
Create a program, which stores multiples of ten in a list, up to 120. Use a loopback to print thes multiples in reverse order. Your
outpu should look like the below:
Sample Output:
120
110
100
90
80
70
61
Slicing Lists
In Python, so far we have printed out either our entire list, or specific elements, but there is a way we can print our a specific range of
elements from this list. Off course we could use a loop to do this, but this would be inefficient, especially as Python gives us the option to
do this, using the slice operation. We can use the slice operation by using colon between our index numbers in the square brackets. For
example myList[index:index]. The below programs, will show how we can do this.
Program 60: Slicing the List
In this program, we are going to slice the list and print out different items in our list by specifying the range of items. Create a new file, copy
the below code, save it and run it. Play around with the numbers inside the brackets and see what is displayed on the screen.
Output:
['Green', 'Blue', 'Pink']
['Blue', 'Pink', 'Yellow', 'Orange']
['Black', 'Red', 'Green', 'Blue']
['Black', 'Red', 'Green', 'Blue', 'Pink', 'Yellow', 'Orange']
The below illustration can help you visualise the range you would need to specify
to ensure you get the right colours to print out to the screen.
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1
Output:
['Yellow']
['Pink', 'Yellow', 'Orange']
['Black', 'Red', 'Green']
['Orange', 'Yellow', 'Pink', 'Blue', 'Green', 'Red', 'Black']
As you can see from the output on line 9, we can reverse print our list by using . Again this is far more efficient than using a loop to
do this for us, like we did in program 59.
62
Adding Items to Lists
When you create a list, the elements of that list are not set in stone, the values of the list can be changed, removed and added. In this
section we are going to look at the three different ways that we can add items to our lists, by using three different methods. These methods
are: , , .
ariable that
A parameter is a v
to a function
has been passed in
r m eth od . Yo u w ill be using a
Program 63: Adding Items to Lists (Insert) o
o f th ese as you a dd items or
In this program, we are going to add items to our list, like we did in the previous few
lists.
program, but rather than add these to the end, we can select the position remove items from
where we would like the new values to be inserted to. We do this using the
method.
Output:
['Cat', 'Dog', 'Rabbit', 'Fish']
['Cat', 'Dog', 'Hamster', 'Rabbit', 'Fish']
Please add item to the list: Bird
['Cat', 'Dog', 'Hamster', 'Bird', 'Rabbit', 'Fish']
When you add items using the , you can select where in the list these values are positioned by selecting
the index number. Once an item has been added to your list using insert, then everything from that point is shifted
to the right. Using the illustration below, you can see exactly where each of the values were positioned into the list.
63
Program 64: Adding Items to Lists (Extend)
Moving on to the last method that can be used to add elements to our list we now look at the method. This method can be
used to take the value of one list and append it to another list. The alternative option is that you can append multiple values to the end of
the list from either user input via variables or coding the values yourself. The program below covers the different ways in which this
method can be used.
The method is a powerful tool to use, if you are adding multiple items to a list, by either taking the values
from another list or adding values from either user input, or placing the values into you code.
Stored as "Mouse"
The comma used next to the string value prevents the string from being broken up into separate items.
Output:
Please add a name to the list: Harry
Please add a name to the list: Ron
Please add a name to the list: Draco
Please add a name to the list: Hermione
Please add a name to the list: Lavender
['Harry', 'Ron', 'Draco', 'Hermione', 'Lavender']
In this activity you are to create two lists, the first list will be a list of names, the second list, will be a list of ages. You are to ask the
how many user how many people are they going to add to the list. This will then inform the loop how many times it needs to
iterate through your code. Your output could look similar to the one below:
Sample Output:
How many people do you want to add to the list: 3
Please add the name of person 1: Harry
How old is Harry: 23
64
Removing Items from Lists
In this section, we are going to look at how we remove items from a list. This can be achieved by using two different list methods, the
method and the method.
Output:
Removing an Item from List
['Cat', 'Dog', 'Rabbit', 'Fish', 'Hamster']
['Cat', 'Dog', 'Rabbit', 'Hamster']
As you can see from both the code and output, that when using the method, that we can remove items from the list if they
are present. If we try to remove an item from the list that does not exist, then you will get an error from your code. If you try to remove a
duplicated item in the list, such as "Draco" in our example, it ill remove the closest index first.
Output:
['Dog', 'Cat', 'Hamster', 'Rabbit', 'Fish', 'Mouse']
['Dog', 'Cat', 'Hamster', 'Rabbit', 'Fish']
['Dog', 'Cat', 'Rabbit', 'Fish']
['Dog', 'Cat', 'Fish']
Our List
Index 0 1 2 3 4 5
65
List Methods
We have so far looked at a range of different programs that demonstrate how to use lists. As part of this we have used a methods that allow
us to take some action with us list, for example to add and remove items. In this section we will cover the different methods that can be used
with lists, that have not previously been covered over the last few pages.
st methods
append() Adds an element to the end of the list Like some of the li
sed, the
extend() Adds all elements of a list to another list you have already u
syntax is the same:
insert() Insert item in list at a defined index
remove() Removes an item from a list
yList. me th od(), however
m
pop() Removes and returns an element at the given index
e of th ese will ta ke more
clear() Removes all items from a list som
t.
index() Returns the index of the first matched item than one argumen
count() Returns the count of the number of items passed as an argument
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
copy() Returns a shallow copy of the list
Output:
['Dog', 'Cat', 'Fish', 'Hamster', 'Rabbit']
[]
Output:
['Dog', 'Cat', 'Fish', 'Hamster', 'Cat']
Fish is at index: 2
Cat is at index: 1
2nd Cat is at index: 4
Hamster is at index: 3
arameters
Unless any range p
e index ()
have been given, th
the index
method will return
alue o f the first duplicated
v
entry it finds.
Output:
['Dog', 'Cat', 'Fish', 'Hamster', 'Cat']
We can find 2 Cats
We can find 1 Dog
66
Program 71: The reverse() method
The reverse method will take the elements of a list and reverse the order of the elements. Try the below on an existing program, by using
the reserve method.
Output:
['Dog', 'Cat', 'Fish', 'Hamster', 'Cat']
['Cat', 'Hamster', 'Fish', 'Cat', 'Dog']
Output:
[Unsorted List
['Dog', 'Cat', 'Fish', 'Hamster', 'Rabbit']
[5, 99, 50, 83, 37, 46, 28, 11, 24, 71]
ate your
You can always cre
additional
own function with
rtin g criteria . T his can be
so
iev ed by u si ng th e "key =
ach
een the
myFunction" betw
Program 73: The copy() method brackets.
The copy method, can be used to copy the elements of another list. The advantage of using the copy method is
that you can copy the values of list without changing the original list. Create a new file, copy the below code,
save it and run it.
Output:
['Hamster', 'Cat', 'Dog', 'Fish', 'Rabbit', 'Mouse']
You will have noticed that on line 4 you can also copy a list this way, however if you make changes to one list, you will also make the same
changes to your new list, which is why the copy method is good for that reason.
Create a list and store the following values: "Apple", "Samsung", "Sony", "Dell", "HP", "Microsoft, "Acer", "Lenovo". You are to
do the following in the exact order:
Copy the list using the copy method
List 1, to be in reverse alphabetical order. List 2 to be in alphabetical order
Print both lists
Remove the 3rd index from list 1 and remove the 4th index from list 2
Print the index number of the value "Apple" from both lists.
Append the value of "Razor" and "Asus" to list 2
Put list 2 back into alphabetical order
Print list 2
67
Other Things to do With Lists
We have so far looked at a range of different programs that demonstrate how to use lists. As part of this we have used a methods that allow
us to take some action with us list, for example to add and remove items. In this section we will cover the different methods that can be used
with lists, that have not previously been covered over the last few pages.
Output:
The total is: 294.7
Output:
t in ra n d o m fun ction has a
2 of Clubs The buil
f d iffe re n t m eth ods that
number o
be u se d. Y o u an explore these
Program 76: Replacing a Value in a List can
m a n y o th e r m e thods by going
and
We have gone through how to add and remove items from list, but you
w .w 3 sc ho ols .co m /python
to ww
may want to change the value of an item in the list quickly, rather than
remove it and add a new one in. This program shows how this can be
achieved.
Output:
['Cat', 'Puppy', 'Fish']
Anshi goes to the shop and buys ten items, she writes the prices of each item down Sample Output:
and adds up the total value. She does this every time she goes shopping, but Please enter the cost for item 8:£4.20
sometimes she buys more than 10 items. Please enter the cost for item 9:£0.50
Please enter the cost for item 10:£6.67
To help Anshi in the future you are to create a program that allows Anshi to
record the price of each item in the list. After all the items have been added to The total cost of your shopping was: £36.90
the list, you then need to up all the values in the list and print out the total cost.
Your program could look like this:
68
Tuples
A tuple is like a list, however the values inside a tuple can not be changed whilst the programming is running. Like a list, you can use some
of the previous techniques such as slicing and negative indexing.
Output:
('lion', 'Tiger', 'Lynx', 'Leopard', 'Panther')
(1, 2, 3, 4, 5, 6, 7, 8, 9)
(1, 'Two', 3.5, '4', 'Five', 6)
Output:
('lion', 'Tiger', 'Lynx', 'Leopard', 'Panther')
Traceback (most recent call last):
File "main.py", line 5, in <module>
print (cats)
If you try and use a tuple after you have deleted it, you will experience an error NameError: name 'cats' is not defined
message. As you can see from the above code, that line 5 contains an error as the
tuple, no longer exists. You can also use the delete command to delete lists too.
Output:
('Dog', 'Cat', 'Hamster')
Rabbit
('Dog', 'Cat', 'Hamster', 'Rabbit', 'Mouse', 'Bird')
('Hamster', 'Rabbit', 'Mouse', 'Bird')
('Bird', 'Mouse', 'Rabbit', 'Hamster', 'Cat', 'Dog')
Output:
('Hamster', 'Rabbit', 'Bird', 'Cat', 'Dog', 'Fish')
69
Dictionaries
In this section we are going to look at dictionaries. Like a list a dictionary is an unordered, can be modified and indexed, like a list. A
dictionary is made up keys and values, where the syntax looks like this:
Lets
Output:
{'Item': 'iphone', 'cost': 999.99, 'Model': '11 Pro Max'}
iphone
{1: 'iphone', 2: 999.99, 3: '11 Pro Max'}
iphone
that the
Have you noticed
of brackets ha v e changed
style
ls we are
again, which signa
naries.
dealing with dictio
With the above program, we created a dictionary called which was made up of 3 keys and 3 values. The first part of our
dictionary, which is is the first key, after the colon is our first value, which is . The comma after this signals for the next
key and value.
Our Dictionary
With lists and tuples we use the index number to access the values, however with dictionaries we use the key. When creating our dictionaries
we can call the key what ever we want, but keep them simple so its easier to use them at a later stage.
Create an empty dictionary. In this dictionary you are to store the following pairs of information about a house:
Bedrooms: 4
Bathrooms: 2
Floors: 3
Price: £499,999
Parking: Yes
Once you have created your dictionary, ask the user to enter how many reception rooms the house has and store the value
entered into the dictionary. You should then print out the dictionary to show all the keys and values.
70
Program 83: Removing Elements from a Dictionary
We can remove elements from our dictionary by using the method. By placing the key value inside the brackets, will remove both
the key and value from the dictionary.
As you will have noticed from the program above, on line 7, we an also use the method to remove all items from
our dictionary.
Output:
9-18-27-36-45-54-63-72-81-90-
Output:
What would you like to search:
Name
Age
School
House
Enter Value: House
Does not exist
So far you have learned to create a basic dictionary to store data about a student. Create a dictionary that stores the facts about
the United Kingdom. Your dictionary should contain the following data: Number of Counties, Total Population, Currency, Total
number of MPs (Member of Parliaments), Total cities.
Once you have created this then you need to do a membership test to see if the value is present, if it is then you are to print the
data, rather than just staying that the data exists.
71
2D Lists
The lists we have created so far in Python have been simple lists that are also known as one dimensional lists. These lists have a range of
different elements. However it is possible to put a series of lists inside a list, these are known as two dimensional lists or 2D lists. In this
section we are going to look at how we create a 2D lists and how we can use indivdual elements of each list.
Output:
1
4
9
Our 2D List
Indices 0 1 2
Index 0 1 2 3
Index 1 4 5 6 The best way to understand how a 2D list works, is to think of it like a table.
Each list inside our is like a row in a table. Each element of that
list is like a column. Use the example table to left which demonstrates how the
Index 2 7 8 9
2D list we created in the above program works.
Index 3 0
Output:
['Harry', 'Potter', 18, 'Gryffindor', 'Seeker']
['Draco', 'Malfoy', 18, 'Slytherin', 'Seeker']
['Cedric', 'Diggory', 18, 'Hufflepuff', 'Seeker']
72
Code it Yourself - Activity 44
Create a program that prints out a seating plan for a cinema. The seating plan should be created using a 2D list. Your output could
look like the below example:
Sample Output:
ABCD
1111
2222
3333
Output:
['Hamster', 'cat', 'Dog', 'Rabbit']
['Hamster', 'cat', 'Dog']
['Dolphin', 'Shark', 'Fish', 'Whale']
['Dolphin', 'Shark', 'Whale']
['Dolphin', 'Shark', 'Crab', 'Whale']
Using the same list from program 88, you are to create a program that uses the following list methods.
append()
remove()
count()
reverse()
copy()
extend()
sort()
You are to use at least each method once, but you must ensure that you make edits to each of the lists included.
73
Code it Yourself - Activity 42
A sales company wants to keep track of the amount of sales that each staff member makes across each region. In the table below
the company has provided you with the most recent sales data for each person and region in GBP(£).
Create the following using a 2D list showing the sales each person has made in the different geogrpahical regions:
Your program should display the above table and do the following:
Display the total sale figures for each person across all regions
Kelly has made another sale of £2520 in the South region, update the table to reflect this and reprint the table.
Display the total sales by each region.
74
End of Chapter Review
(Lists, Tuples & Dictionaries )
You have now reached the end of the fifth chapter. Below are some questions that you should go ahead and answer. Check the answers with
you peers and teacher.
3. Looking at the above program, what is the purpose of the code? What is the output?
75
6. What does the sort() do to a list?
7. If I want to remove a value from a list, what python list function could I use?
8b. If I sorted the list into alphabetical order, what index position would the value "Harry" be stored in?
8c. What Python list function could I use to delete the entire list?
11b. What would you need to do to make the loop execute 10 times?
76
6 Functions and Sorting & Searching Algorithms
78 Defining Functions
79 Arguments
81 Returning Values
83 The Lambda Function
84 Recursion
86 Finishing with Functions
87 Sorting Algorithms
90 Searching Algorithms
92 End of Chapter Quiz
This program, we are going to create a function that contains a single print command. We are then going to call the function to function.
Create a new program, copy the below code, save it and run it.
Output:
Hello Everyone
Line 2, we created our function using the keyword , which means define. We have then named our function and
used two parentheses at the end our functions name.
On line 6, we then call our function to run the code that it contains. In Like a loop and a conditional
this case it will run the print command that we coded on line 4. statement the code of a
function is indented. Just
make sure you are careful to
avoid syntax errors.
Program 91: Passing Data
In this program, we are going to pass data to a function. When we pass data to a function we call this an
argument. The function we are going to create is to expect at least one argument. Create a new file, copy the
below code, save it and run it.
Output:
Harry Potter
Lilly Potter
James Potter
Create a program that asks the user to enter their first name and second name as Sample Output:
two separate variables. You should then pass these values over to a function Please enter your first name: Harry
which will concatenate the values into a single print statement. Please enter your second name: Potter
78
Arguments
We have already looked briefly at what an argument is, in this section we are going to explore these at bit further, as these are a really
important part to ensuring our functions work properly.
Output:
Harry Potter 18
Albus Dumbledore 150
Severus Snape 38
When we call our function, the value of is assigned to the argument, is assigned to the
argument and the value is assigned to the age argument.
In Python we can call a function and use its keywords to assign the values in any order. Create a new program, copy the below code, save it
and run it.
Output:
Harry Potter 18
Harry Potter 18
Harry Potter 18
Line 4, uses the default positional approach to assigning values. On line 5, we have used the same keywords that we have used in our
function. Line 6, uses a mixture of positional and keywords to achieve this.
In this program, we have created one function, that is expecting two arguments to be passed to it. However you will notice on line
5, that when we call the function, we are only passing one. Create a new program, copy, the below code, save it and run it.
Output:
Traceback (most recent call last):
File "main.py", line 5, in <module>
myFunction("Harry")
TypeError: myFunction() missing 1 required
positional argument: 'surname'
79
Program 95: Arbitrary Arguments
There will be times when you are defining functions, when you don't exactly know in advanced how many arguments
is going to get passed to it. The issue of not knowing can lead to syntax errors like in the code above. However this can
be resolved by using arbitrary arguments. Create a new program, copy the below code, save it and run it.
Output:
Hello Harry
Hello Ron
Hello Hermione
Hello Draco
In this example we have used an asterisk (*) before our parameter to let Python know that we are not sure how many arguments to expect.
This will prevent us getting a syntax error. But as you may have noticed that we have had to use a loop to iterate through our variable so that
the function will work as expected.
Output:
His name is Harry Potter
His name is Ron Weasley
Output:
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Output:
Animal: Cat
Animal: Dog
Animal: Hamster
Animal: Rat
Create a program that passes a list of numbers over to the function. Once you have passed this list of numbers over to your function
get the function to add up the values of the list and print it out the final result.
80
Returning Values
The functions we have used so far do very little. We can make functions more useful, especially if we can get them to do something and pass
that result over to the main program. Oh wait, we can do this by using the return statement at the very bottom of our function. This section
explores how we can pass data back to the main program.
Output:
Please enter a number: 5
Please enter a number: 6
Sum is 11
3. The value of variable "Sum" is returned and stored in the "total" variable.
In this program. we are going to create a fuel calculator. To do this we are going to create three functions,
one to gather user input, the 2nd to calculate the cost the other to display the costs. To do this we will need
to use several variables which we will need to pass the values into our functions. Create a new program, copy
the below code, save it and run it.
Output:
How long was your journey?: 120
How many MPG does your vehicle do?35
What was the cost of fuel in pence 1.24
The Journey cost you £ 1.91
81
Understanding how the program works
For this challenge we will create a program to be used by a teacher at a start of a lesson to take the register. The program will go through a
class list and for each pupil in the list, will ask the teacher if the pupils is present (y) or absent (n).
The program will then output the total number of students in the class, the number of students present and the number of students who are
absent.
You must use a function to calculate the amount of students who are present and the number who ar absent.
In tis program, we are going to create a single function that takes no arguments, instead we are going to use our function to return
multiples values back to a list that we have created. Create a new program, copy the below code save it and run it.
Output:
['Happy', 'Coding']
82
The Lambda Function
The lambda function, is also known as the anonymous function, the reason being is that it has no name. When we have used functions
before or created our own, we have called a function to use, by using its name. With the lambda function we don't do this, instead we
just used the keyword lambda. The lambda function can take arguments like any other function, however you can only use one
expression with this function.
Output:
10
HarryPotter
Please enter a number to add: 20
Please enter a number to add: 30
result of function: 50
Output:
[4, 6, 8, 12]
The map() function in Python takes in a function and a list.The function is called with all the items in the list and a new
list is returned which contains items returned by that function for each item. Here is an example use of map() function to
double all the items in a list.
Output:
[2, 10, 8, 12, 16, 22, 6, 24]
Using the lambda function, create a program that prints out the base 2 number system. Your output should look like this:
Sample Output:
[1, 2, 4, 8, 16, 32, 64, 128 ]
83
Recursion
Recursion is the process of defining something in terms of itself. A physical world example would be to place two parallel
mirrors facing each other. Any object in between them would be reflected recursively. In programming, recursion is how
we solve problems where we need to implement a solution to smaller instances of the same problem. To do this we use
recursion, which is essentially a user defined function that calls it self. All the functions you have created and used to date
have been called (used) when you need them. You achieved this by using .
Output:
Please enter a number: 5
The factorial of 5 is 120
Fibonacci Sequence
Output:
How many terms? 10
Fibonacci sequence:
0,1,1,2,3,5,8,13,21,34
84
Program 106: The Fibonacci Sequence (With Recursion)
In this program, we are going to use recursion to achieve the same result as the previous program. You will notice by looking at
the belo code that we have managed to reduce the amount of lines it has taken us to achieve the same result.
Output:
How many terms? 10
Fibonacci sequence:
0,1,1,2,3,5,8,13,21,34
Now you have seen an example of the Fibonacci sequence, you will have noticed that this example does not use a function. You are
to recreate the Fibonacci sequence using a single function. If it helps you can redesign the code, if you think you can shorten the
program.
Advantages Disadvantages
Code can look cleaner and simpler Hard to follow the flow of the program
Recursion can be easier to use than nested statement Hard to debug errors
85
Finishing with Functions
We are coming to the end of our topic on functions. So far you have you created functions, passed arguments to functions and
returned a range of different values. This section just covers some useful things you need to know as well as some good programs
to have handy.
Output:
Please enter the size of the grid (max 20): 5
_____
|_|_|_|_|_|
|_|_|_|_|_|
|_|_|_|_|_|
|_|_|_|_|_|
|_|_|_|_|_|
Credit to www.101computing.net
Code it Yourself - Activity 48
A school timetable is displayed as a 2D table consisting of 5 rows (for each day of the week) and 5 columns (number of lessons in a day). Such
a table can be stored in a computer program using a 2-dimensional list
Each value of a 2D list can then be accessed by proving two indices: the row number and the column number as displayed on the picture
below:
86
Sorting Algorithms
A sorting algorithm can be used to arrange a list or an array of numbers/ values into the intended order. For example if you want
to put a list of mixed up integers into ascending order, this is where a sorting algorithm can be used. However there are lots of
different sorting algorithms that can be used to achieve this, some better than others. In this section we will cover the Bubble
sort, merge sort, Insertion sort.
Output:
[1, 2, 8, 9, 11, 15, 16, 24]
87
The Merge Sort
The merge sort is another sorting algorithm that is known for using the divide and conquer technique. The algorithm
works by taking a list of numbers and then splitting the list in half. It then will split each smaller list again, and will repeat
the process until every value has been separated. Th algorithm then will compare pairs of different elements of the list,
which are then ordered and then combined. The process will repeat until the list is sorted.
5 2 3 8 6 1 4 7
Step 2 - Split the list again, keep
going until each element has
5 2 3 8 6 1 4 7 been seperated.
Output:
Splitting [5, 2, 8, 3, 6, 1, 4, 7]
Splitting [5, 2, 8, 3]
Splitting [5, 2]
Splitting [5]
Merging [5]
Splitting [2]
Merging [2]
Merging [2, 5]
Splitting [8, 3]
Splitting [8]
Merging [8]
Splitting [3]
Merging [3]
Merging [3, 8]
Merging [2, 3, 5, 8]
Splitting [6, 1, 4, 7]
Splitting [6, 1]
Splitting [6]
Merging [6]
Splitting [1]
Merging [1]
Merging [1, 6]
Splitting [4, 7]
Splitting [4]
Merging [4]
Splitting [7]
Merging [7]
Merging [4, 7]
Merging [1, 4, 6, 7]
Merging [1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
88
The Insertation Sort
The insertion sort is one of the most simplest sorting algorithms, in fact its so simple humans use it when they are sorting
data. The insertion sort works by taking each item in the list one by one and moving it into the correct postion. Using the
first value of an unsorted list as the starting point.
Step 1: Our Starting point, will be 5 as this is our first value in the list
5 2 8 3 6 1 4 7
and is now sorted.
Step 2: We can now move onto examining the next value in our list,
5 2 8 3 6 1 4 7
which in this case is 2. As 2 is smaller than 5, we now move the 2 into
the correct position. The value 2 is now in our sorted position.
2 5 8 3 6 1 4 7
Step 3: We now move onto the next value, which is 8 and sort this
2 5 8 3 6 1 4 7 into the correct position
Step 4: We now move onto the next value, which is 3 and sort this
2 3 5 8 6 1 4 7 into the correct position
Step 5: We now move onto the next value, which is 6 and sort this
2 3 5 6 8 1 4 7 into the correct position
Step 6: We now move onto the next value, which is 1 and sort this
1 2 3 5 6 8 4 7
into the correct position
Step 7: We now move onto the next value, which is 4 and sort this
1 2 3 4 5 6 8 7
into the correct position
Step 8: We now move onto the last value, which is 7, and sort this
1 2 3 4 5 6 7 8
into the correct position. Our list is now sorted.
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
In this program we have created a function that called which is our insertion sort. We have created our
list of values on line 13 and on line 14, we then send this our insertion sort function to sort the numbers as shown in the example
below.
89
Searching Algorithms
There are instances where we will need to find a specific piece of data in a data set. To do this we need to use a searching
algorithm, which in this case will allow us to search a list of values to find what we are looking for. There are two main searching
algorithms that you need to know, which are the Binary search and the Linear search.
Find the middle number, to do this take the length of the list and divide
1 2 3 4 5 6 7 8
it by 2. In this case (8 +1) / 2 = 4.5, so we need to start at position 5.
Discard the second half of the list as we know (so does the computer)
1 2 3 4
that 2 is not equal to or greater than 5.
Now we need to find the middle number again in our shorter list, which
1 2 3 4
is now 4 in length, so (4+1) /2 = 2.5, so we need to start at position 3.
Discard the second half of the list again as 2 is not equal to or greater
1 2 3 4
than 3.
Now we need to find the middle number again of our even shorter list,
1 2
which is now 2 in length. so (2+1)/2 - 1.5, so start at position 2.
1 2 As the value of 2(What we are searching for) is equal too the value of 2
in our list, we have now found our number.
Output:
True
90
The Linear Search
The linear search is a simple searching algorithm that can be used on an unordered list. The linear search will check each item in
the list until it finds the correct item or it can't find it at all. Compared to the Binary search, the linear search is not as efficient
and ideally should be used for smaller lists. The algorithm works in the following way:
1. Look at the first item in the list, unordered or ordered.
2. If this is the item you are looking for, you found it, stop the search
3. If not then look at the next item
4. Repeat steps 2 an 3 until you find the lthe item or have searched the whole list.
5 2 8 3 6 1 4 7 Is 6 equal to 6? Yes it is, we found what we are looking for. End Search
Output:
Element found at index: 4
Taking the above program, can you make it better by doing the following:
1. Get the user to input the value to be searched
2. Generate a random list of values by using the random function
3. Print out the value that you are looking for to the screen along with the index number.
91
End of Chapter Review
(Functions and Searching and Sorting Algorithms)
You have now reached the end of the fifth chapter. Below are some questions that you should go ahead and answer. Check the answers with
you peers and teacher.
1. What is the purpose of a function? Explain how does a Function with parameter passing work?
2. What is the about of the below code? what is the reason for the output?
3. What is the difference between a system function and a user defined function?
4b. How many passes through the algorithm will this program do?
92