Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Programming Guide (1)

This document is a beginner's guide to programming in Python, designed for KS3 and KS4 Computer Science students. It covers essential topics such as variables, data types, conditional statements, loops, and functions, along with practical coding exercises. The guide emphasizes the importance of practice, offers resources for learning, and encourages students to engage with the programming community.

Uploaded by

jogeswaran
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Programming Guide (1)

This document is a beginner's guide to programming in Python, designed for KS3 and KS4 Computer Science students. It covers essential topics such as variables, data types, conditional statements, loops, and functions, along with practical coding exercises. The guide emphasizes the importance of practice, offers resources for learning, and encourages students to engage with the programming community.

Uploaded by

jogeswaran
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

Designed for KS3 &

Written in KS4 Computer Science


Python 3.x

CODING
FOR
BEGINNERS
USING

Version 1.0

print("I <3 Coding ")

Programming
Champion

Clear instructions
and easy to follow
Python Essentials
Key Words

def True print elif False return break

for input else if or while except

and range none continue pass try lambda

Input and Output Text


Print a Message Single Quoted

Store a string Double Quoted

Store a number Multi-line

Print a variable
Concatenated Strings

Length of a String

Conditional Logic
Convert String to an Integer
Decide to run a block
Equal too?

decide between two blocks


Not equal too? String Manipulation
Convert to Uppercase

Less than?
Convert to Lowercase

Greater than?
Decide between many blocks 1st letter of each word to uppercase

Less than or equal too?


Count Characters in a String

Greater than or equal too?


Replace a Character or String

Delete a Character or String


Count from 1 to 10
Repeating a Block
Repeat Block 5 times
Count from 10 to 1

Functions
Count from 10 to 1 Creating a function
Repeat while true

Count down 2 at a time Calling a function


Contents
1 Getting Started with Python
6 About This Guide
7 Computer Programming & Python
8 Online Development Environments
9 Installing Python
10 The Interpreter
11 Interpreter vs Compiler
12 Writing your First Program
13 Annotating your Code
14 The Separator and End Parameter
15 End of Chapter Quiz

2 Variables and Data Types


18 Data Types & Variables
19 Creating Variables
21 Getting User Input
22 Variable Arithmetic
25 Casting Variables
26 Comparing Variable Values
27 Logical Operators
28 The ASCII Table
30 End of Chapter Quiz

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

6 Functions, Sorting and 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 Review

7 Glossary of Terms
1 Getting Started with Python

6 About This Guide


7 Computer Programming & Python
8 Online Development Envrionments
9 Installing Python
10 The Interpreter
11 Interpreter vs Compiler
12 Writing your First Program
13 Annotating your Code
14 The Separator and End Parameter
15 End of Chapter Quiz

Welcome to Python! In this chapter you


will learn the very basics of Python, from
installing it on your computer to creating
simple programs. Let the fun begin!
About This Guide?
This guide has been created especially for KS3 and KS4 Computer Science students with a simple yet fun approach to programming in
Python. While this guide will be really useful, there are thousands upon thousands of resources that are freely available on the internet
and you are encouraged to use these too to help broaden your knowledge. Before you get started, you will need to think about which
environment you are going to use when coding. This guide covers both an online development environment or some software you can
install on your computer. What ever setting you choose to use, the code in this guide will work with both online and offline software.

What to look out for


Your Programming Friends
In this guide you are not alone, you have a number of friends that are throughout the guide to give you some key information and tips.
Make sure you read them, as this will help you with your programming challenges and to understand the programs you are working on.

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.

Track Your Progress


At the back of this guide you will find an area to record your progress as you develop a range of different python programs for this
guide. You can tick of your confidence level too, so that you can remind yourself to do some further development in this area.

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:

Mobile Apps Desktop Apps

Web Apps AI / Machine Learning

Hacking Automation

Data Analysis Testing

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

1 To Get started, go to www.repl.it

2 Click on the button "Start Coding"

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.

Once downloaded launch the Python installer on your computer.

3 Click "Add Python 3.8 to PATH" option

Don't forget you


can install this on
macOS and Linux
too!

4 Click the "Customize Installation" option

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.

7 Click on "Install" and let the installer work its magic.

8 Well, done Python is now installed on your computer.

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.

The Python (Command Line)


From the Start Menu, type in "Python", you will see a few options. Click the option that looks like this:
Once you click this, the below screen will appear:

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 IDLE (The Python GUI)


From the Start Menu, type in Python and select "IDLE Python", which looks like this

Once opened, you will open the Python Shell.

IDLE stands for


Integrated
Development
Environment

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.

Mu Visual Studio Code PyCharm Atom

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 Object Code Interpreter

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.

Compiler Object Code Executor

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:

The Interpreter The Compiler

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.

Only needed the once, as the compiled code is stored in


Needed every time you run the program.
an executable file.

Will return a list of errors Will return the first error

Python, BASIC, Perl, Lua Java, C, C++, C#, Swift, Rust

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.

Have you noticed


that .py file has
automatically been
added in for you?

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.

Did you know that you can use single quotation


marks and double quotation marks
interchangeably. For example you could have
done it like this instead:
print('Hello World!')

Well Done! You have created your first program

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.

Program 2: Annotating your code


Below is a Python program that shows you how to use comments. Create a new file called “comments” and
copy the below program, save and run the code.

The interpreter will read your code line


by line, it will never jump segments of
code unless a conditional statement is
present. This method is known as
sequence and forms one of the key
characteristics of programming

Output:

Hello, welcome back to Python

Code It Yourself - Activity 1

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.

What level are you?


Novice Level – You will refer to the previous python code that we have covered so far
Adept Level – You will not need to refer to the previous python programs and use a single line comment
Master Level - You will not need to refer to the previous python programs and use both annotation types

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


The end parameter is used to append any string at the end of the output of the print statement in python. By default the print
function ends with a newline, but what do you do if you want to use multiple print statements that all print out on the same line? This
is where the end parameter will come and save the day.

Program 3: The end Parameter


Create a new python file and type in the below code. Save it and run it. What did you notice?
Between the
Output: quotation marks, we
Hello just added a space,
World! but you can add
Hello World! anything you want.
Go and give it ago

The end parameter joined the "Hello" and "World!" together into one single output statement in the console screen.

Code It Yourself - Activity 2

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

The Separator Parameter


when you print out multiple arguments using the print function in python, by default they will place a space automatically between
each one, these are known as the soft space feature. There will be occasions when you are coding that you will not want this in your
code, so the separator parameter can help with this. In this program we are going to call/ use the print function you have come to
know so far.

Program 4: The sep Parameter


Create a new file and type in the below code. Save it and run it. An argument is a value that
has been given to a function
when its called.
For example print("A", "B",
"C") has 3 arguments, as the
function is calling 3 different
values.

Output:
ABC
A-B-C
A-B-C!

Code It Yourself - Activity 3

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?

3. Below is some simple code, can you identify the errors?


Don't forget to look
back at your own
programs for help!

4. What is the purpose of a comment?

5. What is the purpose of the sep="---" in the below code? What is the output of the below code?

6. What is an escape string?

16
2 Variables and Data Types

16 Data Types & Variables


17 Creating Variables
19 Getting User Input
20 Variable Arithmetic
23 Casting Variables
24 Comparing Variable Values
25 Logical Operators
26 The ASCII Table
28 End of Chapter Quiz
Data Types & Variables
Variables are a way of storing data in the main computer memory so that it can be retrieved for use at a later stage. Only one piece of
data can be held in a variable at any one time and they are stored for as long as they are needed, until they are disposed off. Imagine a
calculator, the numbers you input are stored in the calculator until you use the clear button or turn the calculator off, then the values
are gone. Like anything that is considered "Variable" the data stored can be changed during the run time of the program, however there
is an exception to this which will be covered later.

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.

Examples of Variables names for storing a house number:

houseNumber @house_no house_1no house no

1houseNumber _houseNumber print house_no

Program 5: Creating Variables


Create a new python file and type in the below code. Save it and run it.

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.

Program 6: Changing the values of variables


Create a new python file and type in the below code. Save it and run it.

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.

Try and give your


variables meaningful
names, this will really
help with the
readability of code.

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.

Code It Yourself - Activity 4

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.

Code It Yourself - Activity 5

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.

Program 9: Getting user input


Create a new python file and type in the below code. Save it and run it.

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.

The input function will print a message to the


Whatever the user types, is stored in the
screen asking the user what their name is.
"name" variable

Code It Yourself - Activity 6

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

In this program, you will expected to do the following:


Print all the values captured back out to the console screen
Use comments to explain your code
Use appropriate variable names

You can use previous programs to help you complete this program.

If you want to put a


Its okay to make mistakes, one of new line in using the
the main ways to learn programming end parameter, you
is through trial and error. Use the can use end= '\n'
support of your peers and teachers
to help you if you get stuck.

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:

Operation Operator Example Notes

Addition + 10 + 2= 12

Subtraction - 10 - 2= 10 Will show the answer as a whole number

Multiplication * 10 * 2 = 20

Division / 10 / 2 = 5.0 Shows the answer with a decimal place

Floor Division // 10 // 2 = 5 Shows the answer without a decimal place

Modulo % 10 % 2 = 0 Shows the remainder of a division sum

Exponent ** 10 ** 2 = 100 multiplys the number by itself x times

Program 10: Maths in Python


Create a new python and copy the below code. Save and run it after you have done it to see the results.

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.

lets take an example, we have two variables: Operator Example Equivalent


a=8
b=4 += a += b a=(a+b)
Imagine you want to to add these together and store the
results in a variable. Well we know how to do this already, -= a -= b a=(a-b)
we would just create a 3rd variable called sum and store
*= a *= b a=(a*b)
the result in their or replace the value of a or b.

/= 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)

In this example program, += operator firsts add the value contained


in the variable 'a' to the value contained in the variable 'b'. It then
takes the result of that new value and stores it back in the 'a'
variable. However the original value of 'a' has now been replaced
and is gone from main memory.

Program 13: Peas in a Pod


Create a new python and copy the below code. Save and run it after you have done it to see the results.

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.

Code It Yourself - Activity 7

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.

Program 15: Rounding Up


The round up function can be used to round up numbers. The syntax of the round function has been shown below. Create a new
python program, copy the below code, save it and run it. Try changing some of the maths and decimal places to see different results.

Our number/ The maths How many


Output: variable decimal
0.45 places

Code It Yourself - Activity 8

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

Code It Yourself - Activity 9

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

Code It Yourself - Activity 10

Create a program that converts Celsius to Fahrenheit. The formula to this is:

Temp in Celsius divide by 5, then multiply by 9, then add 32.

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.

Program 16: String Concatenation

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

Why is the output 55 and not 10?

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.

Program 17: Casting Variables


In this program, we are going to our string data type into an integer. We do this by using the this tells the program
to take the user input, and convert it from string to an integer. You can use casting with other data types such as float.

Why don' you go back over


some of the code it yourself
programs and get the user to
Output: input the values instead.
Please enter the first number to add: 5
Please enter the second number to add: 5 Input from user
The sum is 10

Code It Yourself - Activity 11

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.

Greater Than Less Than 15 < 16


The greater than (>) operator will compare both 16 > 15
The less than (<) operator will compare both true
operands and will return true if the first operand true
operands and will return true if the first operand 16 < 15
is greater than the second and false if not. 15 > 16
is less than the second and false if its not. false
false

Greater than or equal to 16 >= 16 Less Than or equal to 15 <= 15


The greater than or equal to will compare both true The less than or equal to will compare both true
operands and return true if the first value is the 15 >= 16 operands and return true if the first value is the 16 <= 15
same or greater than the second. false same or lower than the second. false

Program 18: Comparing Variables


Create a new python and copy the below code. Save and run it Operator What it means

== Equal to (Equality)

!= Not equal to (Inequality)

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

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.

Code It Yourself - Activity 12

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

Use the above code to help you right the program.

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.

You can use a 0 to represent


Program 19: Logic a false value and a 1 to
In this program, we are going to show you how to use these logical operators. represent a true value.
Create a new program, copy the below code and run the program.

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

Our work with logic doesn't end here.


We will revisit this when we go to cover
control statements later in the guide.

Code It Yourself - Activity 13

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]

Program 20: Using ASCII


Creeate a new Python program, copy the below code, save it and run it to see the results.

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 'ö'

Code It Yourself - Activity 14

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.

Your python program, should do the following:


Ask the user to enter the measurements for each room, using the measurements below.
Convert the measurements from feet into meters squared (m2) for each room.
Ask the user to enter a price for the carpet.
Calculate the cost of each room and for the whole flat in total.

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

What level are you?


Novice Level – The program has been attempted and will work according to the specification above. However the code maybe
minimal and slightly disorganised. Annotations will be few or absent throughout the program.
Adept Level – The code is working and some attempts have been made to include more challenging features. Code maybe
inefficiently coded, and is mostly correct.
Master Level - You will have used a variety of different techniques covered above, code will be concise and broken down into
clear components. The program will also be fully and well structured and additional programming techniques may be used
that has not been covered in the guide.

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.

2. Explain what is happening in the below code.

3. What is casting and why is it so important?

4. What is the output of the below code? Explain what is happening.

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

Operator Answer Operator Answer

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?

10. Explain the purpose of the below program.

11. Below are some variable names. Highlight which ones are acceptable and in a different colour highlight the ones that are not
acceptable.

FirstName @firstName first_name first name

1firstname _firstname name first1_name

31
Page left intentionally blank

32
3 Conditional Branching

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

This chapter demonstrates how


conditional expressions are used and
how the path of a python program can
be altered based on conditions. This is
known as selection.
Conditional Statements Explained
So far, everything you have coded has been sequenced based programming, meaning that all your code will execute in the order that its
written. However when creating programs to perform specific tasks, it is common that some form of control structure will be use to alter
the flow of program, so not everything is executed in a sequential manner. This is where we introduce you to your first type of controls
structure: Conditional statements.

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.

What are conditions?


In simple terms a condition is a piece or line of code that will compare two values. It will use operators to to make these
comparisons. Go back to page X to refresh your mind on these.

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:

If condition if code if Harry eats his dinner:


is false print("He Can go out and play")
else:
print("He has to tidy his room")
else code
In this example we are testing our condition, Has Harry eat his dinner? If he has then the
statement becomes true and he can go out and play. If Harry has not eaten his dinner
dinner then the statement has become false and he has to tidy his room.

In this example, the condition is true, as


it is raining. So maybe I should get my
umbrella.

If statements work like real life


decisions. For example, if its raining,
you should bring an umbrella with you.
If its not I will leave it at home.

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

Will check the condition first

Will only go when none of


the conditions have been elif
met.

Will check the condition second

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:

if Harry eats his dinner:


print("He can go out and play")

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.

Program 21: The IF statement


In this program, we are going to create a variable and store the value 71. We will the use the if statement to test the condition. simply put,
if the value of score is over 70 then print the message ("You passed the exam"). Create a new program and copy the below code, run and
save it.

Don't forget to add your colon


(:) to the end of your if
statement, as this shows the start
of the indented block.
Output:
You have passed the exam

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?

Code It Yourself - Activity 16

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.

Program 22: If / Else Statements


In this program, we are going to now add an "else" to the end of our if statement so that we can run a specific code block based on the
value stored in the variable. Create a new python program, copy the below code of either program, save and run it.

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.

If you wanted to compare a


variable to an exact value then
l se ' tells the
The w ord 'e
to take you will need to use the equality
w h ic h p ath
computer ha s not been == operator.
ndit ion
when the co
met.

Code It Yourself - Activity 17

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.

Program 23: else if statements


We are going to adapt the code slightly from the last program and add a few branching elif statements to the program that will be able to
print different results based on the value stored in the score variable. Create a new program, copy the below code, save it and run it.

You don't have to use the else at


the end of your code blocks if
you don't want too, but it might
be a good idea, especially if the
testing of your conditions fail.

Output:
You have passed with a pass grade

Program 24: Creating a Menu


In this program, we have created a small menu system, where the user will be displayed a list of options and entering a number from 1 to 4,
will show which option they have selected. If they enter a value that has not been covered by our elif statement, then the else statement
at the end will print an invalid message. Create a new program, copy the below code, save it and run it.

Output:
Welcome to an example menu
Option 1:
Option 2:
input
Option 3:
Option 4:
Please enter an option: 1
This is option 1

Code It Yourself - Activity 18

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.

Program 25: Creating a Calculator


In this program, we are creating a calculator. however like some of the earlier programs we have created this program, will ask the user to
enter the mathematical operator they would like to use, in order for that some to be carried out. Create this program yourself, copy the
below code, save it and then run it.

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

Code It Yourself - Activity 20

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

Code It Yourself - Activity 21

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

The date is 4th May 2022

Code It Yourself - Activity 22

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

How much is the phone on contract: 43.00


Are there any up front costs?: Yes
How much are these: 200.00
Is this over 24 months? Yes

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

false true if test-expression-1:


IF con 1
statement to be executed if 1 is true.
if test-expression-a:
Statement 3 statement to be executed if a is true.
IF con 2 else:
false true
statement to be executed if a is false.
else:
Statement 2 Statement 1
statement to be executed if 1 is false.
statement to be executed if 1 is false.

In this example, if condition 1 is true, it will then proceed to the next


Statement code block. If condition 2 is true then statement 1 will execute, if its false
after IF the statement true will execute. If condition 1 was false then statement 3
will execute. After the whole conditional statement has finished it will
proceed to the code after the if statement.

Program 26: Nesting Statements


In this program, we are asking the user to enter a number between 1 and 50. If the user enters the number
32, then test test for condition 2, will return a false result.

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

Program 27: Nesting Statements Part 2


In this program, we are using nesting again, but this time we are going to use if statement with elif too so that we
can print out a range of different statements. Create a new Python program, copy the below code. Save it and
run it.

Indentation is not only


important to if statements, but
also important to loops and
functions as well, which we will
cover later in this guide.

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.

Program 28: Using AND


We are going to create a program that asks
a b a AND b AND
the user to enter a y or n value to two
questions using the same example we have The AND operator is used if you want to check if
false false false
used in the table on the right. multiple conditions have been met. For example. If
false true false harry eats his dinner (A) AND does his homework
Create a new python program, copy the (B) he can go out and play.
below code, save it and run it. true false false
Unless both A and B are true, then the statement is
true true true false

Go back and look at page


25, you will can recap over
logic there and how we
have used it in previous
programs.

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

Program 29: Using OR


We are going to use the same code from
a b a OR b OR
program 28, but all we need to do is change
one thing. On line 4, we are going to edit The OR operator is used if you want to check if at
false false false
our code to change the keyword and to or. least one condition has been met. For example. If
This statement will now behave completely false true true Harry eats his dinner (A) OR does his homework (B)
differently. he can go out and play.
true false true
Create a new python program, copy the So we need either A or B to be true, then the
below code, save it and run it. true true true statement will return true.

Have you noticed that if


you use an uppercase 'Y'
that this will effect the
program? Remember when
we looked at ASCII and we
learnt that an uppercase
Output: 'Y' and a lowercase 'y' are
Did Harry do his homework? (y/n) y two different values!
input
Did Harry eat his dinner? (y/n) n
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:

Program 31: Boolean and If Statements


In this program, we are going to create a variable called value and give it the value of false. This will ensure
that the if statement on line 3 will run the command on line 4 asking the user to enter a value between 0 and
20. If the user does this then then the value variable will be assigned a true value so that the last if statement
on line 10 will run. Create a new program, copy the below code, save it and run it.
Take note of how '=' and
'==' are completely
different from each other.
A single equals sign is used
to assign values to
variables. A double equals
sign or equality compares
two values.

Output:
Please enter a number between 0 and 20: 5 input
Your number was 5

Code It Yourself - Activity 23

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.

Your python program, should do the following:


Have a minimum of 5 questions
There should be no more than 4 choices for each question
When the user enters the letter for the choice, it should recognise both the uppercase and lowercase letter
Each correct answer is worth 1 point and you should calculate the score throughout the quiz and at the end.
Use of annotations throughout.
Output is well presented to the user.

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.

5. Which country gifted the statue of liberty to the united states?


a. Germany
b. France
c. England
d. Japan
Answer: A
Sorry that's the incorrect Answer. You have 3 points.

You scored a total of 3 points out of 5. Thats not bad, you could do better next time.

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.

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?

2. What does the term "Nesting" mean?

3. Looking at the above program, what is happening on line 2 and 9.

4.Label the operators below with their correct name:

< >

<= >=

!= ==

5. What is the result of each of the following expressions given the following variable assignments ? (True/ False)
x=4 y=5 z =4

Expression Boolean Expression Expression Boolean Expression

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

6b. What is the output of the program?


True
examScore
>= 93

Output
False "Excellent" 6c. What would the output of the program be if the value of the variable examScore was
set to 85?

End

7. Refer to the code above for question 7.

What would the output be if:

7a. The water temperature was 100C

7b. The water temperature was 0C

7c .The water temperature was 50C

7d. The water temperature was 100.1

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

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

This chapter demonstrates how


loops are used to repeat
segments
of code, based on certain
conditions
Loops and Iteration Uncovered
We have covered quite a bit of Python so far and hopefully your confidence is starting to
grow. We have so much more to learn and discover. At this stage you should be able to
complete a range of different tasks from declaring and initialising variables, to using logic
and writing conditional statements that checks a range of different conditions. In this
section we are going to look at iteration or in other words 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

Condition while (expression):


statement to be executed

If condition If condition while number >10 :


is true is false print("The number is less than 10")

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

for i in range (0,5)


print("This is a loop")
Code Block
This loop is ideal when we know how many times something needs to repeat, for example
if you were to create a program that counted from 1 to 10, this loop would be perfect.

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.

Program 33: Counting Upwards


In this program , we are going to ask the user what number they would like to count up to. On line 3, we have
created a variable which will be used to start our count off. Every pass through the loop the value of one will be
added to our counter, which we have coded online 6. Create a new program, copy the below code, save it and run
it.

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

Code It Yourself - Activity 25

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.

Code It Yourself - Activity 26

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.

Program 35: The Continue Statement


The continue statement can be used to stop the loop repeating that iteration/ pass through and move onto the next statement.
For example you could tell the program to count to 10, but skip over the 3rd iteration. Look at the below program, copy the
code, save it and run it.

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.

Code It Yourself - Activity 27

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.

Program 36: While/ else


In this program we are are going to print the numbers from 4 to 0. Once the loop has printed the last number, it will then
proceed to run the else statement. Look at the below program, copy the code, save it and run it.
Output:
4
3
2
1
0
Loop has now finished

Program 37: While/ Else Part 2


In this program, we are going to ask the user to enter the temperature. While the temperature is equal too or greater than 30, the air
conditioning will turn on and the user will be prompted to enter the temperature again. When the user enters a number lower than 30, the
code block which runs from lines 5 to 10, will have been exhausted and the else block will be executed.

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

Program 38: Random Number Guessing Game


In this program, we have created a guessing game. The computer is going to generate random number between our range of 1 to 10. The user
will keep guessing the number until they get it correct. Copy the code below, and give it a go.

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.

Code It Yourself - Activity 28

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.

Program 39: While with AND


Copy the below code below into a new file, save it and run it. Try putting in different values. What is happening with the program? Is it
working as you would expect?

Output:
Did Harry, complete his homework? (y/n): n
Did Harry eat his dinner? (y/n): n

Did Harry, complete his homework? (y/n): n


Did Harry eat his dinner? (y/n): y
Great, well done Harry you can go and play Xbox

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

true true true


Program 40: While True
In this program, we have corrected the logical errors in program 39, by using the while true approach. The while true means the loop will
execute forever until its told not too. The only way to stop the loop from looping is using the break command. As you can see on line 7, the
break command has been used and this will only execute when the values for dinner and homework equal to a 'y'.

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

Code It Yourself - Activity 29

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

Program 41: While not in


In this program, we have used the "not in" membership as part of our while loop. We are looking for 4 different values; uppercase 'A' or 'P'
or lowercase 'a' or 'p'. If the user types in any other letter than the while loop will evaluate to true and will iterate the code on line 7 again.
We have then used an if and elif statement to execute to split our program up, so when either lowercase or uppercase 'a' or 'p' has been
inserted, the program will run the correct code block. Create a new program and copy the below code, save it and run it.

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.

Code It Yourself - Activity 30

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.

Program 43: The FOR Loop


In this program, we are going to create the simplest for loop we can code. This for loop will use the range function, which returns a
sequence of numbers starting at 0, each pass/iteration of the loop will the number will increment by 1 until, it reaches the specified
number. In this case our number in this program is 4.
for and in are keywords that are 'a' is the name of our variable,
used in python, which is they they you can this what you like.
are blue.

Output:
0
1
2
3

The range() function creates a list of


Every time the loop runs the
numbers. This will create 4 numbers,
value of 'a' will change.
Program 44: For range which starts from 0 by default.

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

Start - Integer starting point to be returned.


Stop - Integer before which the sequence must be returned. The range of range of integers ends at stop -1
Step - Determines the increment or decrement between each integer in the sequence.

Code It Yourself - Activity 31

Create a program that displays the numbers from 10 to 100 in steps of 5.

Program 45: Times Table


Output:
In this example, when using both the for loop with the 11 x 1 = 11
range function, we are able to print our our 11 x 2 = 22
multiplication tables for the eleven's times table. 11 x 3 = 33
u can al s o use the
Yo print
11 x 4 = 44
n c ti on to
range fu bers.
11 x 5 = 55
t iv e n u m
out nega t your
11 x 6 = 66
is ju st se
To do th
11 x 7 = 77
e p a s n egative 11 x 8 = 88
t
stop and s 11 x 9 = 99
numbers. 11 x 10 = 110

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.

Program 46: Breaking Out of the For Loop


In this program, we have used the break command, which we have used inside an if statement. When our variable 'i' is at position 4 or
equals to the value of 3, then our if statement will become true and the break command will be used to exit the loop. Create a new file,
copy the below code, save it and run it.

Remember the continue


command? You can use these to
skip over values in a for loop, just
like the while. However it will
not skip values when the in range
function has been used.
Output:
0
1
2
3
end the loop

Program 47: Prime Number


We have used the break statement in the previous program, but in the below program, we have use both the break command and the else
statement for the for while in the same program. The purpose of the below program is to check if any number entered is a prime now.

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.

Remember a prime number


is only divisible by itself or
one.

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.

Code It Yourself - Activity 32

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

So how does a nested loop work?


How this works is that the first pass of the outer loop will trigger the inner loop. Once we are inside the inner loop it will execute
completely. In the example above, it will print all the times table out for that particular factor, so for the ones time table, this will be
executed right up until the final sum of 1*12 has been printed out. Once this has completed we go back to the outer loop, where the outer
loop has completed its first pass through. The process will start again once both the outer loop and inner loop have been exhausted.

Program 48: Nesting For Loops


An example of using nested for loops can be found in this program. We have nested
one for loop inside another for loop, to print the timetables, up to the 5 times table.

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

Program 49: Nesting For Loops pt 2


This program, we are going to create a pattern by printing out a series of numbers
on each row. The first number iteration of the loop will print 1, then 2 on the next
row, 3 on the row after and son. The count of numbers on each row is equal to the
current row number. Create a new file, copy the below code, save it and run it.
Play around with the values and see what happens.

An ordinary, non nested


loop allows you to repeat a
section of code. Nested
loops allow you to loop
two or more sections of
code. Yay to nesting!!
Output:
1
22
333
4444
55555

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

Program 50: Nesting While Loops


In the program below, we are going to create a program that shows how the while True
loop works, by creating a program that prints the outer loop and the inner loop. Condition 1

Create a new file and copy the code below, save it and the run it.

Condition
2

False False True

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!

Program 51: Nesting While Loops pt 2


In this program, we are going to print the prime numbers up to the value of 30. Now I know we did something similar
in a different program, but this is the great thing about coding, you can approach problems of the same nature, by
implementing different solutions. Copy the below code, save it and run it.

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

Code It Yourself - Activity 33

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.

Any code that is written after the


pass statement will be executed as
normal, we just use the pass
statement to allow us to structure
our program, so we can eventually
come back to it and add some
code.

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.

Program 53: Continue with For


In this program we are going to use the continue statement to skip over a value. In this program, when the loop iterates to the value of
"r", this will be skipped. Create a new program, copy the below code, save it and run it.

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

1. View Film Times


2. View Ticket Prices
3. Book Tickets
Please choose an option from the menu: 3

Sample Output
***********************************
Ticket Bookings
***********************************

You have selected the film: The Imitation Game

Here is the seating Plan:

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

How many adult tickets would you like? : 2


How many children tickets would you like?: 2

You could use the program you created for code it yourself activity 18 and then build from that if helps.

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.

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.

1. What is a loop? Briefly describe what is meant by a nested loop.

2. What is the difference between the while loop and the for loop?

For Question 3, use the above program:

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?

3b. What does do?

58
For question 4 use the above program:

4a. State the output.

4b. What caused the output to display on one line?

4c. What two control structures are used in this code?

For Question 5, 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?

For Question 8, use the above program:

8a. What is the purpose of this program? What is it doing?

8b. Why is the variable been initialised to the value of 0.

8c. Explain what the code it doing online 4.

For Question 9, use the above program:

9a. What does the above program?

9b. What is happening on line 4 of the code?

9c. Explain how this code is using nesting?

60
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
73 End of Chapter Quiz

In this chapter, we will look at


how to use lists to store a range
of different data and then how
we can recall this data for use.
Getting started with Lists
In Python we can group lots of the information together into the same variable, these are known as lists. Lists are very popular due to their
versatility which is why they are very popular amongst programmers. In this section we cover how lists work, how they are created, slicing of
a list, adding or removing elements from them and reorganising them.

Program 55: Creating a List


In this program we are going to create a simple list. Copy the code below, save it and run it.

Output:
[]
['Jaguar', 'Leopard', 'Tiger', 'Lion', 'Puma']
[1, 5, 9, 10, 12]
['Dog', 2.5, '#', 8]

Like a variable, you ca


n name
your list whatever you
want,
as long as you follow
the same
In this program we created a list called , which to start with we gave it no naming rules!
values, which means the list was empty. After we printed out the empty list, we then
added five different values that were stored as strings to our list:

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

These are index numbers. (Python starts counting from 0)

Program 56: Printing Items from list


In this program, we are going to create a new list, called animals and print out each element to the screen. Create a new file, copy the
below code, save it and run it.

Output:
['Cat','Dog', 'Rabbit', 'Fish']
Cat
Dog
Rabbit
Fish

Program 57: Looping Over a List


As you can see we have printed out each index of our list, however to use several print commands to do this is really inefficient.
Only if there was a better way to do this? Oh wait, there is we can use a loop.

Output:
Cat
Dog
Rabbit
Fish

Code it Yourself - Activity 35

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

These are negative index numbers.


Another word for an
item in a
list is also called an el
ement.
-4 -3 -2 -1 Be prepared to use th
ese
words interchangeably
.

0 1 2 3

These are index numbers.

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.

Program 59: Looping Backwards Using Indices


In this program, we are going to do the opposite of program 57 by looping backwards through our list, rather than looping forward. In order
to do this, we will use the for loop with the range function and specify the starting position, the stopping position and the step.

Start at position -1 index

Output:
Stop before position -5 index
Fish
Rabbit
Dog Decrement by 1
Cat

e ca re ful, if y our loop has


B
Don't forget with the stop re ite rati o ns tha n items, you
mo
er the
position that the number used, is will get an error aft
not the number it stops at. Its loop has
statement in your
the one before the stopping been executed.
position that is used.

Code it Yourself - Activity 36

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.

Index Slicing a list in Python


n easily mix
If you wish you ca
ve numbers
length = 7
negative and positi
slices.
when coding your
Black Red Green Blue Pink Yellow Orange

0 1 2 3 4 5 6 7

-7 -6 -5 -4 -3 -2 -1

Program 61: Slicing the List with negative numbers


We can also slice our list using negative indexing. The below program is an example of how this can be achieved. Create a new file, copy
the below code, save it and run it.

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.

Code it Yourself - Activity 37 Sample Output:


120
In this activity we are going to revisit the previous activity which is where you had to 110
print out multiples of 10 in reverse order. In this activity you are to do the same, but 100
also you are to print out the following ranges: 90
From index 10 to index 4 80
From start to index 6 70
From end to index - 6 60
From index -3 to index 50
From index ::-4 to index 40
30
20
10
0

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

Program 62: Adding Items to Lists (Append)


In this program, we are going to create a list, like we have done in previous programs, but we are going to add two items to it. One item will
be added in via the source code, the other will be added in by the user. This will be done, by using the method.
Output:
['Cat', 'Dog', 'Rabbit', 'Fish']
['Cat', 'Dog', 'Rabbit', 'Fish', 'Hamster']
Please add item to the list: Bird
['Cat', 'Dog', 'Rabbit', 'Fish', 'Hamster', 'Bird']

The method will add the item to the


end of the list. In our original list, which has 4
0 1 2 3 4 5 elements, we added a new value called "Hamster"
which is added to index number 4. We then get the
user to enter a value, which is stored in a variable and
Our List then we pass this value into our list, which gets added
to index number 5. The append method only has one
parameter.

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.

The insert method takes


two parameters, the Insert at index number 2 Value to be added to list
index number and the
element that is to be Our List
added to the list.
Index 0 1 2 3 4 5

Original List Cat Dog Rabbit Fish

Add "Hamster" Cat Dog Hamster Rabbit Fish

Add item "Bird" Cat Dog Hamster Bird Rabbit Fish

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.

Sample Output: od takes an


The extend() meth
list, set string
First List: ['Cat', 'Dog', 'Rabbit', 'Fish']
Second List: ['Snake', 'Rat', 'Bird'] iterable, such as a
tc, an yth ing th at is sequential
Merged Lists: ['Cat', 'Dog', 'Rabbit', 'Fish', 'Snake', 'Rat', 'Bird'] e
tha t ca n be u se d to raise
['Cat', 'Dog', 'Rabbit', 'Fish', 'Snake', 'Rat', 'Bird', 'Mouse', 'Hamster'] and
Please enter an animal: Ferret the index.
['Cat', 'Dog', 'Rabbit', 'Fish', 'Snake', 'Rat', 'Bird', 'Mouse', 'Hamster', 'Ferret']

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"

Stored as 'M', 'o', 'u', 's', 'e'

The comma used next to the string value prevents the string from being broken up into separate items.

Program 65: Adding Items with a loop


Using what we have seen in previous programs, we can create an empty list and get our user to enter the elements. We can control the
amount of indices our list has by using a for loop. Look at the below code, create a new file, copy it, save it and run it.

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']

Code it Yourself - Activity 38

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

Please add the name of person 2: Ron


How old is Ron: 31
....
Person 1: Harry and they are aged 23
Person 2: Ron and they are aged 31

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.

Program 66: Removing Items from List


In this program, we are going to use the method, which removes a specified item from the list. Create a new file, copy the
below code, save it and run it.

Output:
Removing an Item from List
['Cat', 'Dog', 'Rabbit', 'Fish', 'Hamster']
['Cat', 'Dog', 'Rabbit', 'Hamster']

Removing a Duplicate Value from List


['Harry', 'Ron', 'Draco', 'Draco', 'Hermione']
['Harry', 'Ron', 'Draco', 'Hermione']

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.

Program 67: Popping Item from List


When we added items to our list using the method we were able to specify the exact index we wanted to place the element. In
this program we can use the method, which allows us to specify which index to remove.

Output:
['Dog', 'Cat', 'Hamster', 'Rabbit', 'Fish', 'Mouse']
['Dog', 'Cat', 'Hamster', 'Rabbit', 'Fish']
['Dog', 'Cat', 'Rabbit', 'Fish']
['Dog', 'Cat', 'Fish']

n a rgu m en t w h ich is passed to


A
When using the method, if you try and use an index that does not p m eth o d is o p tional. If you
po
exists, you will get an error. Make sure that you are careful when selecting
ve th is b la n k, b y default -1
lea
the index number to avoid this. .
index will be used

Our List

Index 0 1 2 3 4 5

Original List Dog Cat Hamster Rabbit Fish Mouse

pop() Dog Cat Hamster Rabbit Fish

pop(2) Dog Cat Rabbit Fish

pop(-2) Dog Cat Fish

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

Program 68: The clear() method


This is a simple program that clears the list of all its elements and values. Create a new file, copy the below
code, save it and run it.

Output:
['Dog', 'Cat', 'Fish', 'Hamster', 'Rabbit']
[]

Program 69: The index() method


In this program, we can use the index method, to return the index number of a particular value. We can do this by either looking at the
whole list, or by looking at a range. See the below program, create a new file, copy the code below, save it and run it.

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.

Program 70: The count() method


The count method can be used to return the number of times a specific value is found in a list. Create a new file, copy the below code,
save it and run it.

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']

Program 72: The sort() method


The sort method can be used to put a list into ascending order (default) or into descending order. If you have a list strings, these by
default will be sorted into alphabetical order, however when referring back to ASCII table, strings with uppercase letters will be sorted
first. Create a new file, copy the below code, save it and run it. Try changing the casing of the the string elements to see how this impacts
the sorting.

Output:
[Unsorted List
['Dog', 'Cat', 'Fish', 'Hamster', 'Rabbit']
[5, 99, 50, 83, 37, 46, 28, 11, 24, 71]

Sorted List in Ascending Order


['Cat', 'Dog', 'Fish', 'Hamster', 'Rabbit']
[5, 11, 24, 28, 37, 46, 50, 71, 83, 99]

Sorted Lis in Descending Order


['Rabbit', 'Hamster', 'Fish', 'Dog', 'Cat']
[99, 83, 71, 50, 46, 37, 28, 24, 11, 5]

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.

Code it Yourself - Activity 39

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.

Program 74: Adding up Values of a List


In this program, we are going to use the built in sum function, that will take all the iterables from a list and return the total value, to store
the value we use a variable. Create a new file, copy the below code, save it and run it.

Output:
The total is: 294.7

era b le is a n o b je c t that can


An it
Program 75: Using Random with Lists te d o v e r. In th e example
be itera
ur it e rab le is th e list, the
You can also use the random function to randomly choose a value from a above, y o
n th a n b e c y c led through
list of given values. In the program below, we have created a random card values ca
generator that will select a random value from each list and join them til all it e m s h a v e been traversed
un
together at the end. Create a new program, copy the below code, save it
(gone through).
and run it.

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']

Code it Yourself - Activity 40

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.

Program 77: Tuples


This program, we have created 3 different tuples, that store a range of different
values. Create a new program, copy the below code, save it and run it.
ave yo u n o tic e d that all of the
H
are in
elements of a tuple
nth ese s. H o w e ve r, these are
pare
n al, it is still a d v ised to use
optio
ractice.
them as its good p

Output:
('lion', 'Tiger', 'Lynx', 'Leopard', 'Panther')
(1, 2, 3, 4, 5, 6, 7, 8, 9)
(1, 'Two', 3.5, '4', 'Five', 6)

Program 78: Deleting a Tuple


As mentioned, you cant edit your tuple or change any of the elements, but you can delete the entire tuple using the keyword
del. See the below program.

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.

Program 79: Slicing Tuples


Like lists, tuples can be sliced in the exact same way. In the program below we will create a tuple and slice it in different ways. Create a new
program, copy the below code, save it and run it.

Output:
('Dog', 'Cat', 'Hamster')
Rabbit
('Dog', 'Cat', 'Hamster', 'Rabbit', 'Mouse', 'Bird')
('Hamster', 'Rabbit', 'Mouse', 'Bird')
('Bird', 'Mouse', 'Rabbit', 'Hamster', 'Cat', 'Dog')

Program 80: Concatenating Tuples


Like strings you can concatenate tuples together. Look at the below code, as you can see the process is identical to that of strings. Create a
new file, copy the below code, save it and run it.

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

Program 81: Getting started with Dictionaries


In this program, we are going to create our first dictionary, create a new file and copy the below code, save it and run it.

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

The name of our Key Value to be added to 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.

Program 82: Adding and Updating Elements


We can also add and update values to our dictionary, in an almost identical style to lists. Look at the below
code, copy it into a new file, save it and run it, to see what happens. Try changing some of the values too.

A Dictionary is mutable. This


means that an item can be
changed after its been
created. An immutable object
Output: like a tuple is not changeable.
{'Name': 'Harry Potter', 'Age': 18, 'School': 'Hogwarts'}
{'Name': 'Harry Potter', 'Age': 17, 'School': 'Hogwarts', 'House': 'Gryffindor'}

Code it Yourself - Activity 41

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.

You can also delete a


dictionary in the same
way that you can delete
a tuple, by using the del
keyword.
Output:
{'Name': 'Harry Potter', 'Age': 18, 'School': 'Hogwarts'}
{'Age': 18, 'School': 'Hogwarts'}
{}

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.

Program 84: Iterating through a Dictionary


In this program, we are going to iterate through the dictionary to print values to the screen. Create a new program and copy the below
code, save it and run it.

Output:
9-18-27-36-45-54-63-72-81-90-

Program 85: Dictionary Membership Tests


Like program 82 we have created a dictionary, where all the data we have stored is about that one student. We can check to see if there is
specific value that we are looking for. Create a new program, copy the below code, save it then run it.

Output:
What would you like to search:
Name
Age
School
House
Enter Value: House
Does not exist

noticed on line 9 that


In this program we created our dictionary and then we asked the user to enter which we took the value of
value we would like them to find to see if it existed or if it didn't existed.
the user input and made
it all into lower case so
that their was no issue
with the IF statement.

Code it Yourself - Activity 43

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.

Program 86: Creating a 2D List


In this program, we are going to create a simple list and a 2D list. The simple list or our one dimensional list is only for illustration purposes
to show the difference between a one dimensional and a two dimensional list. we are then going to create a 2D list, which will contain four
different lists. Using the print command we are then going to print our specific elements of each list. Create a new program, copy the below
code, save it and and run it.

Output:
1
4
9

2D lists are also referred to


as nested lists. When you do
any further reading, you
may hear both of these
terms used interchangeably.

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

Program 87: Creating a 2D List pt2


In this program, we demonstrate how we can create a 2D list called students and in each list inside students we can store some data.
Using a for loop we can then iterate through our list printing out the values of each list. Create a new program, copy the below
code, save it and run it.

Output:
['Harry', 'Potter', 18, 'Gryffindor', 'Seeker']
['Draco', 'Malfoy', 18, 'Slytherin', 'Seeker']
['Cedric', 'Diggory', 18, 'Hufflepuff', 'Seeker']

Python doesn't stop at


2D lists. You can create
multidimensional lists
that are 3D, 4D or go
Our 2D List (Students)
even higher.
Indices 0 1 2 3 4

Index 0 Harry Potter 18 Gryffindor Seeker

Index 1 Draco Malfoy 18 Slytherin Seeker

Index 2 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

Program 88: Creating a User Defined 2D List


You can create a 2D list, where the length of the list has been defined by the user. By asking the user to enter the value of how many
rows and columns into variables, we can then use these values to create a 2D list. We do this by stating the value to be stored in our
list, in this example we have used 0. we then multiply this by the amount of columns to be created and then multiply our columns by
the amount of rows. Create a new program, copy the below code, save it and run it.

Output: Using list methods with 2D lists are


Enter Rows: 5 pretty much the same as 1D lists. You
Eneter Columns: 5
just however need to tell the
[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
program which list you are working
on, by specifying the index number.
Program 89: Editing 2D lists
Like with single dimensional lists, we can edit our 2D lists by using the list methods that we have used in
previous programs. In the below program, we are going to show how to use the pop() and insert method()
to edit the values stored in our 2D lists. Create a new program, copy the below code, save it and run it.

Output:
['Hamster', 'cat', 'Dog', 'Rabbit']
['Hamster', 'cat', 'Dog']
['Dolphin', 'Shark', 'Fish', 'Whale']
['Dolphin', 'Shark', 'Whale']
['Dolphin', 'Shark', 'Crab', 'Whale']

Code it Yourself - Activity 45

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:

North East South West

John 14984 3290 21429 5740

Kelly 6550 12312 4631 34578

Harry 1457 952 7400 500

Rachel 11124 16457 6451 1467

Mohammed 9478 15392 9874 4678

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.

1. What is the difference between a list, tuple and dictionary?

2. What is meant by the term immutable and mutable?

3. Looking at the above program, what is the purpose of the code? What is the output?

4. What is the difference between indexing and slicing a list?

5. Which of these is the correct code for creating a list of names?

A. nameList = John, Harry, Jesse, John, Harry, Harry

B. nameList = ("John", "Harry", "Jesse", "John", "Harry", "Harry")

C. nameList = ["John", "Harry", "Jesse", "John", "Harry", "Harry"]

D. nameList = [John, Harry, Jesse, John, Harry, Harry]

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?

Below is an example of an unsorted list:

Unsorted List of names

Harry Ron Craig Andrew Goyle Oliver Draco

8a. What value is stored at index number 3?

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?

9. What is the difference between insert() and append()?

10. What is the difference between clear() and remove()?

For question 11, use the below code:

11a. Explain what this code does

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

In this chapter, we will look at


how to define our own functions
to carry out a particular task.
You will also learn how to send
values between functions.
Defining Functions
A function is dedicated block of reusable code that performs a particular action when it is called. You have been using a range of built in
functions with python since the very beginning. However, you can create your own functions that perform the actions you desire. In this
chapter we are going to look at writing our own functions and how we pass data between them.

Program 90: My First Function

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

We have created a function which takes one parameter, this


fname is our parameter parameter is called fname. Inside our function calls on lines 4,5
and 6 we have placed our arguments inside the parenthesises.
Its these arguments which are then sent to the function to be
processed.

This is the data to be sent


to the function known as
an argument A function call is invoking or
using the function. If a
all a fu n c tion you function is not called, then it
c
When you n y d a ta of the doesn't get used.
ol and a
pass contr u nc tio n . A fter
that f
program to x ec u t ed, the
on h a s e
the functi d b a c k to the
retur n e
control is
a in cod e block.
m

Code it Yourself - Activity 43

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

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

Program 92: Passing Multiple Arguments


It is possible to pass more than one argument to a function, in fact you can pass up to 255 arguments in a single function. These can
be a mixture of different data types too. Create a new program, copy the below code, save it and run it.

Output:
Harry Potter 18
Albus Dumbledore 150
Severus Snape 38

Program 93: Keyword Arguments


When we call a function and pass some values to the function, these values get assigned to assigned to arguments according to their position.
Look at the below example:

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.

Program 94: Invalid Argument

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'

The same syntax error can


Its obvious from looking at the code above, that the program will not run as we have a
occur when we try and pass
syntax error. This is due to the fact the function is expecting two arguments and we
more arguments than what is
are only giving it one.
expected.

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.

Program 95: Arbitrary Keyword Arguments


In this program we can use arbitrary keyword arguments when we don't know how many arguments will be passed to the function. To do this
we use a double asterisk (**), before the argument. The function then can access a dictionary of arguments, which it will use accordingly.
Create a new program, copy the below code, save it and run it.

Output:
His name is Harry Potter
His name is Ron Weasley

Program 96: Default Parameter Value


When suing functions if we need to, we can set our parameters to a default value, then if we need to pass an argument to our function, this
will replace the default value that we have used. Create a new program, copy the below code, save it and run it.

Output:
I am from Sweden
I am from India
I am from Norway
I am from Brazil

When you pass a list to the


Program 97: Passing a List of Arguments function, it will still be a list.
It is also possible to pass a list of arguments to a function as well. By creating a list in
Remember your list can use a
a normal way, we can then pass that list as a single argument. Create a new mixture of different data types.
program, copy the below code, save it and run it.

Output:
Animal: Cat
Animal: Dog
Animal: Hamster
Animal: Rat

Code it Yourself - Activity 44

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.

Program 98: Returning a value


In this program, we are going to create a simple addition program that uses a function. However the difference being we will return the
result of the addition back to the main program, once the function has processed the addition. Create a new program, copy the below, save
it and run it.

Output:
Please enter a number: 5
Please enter a number: 6
Sum is 11

So how does this process work?

1.The variable "num1" is passed to the parameter "number1".

2. The variable "num2" is passed to the parameter "number2".


3 2

3. The value of variable "Sum" is returned and stored in the "total" variable.

1 Did you know there are two main type


of functions. Built in functions, which
you have been using from the very start
of this guide. The other, are user
defined, which are the functions we are
creating in this chapter.
Program 99: Fuel Calculator

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

1.To start, we create 3 variables called:


1
which the values stored in this variables will be
initialised from the three variables:

Which will be returned from our


These values will be stored in the order in which
they returned.

2.The variables we created at the start:


2
will be passed through into our next function

The variable inside our calculateCost() function

3 will be returned back to the main program and


stored in the variable

3. The variable will now be passed to the


function

which will now be displayed to the user.

Code it Yourself - Activity 45

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.

Program 100: Returning Multiple Values

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.

You can also return your values as a list,


tuple and a dictionary. Just refer back
to the previous section to make sure
you use the right syntax.

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.

Program 101: The lambda Function


In this program, we are going to demonstrate the use of the lambda of function. Create a new program, copy the below code
save it and run it.

Output:
10
HarryPotter
Please enter a number to add: 20
Please enter a number to add: 30
result of function: 50

The lambda function is


normally used with the
In this program on line 2, is our function. x is the filter() and map()
argument and and is the expression that gets evaluated and returned function. Which is
by the lambda function. On line 3 we pass over our argument and covered below.
the value of 5, which is then sent to the lambda function.

Program 102: Filter() and lambda


The filter() function in Python takes in a function and a list as arguments.The function is called with all the items in the
list and a new list is returned which contains items for which the function evaluates to True.Here is an example use of
filter() function to filter out only even numbers from a list. Create a new program, copy the below code, save it and run
it.

Output:
[4, 6, 8, 12]

Program 103: map() and lambda

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]

Code it Yourself - Activity 46

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 .

Program 104: The Recursive Function


In this program, we are going to use recursion to work out the factorial of a number that has been entered by a user . This
will then display the final value in the output window. Create a new program, copy the below code, save it and run it.

Output:
Please enter a number: 5
The factorial of 5 is 120

Program 105: The Fibonacci Sequence (Without Recursion)


In this program, we are going to create the famous Fibonacci sequence. The idea of the Fibonacci Sequence is fairly simple. You
take the first two numbers (0 and 1) and add them together to calculate the next digit – in this case, 1. This is followed by adding
the new value with the previous – in this case, 1 and 1 to make 2, and so on. The image below lists the first set of numbers in the
sequence.

Fibonacci Sequence

1 1 2 3 5 8 13 21 34 55 89 144 233 ...

1+1 = 2 3+5 = 8 13 + 21 = 34 55 + 89 = 144

1+2 = 3 5+8 = 13 21+ 34 =55 89 + 144 = 233

2+3 = 5 8 + 13 =21 34 +55 = 89 144 + 233 = 377

Output:
How many terms? 10
Fibonacci sequence:
0,1,1,2,3,5,8,13,21,34

When we take any two


successive (one after the other)
Fibonacci Numbers, their ratio is
very close to the Golden Ratio
"φ" which is approximately
1.618034...

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

Code it Yourself - Activity 47

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.

Recursion - Should you use it?

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

Complex tasks can be broken down into similar sub problems,


Uses more memory and time
making the final solution easier

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.

Program 107: Creating a Grid


In this program, we are going to create a grid of squares. To do this, we are going to define three functions. One to get the grid size from
the user, one to create the grid, the other to display the grid. In this program, we have set a maximum size of 20 by 20. However, if you
wish you can remove this. Create a new program, copy the below code, save it and run it.

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:

Write a program that:


When completing this program, you can
1. Prints the timetable out
write it without the use off a function. Do
2. Asks the user to input a day of the week (e.g. Tuesday)
this first, then write a function that does
3. Asks the user to input a period of the day (between 1 and 5) (e.g. 2)
the same thing.
4. Retrieve and outputs the lesson on that day and period (e.g. Spanish)

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.

The Bubble Sort


The bubble sort is one of the simplest sorting algorithms. It works by comparing each element of a list/array to its adjacent
element and swapping them if they are not in the intended order. It is known as the bubble sort, as every pass through the
sort, the elements move up in the correct order, like bubbles rising to the surface.

The Bubble Sort (Into Ascending Order)

Initial 5 3 8 4 6 Our starting list of unsorted numbers

Step 1 5 3 8 4 6 Compare the 1st and 2nd Item of the list.


As 5 is bigger than 3, a swap is needed.

3 5 8 4 6 Compare the 2nd and 3rd Item of the list,


Step 2
as 5 is not bigger than 8, no swap is needed

Compare the 3rd and 4th Item of the list,


Step 3 3 5 8 4 6
as 8 is bigger than 4, a swap is needed

Compare the 4th and 5th Item of the list,


Step 4 3 5 4 8 6 as 8 is bigger than 6, a swap is needed

Repeat steps 1-5 until no more swaps are


Initial 3 5 4 6 8
needed.

Program 108: The Bubble Sort


In the below program, we are going to create a bubble sort algorithm. Copy the below code, save it and run it.

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.

The Merge Sort (Into ascending order)

5 2 8 3 6 1 4 7 Our unsorted list of numbers

5 2 3 8 6 1 4 7 Step 1 - Split the list in half

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.

Step 4 - Compare each pair then


swap the elements into the
correct order. The comparisons
2 5 3 8 1 go from left to right. Group pairs
6 4 7
together

Step 5 - Compare the elements of


the new pars going from left to
2 3 5 8 1 4 6 7 right and swap if needed. Repeat
process until the numbers are
1 2 3 4 5 6 7 8 sorted.

Program 109: The Merge Sort


In the below program, we are going to create the merge sort algorithm. Copy the below code, save it and run it.

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.

The Insertion Sort (Into ascending order)

Our unsorted list of numbers

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.

Program 110: The Insertion Sort


In the below program, we are going to create the insertion sort algorithm. Copy the below code, save it and run it.

The insertion sort is great for


working on small lists and is and
uses no additional computer
memory as it uses the original
list. However it's not as fast as
the merge sort and gets slower
with each additional element
that is in the list.

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.

The Binary Search


In order for the Binary search to work, the list must be sorted first. The binary search works like this:
Step 1: Find the middle value of the list
Step 2: If this is the value we are looking for, then the search is terminated.
Step 3: If not then the value is compared to the middle item in this list. If the value comes before the middle item, then the
second half of the list is ignored and we only work with the first half.
Step 4: we will now have a list that is half the size and, we will now repeat steps 1 and 3, we will keep applying this process until
we have found the value we are looking for.

Binary Search (Find number 2)

1 2 3 4 5 6 7 8 Our sorted list of numbers

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.

Program 111: Binary Search


In the below program, we are going to create a program that's searches for the value of 2. Copy the below code, save it and run it.

Remember computers need


to follow instructions,
whilst it's easier for a
human to find the value it's
looking for, computers do
not work like this and need
to follow an algorithm.

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.

Linear Search (Find number 6)

5 2 8 3 6 1 4 7 Our unsorted list of numbers

5 2 8 3 6 1 4 7 Is 5 equal to 6? No it is not so move onto the next item in our list.

5 2 8 3 6 1 4 7 Is 2 equal to 6? No it is not so move onto the next item in our list.

5 2 8 3 6 1 4 7 Is 8 equal to 6? No it is not so move onto the next item in our list.

5 2 8 3 6 1 4 7 Is 3 equal to 6? No it is not so move onto the next item in our 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

Program 112: Linear Search


In this program below we are going to replicate the above example of the linear search. Create a new program, copy the below
code, save it and run it.

While the linear


search is a very simple
searching algorithm,
you should use the
binary search or other
searching algorithms
for larger lists.

Output:
Element found at index: 4

Code it Yourself - Activity 49

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?

4. Answer the questions below about the code provided below

4a. What sorting algorithm is being used above?

4b. How many passes through the algorithm will this program do?

4c. How many swaps in total will be made?

92

You might also like