Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Python for Beginners
Description: The ultimate introduction to Python programming. Over 12 hours of content, including diagrams, exercises and project walkthroughs! Suitable for all levels of ability, even if you have never coded before! This PDF includes a link to the interactive Notion-based version of the course. This course covers: - Getting Python running on your machine - Variables and data types - If statements - For loops and while loops - Data structures (lists, dictionaries, tuples and sets) - Functions - Walkthroughs of coding exercises - Python project suggestions

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Python For Beginners
To access the interactive and most up-to-date version of this course, follow the link at the bottom of this
document
...
It is suitable for all levels of ability and does not
require any prior programming knowledge
...
If you have never programmed before, learning your first
language will introduce you to a new way of logical thinking
...


This course will cover:
Getting Python running on your machine
Variables and data types
If statements
For loops and while loops
Data structures (list, dictionaries, tuples, and sets)
Functions
Walkthroughs of coding exercises
Python project suggestions

You Will Need
This course will contain code and exercises
...
If you prefer, you can skip this step and just read
through the course, but writing code and experimenting is the most effective way to learn programming!

To write and run Python on your machine, you will need:
1
...
There will be instructions to access the terminal later in the course
...

2
...
It is likely that Python is
not installed on your device
...

3
...
Follow the steps below to install one of our
recommended editors
...
As of the
time this course is written, Python 3
...
2 is the latest release, but any version of Python 3 will be suitable for this
course
...
To
open this on Windows, search for 'command prompt' and open the command prompt app
...


Within this console, you can enter commands to try and access Python
...
Try each of the following commands below
...
X
...

python --version
python3 --version
py --version

For example, my system can access Python 3 using the

python --version

command:

Be aware that seeing Python 2
...
X indicates Python 2 is installed and is accessible through the command you
just entered
...

This course will use Python 3, so you can just ignore this Python 2 command and continue checking the other
commands for Python 3
...
X
...


Windows
Python for windows can be downloaded from https://www
...
org/downloads/
When following the install setup, ensure that you select 'Add Python 3
...


Python For Beginners

3

MacOS
Python for MacOS can be downloaded from https://www
...
org/downloads/mac-osx/
Download the installer and follow the instructions
...

On Ubuntu, you can open the terminal and enter

sudo apt-get python3

Alternatively, the Python zip can be downloaded from https://www
...
org/downloads/source/

If following these instructions do not work for you, there many YouTube tutorials that can visually guide you
through installing Python on your machine
...

Alternatively, follow the steps in this detailed tutorial here
...
When you get it working, make a note of whether you entered python ,
python3 or py as this will be the command you use to execute Python programs
...
It
grew and evolved over the years to arrive at Python 3 in 2008, which over the years has grown to become one of
the most popular programming languages
...
All programming languages have strengths and weaknesses, and
circumstances where some would excel whilst others may perform poorly
...

Python is an extremely popular language with a huge community of programmers from all backgrounds
...

Python's user-friendly syntax and vast collection of code libraries makes for a fast speed of development
...

Python has many tools available for data analysis that make it great for applications within scientific
computing and finance
...

Python has many web frameworks that make it a great choice for running web servers
...

Python's good flexibility results in a relatively large use of memory compared to other languages, making
it a bad choice of language when memory is limited, such as embedded devices
...


Interpreted vs Compiled Languages
Python is an interpreted programming language, rather than compiled
...
The language first
scans your code for any errors, and if your code is acceptable, it turns the code file you have written into an
executable
...
An interpreted language on the other hand,
like Python, can be run immediately
...
With interpreted languages, there is no
initial check for errors in your code, which means that often your code will begin running and later fail and exit
once a line of code that contains an error is executed
...


Hello World!
When learning a new programming language, it's traditional for the first program you write to be a program called
'Hello World'
...
The idea behind

Python For Beginners

5

this program is to make something happen using the minimum amount of code necessary, so you can begin to
understand the syntax (the structure and grammar) of the programming language
...
All that is required is the
following code:
print('Hello World!')

Once run, this code displays the phrase 'Hello World!' in your computer's terminal
...


Running Hello World on Your Machine
1
...
I would
recommend creating this folder on your desktop
...
Open text editor
Open your chosen text editor (i
...
Visual Studio Code, Atom, Sublime Text, Notepad++) and open this new
folder within your editor
...
Creating the file
Create a new file by going to 'file' and then 'new file' within your editor
...
py
...
You have now created
a Python script file
...


4
...

On Windows, the terminal is called the 'command prompt'
...

On MacOS/Linux, search for the 'terminal' application on your device
...
py file we have created
...

cd

on Windows

For example, if your project folder is on your Desktop, you could enter:
cd C:\Users\\Desktop\
...


cd C:\

to enter your C drive
...
Then

cd Users

to enter the Users folder within your C drive
...
Then

cd

followed by your username to enter your user folder
...
Then

cd Desktop

We are now in:

C:\Users\

to enter your Desktop folder
...
Then finally cd followed by your project folder name to enter the project folder you created on
your desktop
...

In the File Explorer, If we started in the C drive we could double click the Users folder to move there, then
your username folder, then your Desktop folder, and so on
...

Alternatively, you could take it step-by-step and enter:
1
...
Then

cd home

to enter the home folder within your root folder

We are now in:
3
...
Then

/

cd Desktop

We are now in:
5
...
The directory you enter is case sensitive so make sure
words folders with capitals like Users and Desktop are capitalised
...
If you see the name of your Python script
(helloworld
...

Example on Windows
I have created a folder called "python-for-beginners" on my desktop that holds a file called helloworld
...


dir

We can see the helloworld
...
We can now move on to the next stage below to
execute this Python file
...
Running the file
Finally, we can run the Python program
...
py , py helloworld
...
You should see 'Hello World!' printed to your terminal screen
...
py file
...
Entering

helloworld
...
py

allows

If all three of those command do not work, you either do not have Python installed correctly, or do not have
your system's Python PATH environment variable set up correctly
...

If you do not have Python installed, follow the installation guide above
...

Alternatively, simply run the Python installer again, but ensure that the 'add Python to PATH' is checked
during setup
...
A variable is like a small section of your computer's
memory that you can put a value into to store temporarily while your program is running
...

A variable in Python has:
A name
A value
A data type

To create an integer variable (a variable that holds a whole number), we can write:
my_number = 2

In this example:
the name of the variable is 'my_number'
the value of the variable is 2
the data type of this variable is integer

The

my_number

variable will now hold the value of 2 for the duration of the program, or until it is updated with a

new value
...
It
helps to try and keep your names somewhat meaningful and easy to understand
...

There are a small number of rules to follow when naming a variable
...
This will allow us to later use or modify its value
...
At one point in your code the variable my_number might hold the value
2
...
Its value can vary, hence the name 'variable'
...
In Python, the equals sign does not signify
'equality'
...

This assignment operator

=

assigns a value to a variable strictly right to left
...


The code below would not work, and
variable are the wrong way around
...
The data type of a variable tells Python how big the
section of memory it requires to store a value of that type
...
These are:
Integer (a whole number e
...
, 6)
Float (a number with a decimal part e
...
, 5
...
g
...
This is completely arbitrary, and you could use any name
you like!
To create an integer (whole number) variable, we can set our variable to be any whole number:
x = 23

Integers are useful when trying to represent something that can only be a whole number, such as a person’s age
or a quantity of items
...
3

This can also include values with a decimal part of zero
...
0

Floats are useful when representing things with fractional parts, such as the result of a division or Pi
...
This is known as an empty string (a string with
no characters in it)
...
As long as it is wrapped in inverted commas, it is still considered a
string, not an integer or float
...
They have an identical function
...

x = "hello there!"

x = ""

x = "54"

Strings are useful when representing anything that involves text, such as a person's name
...

The name 'Boolean' is capitalised as it is named after the mathematician George Boole
...
Comments are found in most programming languages and are plain English notes that the
programmer can use to try and explain what their code is doing
...
You could delete comments from your code, and it will work exactly
the same
...
For example:
# This is a comment

You can write comments on a line of their own, or after a piece of code
...
You are therefore unable to write a comment before a piece of code on the same line
...


Multiline Comments
If you want to write a long comment that spans multiple lines, Python can do multi-line comments by containing it
between a pair of triple inverted commas '''
...
Although, the hashtag version is often preferred, the multiline comment is typically reserved to
describe the purpose of a large chunk of code
...
We can do this by writing 'print' and
wrapping the variable name in parenthesis on a line further down
...
py file extension (e
...
, program
...
Then open
your command prompt/terminal and navigate to the folder that this file is within using the cd command, like we
did in Hello World
...
g
...
py) into your computer terminal (whichever works on your device)
...


You can print out any variable in this way, no matter the data type of the variable
...
6
z = 'hi'
print(x)
print(y)
print(z)

# This will print 14
# This will print 36
...
6
hi
Notice that when you print a string, it doesn't print the inverted commas
...
When printed, comma
separated values will be separated by spaces
...
2
print(x, z)
print(x, y, z)
print(x,y,z) # Spaces after each comma aren't required

Once run, this code would print:

hello 43
...
2
hello True 43
...
However, with larger, more complex programs, printing values to the screen is
incredibly powerful as it can give an insight into the current state of your program
...
Without the ability to print the value of variables, it may
be difficult to know what parts of your program is doing!

Modifying a Variable
Once we've made a variable, we can later change the value it holds
...
This means a variable
can be assigned a value of one type, and then given a different value of a completely different type later in the
program
...
Python is much more flexible
...
e
...
The creation of a constant is often achieved by defining the variable using a keyword such as

const


...
All variables can be modified
...
For example, you may have a variable to hold a username and password that
should never need to change throughout the program
...

USERNAME = 'my_username'
PASSWORD = 'password123'

# Never use a password like this!

type()
A nice feature of Python compared to other languages is that it can automatically infer the data type that a
variable should be based entirely on the value we assign it
...
If Python notices a decimal point, it
knows it should be a float
...
Other languages require the programmer to explicitly state the data type they want each
variable to be
...
When a particular section of code wants to use a
variable, there is no absolute guarantee that it is the data type it is expecting
...
This can be done with

type()


...
e
...
Placing a variable within the parenthesis will cause Python to examine the value currently within
that variable and return to us its data type, which we can then assign to a variable
...


Python For Beginners

type(variable)

5

or a string

'hello'

in the parentheses of

) if we didn't want to assign it to a

print()

to print the data type out

15

x = 7

# Create an integer variable x

# Immediately print out the type of variable x
print(type(x))

Once run, the code above would print the same result:


Types are printed out in the format




...
The

only part we are concerned with is the type stated within the inverted commas
...
66
print(type(my_int))
print(type(my_string))
print(type(my_bool))
print(type(my_float))

Once run, we can see it prints each of the four data types: integer, string, Boolean and float:






None
Python has a special keyword

None

languages use words like

or

None

null

to represent a value of nothing/no value
...
The

None

keyword must be capitalised
...


name = 'Bob'
age = None
gender = 'male'
print(name, age, gender)

Once run, the code above would print:

None

Bob None male


...

as a default starting value to indicate that a variable has not yet been assigned a meaningful value
...


The use cases for None vary on the context of a specific variable
...
In these cases, you may want to opt for

None

and assign the variable it's proper value

later in the code
...
If we run this code, we can see

is a type called 'NoneType'
...


REPL
As Python is an interpreted language, when any Python program is run, rather than generating an executable file
like with a compiled language, the Python interpreter immediately begins executing each line of code to
completion before moving on to the next
...
Write a Python code file with the
...

2
...


What is a REPL?
REPL stands for Read-Evaluate-Print Loop
...

The REPL will repeatedly:
1
...
fully execute it
3
...


Using the REPL
If you have Python installed, you can activate the REPL by entering the Python command specific to your
system within the terminal, either:

python

,

python3

or

py


...
To prompt you to
enter code, the REPL will display

>>>


...
Although in this case, we are

following the prompt with a line of Python code that will execute after pressing return instead of an executable
terminal command
...


Python For Beginners

18

It will then immediately display the prompt

>>>

and wait for us to enter more Python code
...

We can enter

print('Hi!')

and it will output

Hi!


...
For example, you could create a variable on one line,
and that variable will be ready to use on any line further down
...


Python For Beginners

19

Following a line of code, e
...
,

print('Hi!')

go back to waiting for more code with the

, you will see the output on the next line
...
Only if a line of code produces an output, like

print('Hello

, would the line below be an output line
...

world!')

To exit the REPL enter:
CTRL + Z followed by Enter on Linux and Windows
or CMD + Z followed by Enter on MacOS
This will bring you back to your original terminal
...
You can quickly experiment and test bits of code that
you don't intend to permanently save
...


Python Code File vs REPL
Python Code File Snippet
print('Hello world!')
x = 20
name = 'Bob'
print(x, name)

Python For Beginners

20

If this file were to be saved with the
...
g
...
py), and then run using the Python
command (e
...
,

python program
...
Each line is
immediately executed, and if a line returns an output will be immediately displayed on the line below
...
py file and executed
...
An operator is a symbol that represents
a mathematical, relational, or logical operation
...


Variables vs Literals
Operators can work on any value
...
We can
10

, and

21


...


print(5 + 10 - 21)

One run, this code will print

-6


...
Below, we can see that
when we enter

y - x

, it outputs

-78

, and when we enter

x + x

, it outputs

200

x = 100
y = 22
print(y - x)
print(x + x)

Python For Beginners

21

Once run, the code above would print:

-78
200

And literals and variables can be both used together with an operator:
x = 50
print(x + 21)

Once run, the code above would print

71


...
Multiple and divide are slightly different from the
average calculator
...
5
5
...


Parenthesis
Like with a calculator, we can use parenthesis to specify the order of execution
...
Doing this can result in a
completely different result
...


More Arithmetic Operators
Exponent
The exponential or power operator is

**


...


print(3 ** 2)
print(2 ** 4)

Once run, the code above would print:

9
16

Integer Division
A special version of the division operator exists called 'integer division' or 'floor division'
...


print(3 // 2)
print(6 // 3)

Once run, the code above would print:

1
2
3 // 2

divides

3

by

2

to get

1
...


Modulus
The modulus operator

%

is one of the trickier operators to understand
...

For example, 11 modulus 3 (or

11 % 3

) first divides 11 by 3
...
66, or 3 remainder 2 (as 3 goes in

to 11 three times before leaving 2 left over)
...

An easy method to find the value of A modulus B is to repeatedly subtract B from A until it cannot fit
anymore
...


11 − 3 = 8
8−3 =5
5−3 =2
print(11 % 3)
print(6 % 2)

Python For Beginners

23

Once run, the code above would print:

2
0

Modulus can also work with float values:
print(2
...
5)
print(3
...
5)

Once run, the code above would print:

0
...
5

Any value of A modulus B where A is less than B is always equal to A
...

print(3 % 10)
print(1 % 2)
print(19 % 22)

Once run, the code above would print:

3
1
19

Modifying a Variable
Now we understand operators, we can learn how to modify a variable
...

x = 20 # Assign variable x an initial value of 20
print(x)
x = x + 100
print(x)
x = x - 1
print(x)

# Adds 100 to x's current value of 20

# Subtracts 1 from x's current value of 120

In the code above, we first set the variable
holding, which is 20
...
We then store 120 into

x

to hold the integer value 20
...
As x is currently holding a value of 20, this is

and replace the value of 20 it used to hold
...
We then do a similar operation and assign
120, we assign x a value of 119
...
As

x

now holds

24

Once run, the code above would print:

20
120
119

The

=

itself is technically an operator, as it performs on operation on variables and values: it assigns the value

on the right to the variable on the left
...

It turns out that modifying the value of a variable in terms of value it currently holds is a common thing to do
when programming
...
These operators include

+=

,

-=

,

*=

and

/=


...
For example, with two strings the addition operator concatenates them together to create a single string
...


If a string is multiplied by an integer X, it will create a new string that is the original string but repeated X number
of times
...
'
repeated_greeting = greeting * 4
print(repeated_greeting)

The code above would print

'Hello
...
Hello
...
'


...
Operators do not just have to be for arithmetic
...


25

Equivalence
The

==

operator checks whether two values are equal in value
...

=

==

or

False


...


==

checks whether the value on the left and the value on the right are equal
...


x = 2
print(x != 2)
print(x != 5)

Once run, the code above would print:

False
True

Inequalities
Inequality operators can be used to check whether values are greater than or less than other values
...


x > y

checks whether

x

is greater than

x < y

checks whether

x

is less than

y

y

x >= y

checks whether

x

is greater than or equal to

x <= y

checks whether

x

is less than or equal to

Python For Beginners

y

y

26

x = 10
y = 50
print(x < 10)
print(x <= 10)
print(y > x)

Once run, the code above would print:

False
True
True

Logical Operators
Logical operators can combine multiple conditional statements
...
These

operators are slightly different to all the previous operators we've seen, as instead of comparing two values they
compare two conditions to create a new, larger condition
...


When executing the code above:
1
...
The right-hand side
3
...


True and True

(1 != 2)

is evaluated to
is evaluated to

True
True

True and True

is evaluated to True

We can skip the evaluation of the conditions on the left and right and simply replace them with

True

and

False

values to easily see the result of all combinations
...


Or
The

or

operator is like

becomes

True

and

except that if either the right or left side or both evaluate to

True

, the entire condition


...


Not
The

not

not True

operator is slightly different
...

becomes

False

, and

not False

becomes

True


...


Python For Beginners

28

w
x
y
z

=
=
=
=

not True
(2 == 10) and (5 <= 100)
not (x or w)
(15 > 50) or y

What would be assigned to each of the variables

w

,

x

,

y

,

z

?

True

or

False

?

Answer
Variable

w

is

False

Variable

x

is

False

Variable

y

is

True

Variable

z

is

True

Variable

w

:

not True

Variable

x

equals

False

:

(2 == 10) and (5 <= 100)

Variable

y

z

False and True

which equals

False

:

not (x or w)

Variable

equals

equals

not (False or False)

which equals

not False

which equals

True

:

(15 > 50) or y

equals

False or True

which equals

True

Programming In Python
Control Structures
Programming languages use various 'control structures' to control the flow of execution
...
Control structures allows the code to jump
and divert to different areas of the code based on whether a given condition is satisfied
...
These are common
programming structures and found within most languages
...
Loops allow you to repeatedly execute the same chunk
of code until a condition becomes satisfied
...
They can divert the flow of execution and stop Python from simply
executing line-after-line sequentially
...

If statements create a structure such that a given block of code is only executed if a given condition is
evaluated to

True


...
If this condition is found to be True , the block of code below condition will be executed
...
This means that each line of the code
block should start with four spaces, but two spaces would also work
...

if condition:
# Execute this indented block of code
#
...


Your text editor can often be configured to insert the correct indentation with a single click of the tab key
...
To
avoid having to repeatedly press the spacebar four times to create indentation, text editors for programming
are often configured to just produce four spaces instead of a tab character when the tab key is pressed
...
If you are
getting indentation errors when your indentation appears to be consistent and correct, you may have
pressed the tab character and actually inserted a tab character, so check the tab key configuration within
your text editors to ensure it only produces spaces
...
Python will check this condition and evaluate it to either

the screen only if this condition is found to be
The program initially assigns the

month

and

True

day

True

or

'December'

False

AND whether

day

is equal to


...


variables with the value

when this program is run the condition will be evaluated to

True

'December'

and

25


...


It only makes sense for the condition within an if statement to contain a variable, as this allows for dynamic
behaviour because the evaluation of the condition can change if the value of the variable changes
...


Python For Beginners

30

If the condition within an if statement does not depend on a variable, only static literal values, it means its
outcome can never change
...


if True:
print('A')
if 3 == 2:
print('B')
if 8 < 10:
print('C')
if False:
print('D')

Whenever this program is run, it will always print:

A
C
A will always be printed, B will never be printed, and C will always be printed
...
Therefore, in this
example, it would be more sensible to use the code below, without the if statements, as it would have exactly the
same functionality
...
When Python sees the colon
at the end of the first line of an if statement, it informs Python that the following indented code 'belongs' to the
if statement, meaning that the indented block of code should only be executed if the condition is
if 5 < 3:
print('A')
print('B')
print('C')

True


...


if 5 < 3:
print('A') # Belongs to the if statement
print('B') # Belongs to the if statement
print('C') # Does not belong to the if statement

Once run, this program will print C as the print('C') line of code is not indented and is therefore outside of the
if statement code block
...


31

Below is some code
...

if 5 < 3:
print('A') # Belongs to the if statement
print('B') # Does not belong to the if statement
print('C') # Will cause an error - unexpectedly indented

Once you run this code, it will produce an error
...
Here we see that line
5 ( print('C') ) caused the error due to an 'unexpected indent'
...

1
...
Python then sees that

5 < 3

is

True

print('A')


...


3
...

4
...


If

print('C')

was not indented, the code would work correctly
...
To do this we can use the

else

keyword followed by a colon
...

if condition:
# Do something
#
...


Python For Beginners

32

For example:
month = 'April'
day = 3
if (month == 'December') and (day == 25):
print('Merry Christmas!')
print('And a Happy New Year!')
else:
print('It\'s not Christmas')

In the program above there are only two possibilities, either:
1
...
OR 'It's not Christmas' will be printed to the screen
This time the

month

variable is assigned the value

Therefore, the condition

'April'

and the

(month == 'December') and (day == 25)

It\'s

variable is assigned the value

is now evaluated to

the block of code that prints a Christmas greeting and instead print
Note: The backslash within

day

False

'It's not Christmas'

3


...
The program will skip

...


To avoid Python interpreting the apostrophe ' within

It's

include a backslash immediately before the apostrophe

as the termination of the string, we must

\'


...
e
...

Similarly, if you opted to use the equally valid quotation marks (instead of inverted commas) for your strings
(e
...


"hello"

) and wanted to include a quotation mark within your string, you could use

\"


...
The first backslash will act as an escape character, and stop the second backslash from

acting as another escape character

Elif
We can further extend an if statement using the elif keyword and stands for 'else if'
...


if condition1:
# Execute this
#
...

elif condition3:
# Execute this
#
...


block of code

if condition1 was False but condition2 is True

if condition1 and condition2 were False but condition3 is True

if all conditions were False

# Continue with the rest of the program
#
...


33

The if statement will work down the list of conditions until it finds the first condition that is

True


...
After it has finished executing this block it will exit the if
statement entirely, without checking any further conditions
...
If all conditions

were found to be

False

, and if an

statement will be executed
...


For example:
number_of_guests = 8
table_booked = False
if table_booked:
print('Welcome, let me show you to your table')
elif number_of_guests > 6:
print('We don\'t have a large table available tonight, you should have booked!')
else:
print('You haven\'t booked, but I think we could still squeeze you in')

Once run, the code above would print:

We don't have a large table available tonight, you should have booked!
The if statement in the code above will first check whether

table_booked

is

True


...
If not, it will move on to the elif statement and check whether the number_of_guests is
too large
...
If not, the else
show you to your table'

statement will be executed and the program will print
in'

'You haven't booked, but I think we could still squeeze you


...


age = 19
if age < 1:
print('You are a baby')
elif 1 <= age < 3:
print('You are a toddler')
elif 3 <= age < 13:
print('You are a child')
elif 13 <= age < 20:
print('You are a teenager')
elif age > 18:
print('You are an adult')
print('The if statement has been exited')

Once run, the code above would print:

You are a teenager
The if statement has been exited
The first line of code sets

age

this is the first condition to be

to be
True

19

, it prints the code block

the if statement and moves on to print

Python For Beginners


...
As


...
As it exits the if statement, it does not

34

get chance to review the condition

age > 18

, even though this is

True


...


Exercise - Odd or Even
You are given a variable that can hold a number
...

If it is odd, your program should print 'odd'
...


Copy the code below containing the number variable to use
...


Hint 1
We can check whether a value is even using the modulus operator
Remember:

A % B

%


...


Hint 2
If

number % 2

number

If

number % 2

number

is equal to 0, it means

A

can be cleanly divided by 2, with no remainder left over
...

is equal to 1, it means if

A

is divided by 2, it leaves a remainder of 1 left over
...


Answer
With the example number of 503, your program should print 'odd', but it should adapt when this number is
changed
...


If

number % 2

results in 0,

number

divides cleanly by 2, and therefore it is even
...

We can use an if statement to check whether number is even first, and if not, we can use an
to check whether it is odd
...
Checking whether the number is odd first works equally well
...
If the first condition ( number
be False , it must be 1 instead
...


The code below will produce exactly the same result as in answer 1, but it removes the need for the
computer unnecessarily computing and evaluating

number % 2 == 1

to either

True

or

False


...

number = 503
if number % 2 == 1:
print('odd')
else:
print('even')

Exercise - Leap Year
A year is a leap year if:
it is perfectly divisible by 4, 100 and 400
...

Build a program to that can check whether a given year is a leap year and print the result (e
...
, '2016 is a
leap year' or '2016 is not a leap year')

Copy the code below containing the year to check
...


Hint 1
We can check to see if the year is perfectly divisible using the modulus operator

%


...


Answer
There are many different solutions to this problem
...


Answer 1
We could check the two conditions in turn, but this is a bit repetitive, and the computer may waste time
evaluating

(year % 4) == 0

and

(year % 100) == 0

two separate times
...
It's good practise to try and avoid redundant computations
when you can
...
It's

good practise to try and avoid repeating your code, as it can make your program more difficult to understand
...
There is almost always a way to eliminate duplicate
lines and make your code more concise
...
But the computer still has to

unnecessarily evaluate

(year % 4) == 0

and

(year % 100) == 0

twice
...

year = 2016
if ((year % 4) == 0 and (year % 100) == 0 and (year % 400) == 0) or ((year % 4) == 0 and (not (year % 100) == 0)):
# Perfectly divisible by 4, 100 and 400
print(year, 'is a leap year')
else:
print(year, 'is not a leap year')

Python For Beginners

37

Answer 3
The final solution is arguably more concise, and the computer only must compute and evaluate each
condition at most once
...
The main
problem with this solution is it can also be a bit difficult to read
...

str

- means 'the string data type'

int

- means 'the integer data type'

float
bool

- means 'the float data type'
- means 'the Boolean data type'

These keywords are useful as they allow us to check whether the data type of a variable is equal to a
particular one of these types
...
We can then use the

to check whether this data type is equal to one of the keywords listed above
...
932
True

# Check and print whether each
print(type(a) == int) # Would
print(type(b) == int) # Would
print(type(c) == int) # Would
print(type(d) == int) # Would

type is the integer data type
print True
print False
print False
print False

# Check and print whether each
print(type(a) == str) # Would
print(type(b) == str) # Would
print(type(c) == str) # Would
print(type(d) == str) # Would

type is the string data type
print False
print True
print False
print False

# Check and print whether each type is
print(type(a) == float) # Would print
print(type(b) == float) # Would print
print(type(c) == float) # Would print
print(type(d) == float) # Would print

Python For Beginners

the float data type
False
False
True
False

38

# Check and print whether
print(type(a) == bool) #
print(type(b) == bool) #
print(type(c) == bool) #
print(type(d) == bool) #

each type is the boolean data type
Would print False
Would print False
Would print False
Would print True

This can be useful in many ways
...
We can change the code we run depending on the data type of
a variable
...
4

# Assign x a float value

if type(x) == int:
print('x is currently holding an integer')
elif type(x) == str:
print('x is currently holding a string')
elif type(x) == float:
print('x is currently holding a float')
elif type(x) == bool:
print('x is currently holding a Boolean')
else:
print('x is not holding an integer, string, float or Boolean')

Once run, the code above would print
x

'x is currently holding a float'

is holding a float value and therefore its data type is

float

, because at the time of the

if

statement,


...
They allow you to create dynamic behaviour and
eliminate repeated sections of code by repeating the same block of code more than one time
...
For loops
2
...
They should be used
when you know exactly how many times you want to repeat a block of code
...
We state the number of times we wish

is an integer number (or variable that holds and integer) that is the number of

times we wish to loop the block of code
...

for variable in range(N):
# Execute this block of code N-number of times
#
...
Is this the first time we are
executing this code? Or the tenth? This is where the 'for loop' variable comes in
...
With each loop, this variable will be assigned the current
loop number
...
This can be confusing at first and will take a while to get used to
...
During the first loop it will hold the value 0, during the second it will hold 1, and so on
...
We can use this variable to

produce different behaviour within the code block depending on the number of times we have looped
...


If we wanted to create a 'for loop' that loops 5 times, we would write:
for i in range(5):
print(i)

This will print:

0
1
2
3
4
The 'for loop' variable

i

takes the values from 0 to 4, but this is still 5 unique values, so the loop has looped 5

times
...
It then prints this value and returns to the top of the 'for loop' to get
incremented by 1
...
This continues
until

i

is no longer less than 5 and it exits the 'for loop' and continues with the rest of the program
...


for i in range(5):
print(i+1)

This will print:

1
2
3
4
5

Starting Value
We can also specify an optional starting value
...


Step
Finally, we can specify an optional

step

value
...

for variable in range(starting_N, ending_N, step):
print(variable)

For example:
for i in range(50, 100, 10):
print(i)

This will print:

50
60
70
80
90

Combining Loops and If Statements
Within the loop, we could use an if statement check the current value of the loop counting variable and
change the behaviour of the code within the loop depending on its value
...
A 'while loop' should be used when you are unable to
explicitly state the number of times you need to loop
...
It will continue to loop until that condition is first found to


...
Just like with

for loop, the indented block of code that follows this is the code to be repeated
...


Using a 'while loop', we could still print the numbers counting to a given value, just like with a for loop
...

i = 0

# Create our own counting variable

while i < 5:
print(i)
i += 1 # Increment our counting variable (the 'while loop' will not do this for us)

Once run, the code above would print:

0
1
2
3
4

Python For Beginners

42

The code below repeatedly doubles the value of
of

x

x

until it has exceeded 100
...


x = 5
while x < 100:
x *= 2
print(x)

Once run, the code above would print:

10
20
40
80
160

If we removed the indent from the print statement, it would no longer be classed as within the loop
...
It would print the final value of

x

after the effects of the loop have

taken place
...


Infinite Loops
'While loops' create the danger of infinite loops
...
Similarly, we could simply use a literal that is completely static and will always
evaluate to True
...


If we save this code with the filename infinite
...


Python For Beginners

43

To get it to stop, you will have to manually end the program
...


Loops Within Loops
Now for something tricky
...

for i in range(3):
for j in range(3):
print(i, j)

Once run, the code above will print:

0, 0
0, 1
0, 2
1, 0
1, 1
1, 2
2, 0

Python For Beginners

44

2, 1
2, 2
The code prints all 9 combinations
...
Once the primary loop is entered,

sets off and begins fully completing the nested loop, cycling through all values of
nested loop and returns to the top of the primary loop where
again, and the nested loop is completed while

i

i

j

i

is assigned 0, and it then

from 0 to 2
...
The process then repeats

is 1
...


Exercise - Multiples of 7
Build a program that prints out the numbers that are a multiple of 7 from 1 to 100, with each number on
its own line
...
We can do this with a for loop as following:
for i in range(1, 100):
# Repeated code
#
...

Hint 2
For a number to be a multiple of 7, it would need to have a remainder of 0 when divided by 7
...


Answer
There are multiple ways of answering this exercise
...


Answer 1
Using a 'for loop', we can take each value in the range 1 to 101, but 101 will not be included
...
We can initially set a variable
n

to 1 and loop while

Python For Beginners

n

is less than 101
...


45

n = 1
# Loop from 1 to 100
while n < 101:
# Print n if it is a multiple of 7
if n % 7 == 0:
print(n)
n += 1 # Increment n for the next loop

Data Structures
As your program begins to grow and become more complex, it becomes infeasible to hold a single value per
variable
...

Data structures are a way of taking multiple values that are related to each other in some way and grouping
them to become accessible through a single variable
...

With our 1000 numbers example, we could create a single data structure, assign it this structure to variable

x

and then place 1000 numeric values into this data structure
...
This will become
easier to understand when we take a look at specific examples of data structures in Python
...
At the same time, it also gives us the
ability to create larger, more complex concepts that we can use during our program
...
We can now hold on to a single variable and access the
gender

all through the

person

name

,

age

and

variable
...


Previously our variables would hold a value that had a data type, such as holding the value 4, which is an
integer
...
These Python data structures (list, dictionaries, tuples, and sets) are in fact data types themselves, just
like integer, float, string or Boolean
...


Lists
Lists (sometimes referred to as arrays) are the first data structure in Python that we will cover
...

A list can:
hold any number of values
add or remove items at any time
hold values of any data type

When you create a Python list, you create a sequence of storage spaces in memory called elements
...
To be able to access a particular space, each of these
spaces are labelled by an numerical index value
...


In the example above, we represent a person as a list of their values
...
At index 0 of the list is the person's
name, at index 1 is their age and their gender is at index 2
...


Python For Beginners

47

Creating a List
Python uses the square brackets

[]

to create a list of items
...
We can create an empty list using an empty set
of square brackets []
...
append() with the value to append
within the parenthesis
...
append('Bob')
print(person)
person
...
append('male')
print(person)

Once run, this code will print:

[]
['Bob']
['Bob', 25]
['Bob', 25, 'male']

person = ['Bob', 25, 'male']
print(type(person))

If we print out the type of

person

, it will display




...


Accessing Elements
Once we have a list containing values, we can access these values by using the index of a specific value
...


colours = ['red', 'blue', 'green']
list_length = len(colours)
print(list_length)

# Assign length value to list_length

# Add two new items to the colours list
colours
...
append('purple')
list_length = len(colours)
print(list_length)

# Assign the new length value to list_length

Once run, the code above will print:

3
5

To access the final element in a list, we would need to know the index of that value
...


Python For Beginners

49

As indices begin at 0, with a list containing three elements, the final element is at index 3
...
Therefore, we can always access the last element of a list by using an index value of len(my_list) - 1
...


Negative Indices
A negative index can be used to access values from the end of the list, starting with -1
...

An index of -2 will access the second to last element in the list
...


person = ['Bob', 25, 'male']
print(person)
print(person[2])
print(person[-1])
person
...
Once another value is appended to

the end of the list, index 2 still accesses
list
...

With list of 3 elements, only indexes between 0 to 2, or -3 to -1 are valid, any higher or lower and you would
run off the end of the list and you would get an error
...

If I save this code as out_of_bounds
...


The error states that the list index is out of range, meaning that 6 is out of the range -3 to 2 and is not a valid
index for any of the value within the list
...

With a list containing 5 elements, we can use a 'for loop', with

range(5)

, to loop 5 times
...
This happens to perfectly match the possible
indices of the list and we can use variable i to access the value at each index from 0 to 4 and immediately print
it out
...

my_list = [10, 20, 30, 40, 50]
for i in range(len(my_list)):
print(my_list[i]) # Print the value at index i

This would produce the same output
...
Rather than using range(N) to give our counting
variable i the value of numbers up to (not including) N, we can replace it with the actual list variable (e
...
,

Python For Beginners

53

my_list

) and instead the counting variable would take the values within the list, one after the other
...

In the example below, we create a for loop variable that we've called
the next value in my_list
...
With each loop this will be assigned

my_list = [10, 20, 30, 40, 50]
# Loop over each value in my_list
# With each loop, assign it to the number variable
for number in my_list:
print(number)

Once run, this code would print:

10
20
30
40
50

Slices
Python allows you to take 'slices' of a list and assign them to a new variable
...
We can create a slice by stating the variable name of your list,
immediately followed by [start_index:end_index] , where start_index and end_index are two integers (or variables
holding an integer), and both are valid indices for the size of the list
...


python_letters = ['p', 'y', 't', 'h', 'o', 'n']
# Create a from index 1 to index 3 (not including index 4)
# Assing this slice to another variable and print it out
my_slice = python_letters[1:4]
print(my_slice)
# Print a slice from index 3 to index 4 (not including 5)
print(python_letters[3:5])
# Print a slice from index 0 to index 5 (not including 6) using variables
start = 0
end = 6
print(python_letters[start:end])

Once run, the code above would print:

['y', 't', 'h']
['h', 'o']
['p', y', 't', 'h', 'o']

Python For Beginners

54

The list

['p', 'y', 't', 'h', 'o', 'n']

, holds 6 strings, with

The first slice ( [1:4] ) does not include the

'o'

The second slice ( [3:5] ) does not include the

'p'

at index 0, and

'n'

at index 5
...

'n'

at the ending index of 5

The final slice ( [0:6] ) does not include the ending index of 6, although this is not a valid index anyway
...

python_letters = ['p', 'y', 't', 'h', 'o', 'n']
# No start index - from the start of the list to the item at index 2
print(python_letters[:3])
# No end index - from the item at index 2 to the end of the list
print(python_letters[2:])
# Leave both values out - a full copy of the entire list
print(python_letters[:])

Once run, the code above would print:

['p', 'y', 't']
['t', 'h', 'o', 'n']
['p', 'y', 't', 'h', 'o', 'n']

A slice will not include the item located at the end index
...

python_letters = ['p', 'y', 't', 'h', 'o', 'n']
# Print an empty list
print(python_letters[3:3])

Python For Beginners

55

Once run, the code above would print:

[]


...

In the example below, we use an index value of 2 to create two different slices
...
This feature allows you to
easily split a list into two lists at a given index
...


keyword, followed by the list to check (or a

variable containing the list to check), will check whether the stated value is currently held within that list
...
For
example,

9 in [3, 6, 9, 12]

would return

True


...


Python For Beginners

56

colours = ['red', 'blue', 'green', 'purple']
orange_not_present = 'orange' not in colours
print(orange_not_present) # Prints True
print('red' not in colours)

# Prints False

print('brown' not in colours)
print(50 not in colours)

# Prints True

# Prints True

Once run, the code above would print:

True
False
True
True

Exercise - Summing Numbers
Take a list of numbers and calculate the sum of all of the values within the list and print this value to the
screen
...

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
# Code to find the sum of the list
#
...

Hint 2
We're going to need a variable to keep track of the sum of the list
...


Answer
The program should print out 210
...


Answer 1
We could use a 'for loop' though each of the possible 20 index values within the list (0-19)
...
Once the
loop has finished, the list_sum variable should contain the sum of all the values within the list
...
With each loop, the value variable will take the next value within the
list
...

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
list_sum = 0
# Iterate over each value in the list
# Each time store it in the variable value
for value in my_list:
# Increase list_sum by this value
list_sum += value
print(list_sum)

Exercise - Find Value
You're given an extensive list of numbers
...
Print 'Yes' if so, otherwise print 'No'
...

numbers = [871,
459,
831,
126,
877,
132,
716,

143,
722,
230,
262,
839,
730,
415,

297,
481,
893,
804,
878,
757,
880,

849,
239,
408,
269,
946,
954,
144,

128,
674,
969,
526,
740,
791,
638,

574,
101,
180,
401,
443,
257,
959,

755,
256,
141,
689,
737,
292,
206,

133,
477,
422,
590,
334,
809,
967,

331,
633,
417,
645,
559,
215,
269,

448,
901,
511,
785,
573,
931,
245,

147,
898,
623,
949,
790,
895,
368,

168,
208,
899,
638,
794,
682,
305]

996,
649,
267,
954,
146,
435,

435,
871,
746,
639,
739,

596,
639,
445,
114,
684,

value_to_check_for = 730
# Check whether 730 is within the numbers list
#
...

Hint 2
Once the loop has finished, we will need to have remembered whether we found the value we were
searching for
...


Python For Beginners

False

before the loop

58

Answer
Your program should print
the most straightforward
...
There are many viable solutions to this problem, but the method below is

value_to_check_for

to be the indicator as to whether we have seen the value we

are searching for
...

If a number is found, we set the value_to_check_for to be True , otherwise value_to_check_for will never
change from being False
...

numbers = [871,
459,
831,
126,
877,
132,
716,

143,
722,
230,
262,
839,
730,
415,

297,
481,
893,
804,
878,
757,
880,

849,
239,
408,
269,
946,
954,
144,

128,
674,
969,
526,
740,
791,
638,

574,
101,
180,
401,
443,
257,
959,

755,
256,
141,
689,
737,
292,
206,

133,
477,
422,
590,
334,
809,
967,

331,
633,
417,
645,
559,
215,
269,

448,
901,
511,
785,
573,
931,
245,

147,
898,
623,
949,
790,
895,
368,

168,
208,
899,
638,
794,
682,
305]

996,
649,
267,
954,
146,
435,

435,
871,
746,
639,
739,

596,
639,
445,
114,
684,

value_to_check_for = 730
# Initially set found_number to False
# If we find the number, we can change this to True
found_number = False
# Loop through each number in the numbers list
for n in numbers:
# Check if the number 'n' is equal to 730
if n == value_to_check_for:
# If so, remember that we've found the number!
found_number = True
# Print the result
if found_number:
print('Yes')
else:
print('No')

List Filter
There may be a situation where there is a certain type of item within a list that you no longer need and want to
remove
...
This would essentially 'filter out' any items that do not meet the
condition
...
We could build a program that loops over each
item in a list, checks whether each item is a certain data type (e
...
, string by checking whether type(item) ==
str

), and remove it if so
...

my_list = ['red', 5
...
0, 'blue']
length_of_list = len(my_list)
# Loop through each index value of my_list

Python For Beginners

59

for i in range(length_of_list):
item = my_list[i] # Get the item in the list at this index
if type(item) == str: # Check if the item is a string
del my_list[i] # Remove the item from the list

However, we run into two problems when removing items this way:
1
...
To close this gap,
Python automatically moves all other following items one space to the left
...
must shift across one space to
become 2, 3, 4, 5
...
This means that during our next loop, our loop counting variable i will be incremented to become 3,
and we would have skipped the next value which is now at index 2
...

2
...
If we have a list of 5 items, and create a loop to check each
index from 0 to 4, if at some point we remove an item, the items to the right will be shifted across one
space to fill the gap created, and the length of the list will decrease by one
...
However, we have already
told the loop we are looping until i has taken the value of 4, and during the final loop, index 4 of the list
will be checked (which no longer exists), which will cause an error
...
This way, we can

have full control over when we choose to increment a loop counting variable
...

Loop backwards through the list (from the largest index to index 0)
...


While Loop:
We can create our own variable

i

and initially set it to 0
...

my_list = ['red', 5
...
0, 'blue']
i = 0
while i < len(my_list)
item = my_list[i] # Get the item in the list at this index

Python For Beginners

61

if type(item) == str: # Check if the item is a string
del my_list[i] # Remove the item from the list
else:
i += 1 # Increment i if we didn't remove the value

Looping Backwards:
It's possible to loop backwards and decrease the loop counting variable by 1 with each loop
...

If we use:
a larger
and a

start

step

value, than

end

value

value of -1

For example:
for i in range(10, 0, -1):
print(i)

The code above would print the values from 10 to 1
...


range(final_index, -1, -1)

, where

final_index

is the last index within the list, we could loop through

each index value in reverse: from the final index value, all the way to 0
...

my_list = ['red', 5
...
0, 'blue']
final_index = len(list) - 1
# Loop backwards through each index value of my_list
for i in range(final_index, -1, -1):
item = my_list[i] # Get the item in the list at this index
if type(item) == str: # Check if the item is a string
del my_list[i] # Remove the item from the list

Circular List
There may be a time where you want to endlessly loop over items in a list
...
For example, your list may be acting as a queue of items to
process, and constantly being updated with new items
...
There are
two ways we may do this:
We could manually check whether the current index is equal to the final index in the list, and if so, reset
it back to 0
...


Python For Beginners

62

Looping through a list this way creates a 'circular' list because it appears as though we have connected the two
ends of the list together, creating a circle
...


Manually Checking the Index
During each loop, we will need to check whether our current index is equal to the final index in the list, and if
so, reset it back to 0
...
We can find the length of the list in Python by using the len()
...


my_list = [23, 62, 55, 22, 1, 46]
index = 0

# Start from index 0

for x in range(100): # Loop 100 times
print(my_list[index])
if index == len(my_list) - 1: # If we are at the end of the list
index = 0 # Reset index back to 0 to begin looping from the start
else:
index += 1 # Otherwise increment to the next index along

Modulus
The modulus operator

%

calculates the remainder when two numbers are divided
...

Notably, X % Y , where X is less than
be equal to 0 with remainder X
...
This is because

3 % 8

equals 3 (because 3 divided by 8 equals 0 remainder 3)

1 % 2

equals 1 (because 1 divided by 2 equals 0 remainder 1)

Python For Beginners

X

divided by

Y

would always

63

Although, as

X

increases, eventually

remainder, and

X % Y

0 % 3

equals 0

1 % 3

equals 1

2 % 3

equals 2

3 % 3

equals 0

X

will become equal to

Y

, meaning

X

divided by

Y

will have no

will equal 0
...
It allows us to use the
value of Y like an upper limit, that when X reaches, the whole equation resets back to 0
...
Then as soon as X reaches this first invalid index value, X % Y
will be equal to 0
...
As the last index of a list is at its length minus 1, this is the
length of the list, or len(list_name)
...


to count through each index 0, 1, 2
...


index % len(my_list)

just equals

index


...


Python For Beginners

65

By assigning the variable that we are using to count through each index ( index ) the value of index
len(my_list) within each loop, we can reset its value back to 0 whenever it runs off the end of the list
...

Until 100 values are printed
...


Dictionaries
Dictionaries are the second type of data structure that we will cover
...

When representing a person using a list, there is nothing explicit that tells us that the value at index 1 represents
their age
...

Dictionaries solve this problem by using unique keys that are associated with a specific value
...
If you enter a key into a dictionary, it will fetch whatever value is
attached to that key and return it to you
...
The key allows us to give a meaningful identification to the
value, rather than just a positional index number
...
It has the keys 'name' , 'age' and
you entered the key 'age' into the dictionary, it would fetch and return you the value of 25
...
If

Creating a Dictionary
Python uses curly braces

{}

to create a dictionary
...
If we have more than one key-value pairs, we separate them by commas, as shown above
...

1
...
We create the

'age'

3
...



...


This code will create the dictionary structure as shown below
...


All keys within a dictionary must be associated with one value
...

person = {'name': 'Bob', 'age': 25, 'gender': 'male', 'age': 37}
print(person)

Once run, this will print

Python For Beginners

{'name': 'Bob', 'age': 37, 'gender': 'male'}


...


Accessing Values
We can access the values within a dictionary using the keys
...
g
...

person = {'name': 'Bob', 'age': 25, 'gender': 'male'}
# Fetch the value associated with 'name'
# and assign it to the person_name variable
person_name = person['name']
print(person_name)
# Immediately print the value associated with the 'age' key
print(person['age'])

Once run, the code above will print:

'Bob'
25

If you attempt to use a key that is not valid for a particular dictionary, it will cause an error
...


'nationality'

key

Inserting Values
We can insert new values into the dictionary using
used within the dictionary
...


This means that, like with lists, we can create an empty dictionary and add items to it later
...


person = {}
print(person)
person['age'] = 25
print(person)
person['name'] = 'Bob'
print(person)
person['gender'] = 'male'
print(person)

Once run, the code above would print:

{}
{'age': 25}
{'age': 25, 'name': 'Bob'}
{'age': 25, 'name': 'Bob', 'gender': 'male'}

Modifying Values
If we attempt to add a new value, but the key used is already within the dictionary, it will modify the value
currently associated with that key
...


For example:
person = {'name': 'Bob', 'age': 25, 'gender': 'male'}

Python For Beginners

70

# Delete the key 'name' and value 'Bob' from the dictionary
del person['name']
print(person)

Once run, the code above would print

{'age': 25, 'gender': 'male'}


...
keys() and
...
keys()

or


...


person = {'name': 'Bob', 'age': 25, 'gender': 'male'}
# Assign the dictionary keys list to a variable
dictionary_keys = person
...
values()
print(dictionary_values)

Once run, the code above would print:

dict_keys(['name', 'age', 'gender'])
dict_values(['Bob', 25, 'male'])

Iterating Over Keys
Converting a dictionaries keys or values into a list format is useful as it gives us the ability to loop over the
values within a list
...

Using


...


person = {'name': 'Bob', 'age': 25, 'gender': 'male'}
# Loop over each key within the person dictionary and print it out
for key in person
...
We could iterate over the keys using
associated value
...
keys()

, and within each loop, we could use each key to access its

71

person = {'name': 'Bob', 'age': 25, 'gender': 'male'}
for key in person
...
We could use


...


person = {'name': 'Bob', 'age': 25, 'gender': 'male'}
for value in person
...
items()
It's quite common to want to access both the key and its associated value within each loop
...
items()
...
items() , we can access both the key and values simultaneously with two
variables separated by comma
...
As usual, variables created for us by a 'for loop' can
be given any name, but to avoid confusion, when looping over a dictionary's
...


person = {'name': 'Bob', 'age': 25, 'gender': 'male'}
for key, value
print('The
print('The
print() #

in person
...

Each key within the dictionary should be a number from 1 to 20, and the value associated with each key
should be the square of the key
...

squares = {}

# A dictionary to hold numbers and their squares

# Code to add squares of 1 to 20
#
...

Hint 2
For each number we can calculate its square
...

Hint 3
We can add values to the dictionary by writing

squares[key] = value


...


Answer 1
When adding an item to the dictionary, we can use each number as a key, and its associated value would
be each number squared
...


# A dictionary to hold numbers and their squares

# Loop through the numbers 1 to 20
for number in range(1, 21):
# Use the number as a key, and its value the number squared
squares[number] = number ** 2
print(squares)

# Print out the completed dictionary

Answer 2
Alternatively, we could simply multiply

Python For Beginners

number

by itself
...
We could just use

range(20)

, to loop from

0 to 19
...
Although, it's possible to make the argument that this code is slightly less clear
...
Each student's
name is used as a key, and their corresponding grades A to F are the values
...

all grades C should actually be a grade B
all grades E should actually be grade D
Write some code to check each grade and correct the erroneous grades
...


Copy and complete the code below containing the grades dictionary to correct
...

# Print the corrected grades
print(grades)

Hint 1
We will need to check each student's grade (the values) in the dictionary, but we will also need to access
each student's name (the keys) so that we can update their grade if we need to
...
keys() in a for loop to access each student's name key
...

Use

grades
...


Answer
Your code should update the grades for Emily, Lily, Leo, James, Matt, Mike, Mo, Oliver and Josh and print
out:
{'Jake': 'B', 'Emily': 'B', 'Ashley': 'A', 'Ben': 'D', 'Mike': 'D', 'Mo': 'D', 'Lily': 'B', 'Noah': 'B', 'Oliver':
'D', 'Leo': 'B', 'Isla': 'B', 'Alfie': 'F', 'Olivia': 'A', 'James': 'B', 'Rose': 'D', 'Lucy': 'B', 'William': 'A',
'Josh': 'D', 'Matt': 'B', 'Jack': 'B'}

Answer 1
We can iterate over each key-value pair using
# Dictionary of students and their grades
grades = {'Jake': 'B', 'Emily': 'C', 'Ashley':
'Mo': 'E', 'Lily': 'C', 'Noah': 'B',
'Isla': 'B', 'Alfie': 'F', 'Olivia':
'Lucy': 'B', 'William': 'A', 'Josh':

grades
...


'A', 'Ben': 'D', 'Mike': 'E',
'Oliver': 'E', 'Leo': 'C',
'A', 'James': 'C', 'Rose': 'D',
'E', 'Matt': 'C', 'Jack': 'B'}

# Loop through each key value pair within the dictionary
for name, grade in grades
...
keys()

, and each time use this key to manually access

its associated value
...
keys():
grade = grades[name]
# Get the grade value associated with this student
if grade == 'C':
grades[name] = 'B'
elif grade == 'E':
grades[name] = 'D'

# Overwrite and correct this value
# Overwrite and correct this value

# Print the corrected grades
print(grades)

Python For Beginners

75

Tuples
Tuples very are similar to lists, except for the fact that they are immutable
...
You cannot add or remove values from a tuple
...


Creating a Tuple
Python uses parenthesis

()

to create a tuple of items
...

person = ('Bob', 25, 'male')
# Attempt to change the age
person[1] = 39

Saving this code as

tuple
...


Although there is nothing to stop you completely replacing a tuple, with another tuple that contains different
values
...


Accessing Values
We can access tuple values in exactly the same way as a list
...

person = ('Bob', 25, 'male')
for value in person:
print(value)

Once run, the code above would print:

Bob
25
male

Slices
Slices of tuples are also the same as lists, except a slice of a tuple results in a new tuple, rather than a list
...


Sets
Sets are another data structure that are similar to lists
...
They are simply a collection of unique values
...
For Python to realise you intend to
create a set, it must contain a series of values separated by commas, (rather than key: value pairs with colons
as with dictionaries)
...
However, the empty curly braces

{}

have

already been chosen to represent an empty dictionary (as dictionaries are generally more commonly used)
...
We can then use
my_numbers = set()


...


# Create an empty set

my_numbers
...
add(15)
my_numbers
...
add(25)
my_numbers
...
As you can see, sets are unordered and the order in

which values are added to the set does not change anything
...

my_numbers = {4, 6, 1, 21, 9, 15, 4, 21, 4}

# Set with duplicates

print(my_numbers)
# Add another duplicate
my_numbers
...


Accessing Values
As sets are unordered, there is no positional indexing system that we can use to access a value
...
Writing

in

will return

True

or

False


...



...
remove() , with the value within the parentheses
...

colours = {'red', 'blue', 'green', 'purple', 'orange'}
print(colours)
colours
...
discard()
We can discard a named value from the set using
...
This works
exactly like
...

Like with lists, Python can check for the presence of a given item is in a set using the in keyword
...

colours = {'red', 'blue', 'green', 'purple', 'orange'}
print(colours)
print('blue' in colours)

# Check whether 'blue' is in colours - True or False

colours
...
pop()
If we want to retrieve and remove a random item from the list, we can use
...
pop() will remove a value from the set and return it to you for you to assign to a variable or print
out
...
pop()
print('The colour we have popped is:', colour)
print(colours)

Once run, the code above would print:

{'blue', 'purple', 'orange', 'red', 'green'}
The colour we have popped is: blue
{'purple', 'orange', 'red', 'green'}

Python For Beginners

80

Iterating Over Values
Just like with lists or tuples, we can loop over the values within a set
...


Intersection

&

The intersection operation will take two sets, A and B, and return a set containing only the values that appear
in both A and B
...


|

The union operation will take two sets, A and B, and return a set containing the values that appear in either A
or B or both
...


-

The different operation will take two sets, A and B, and return a set containing the values within set A, with
all the values that are also in set B removed
...


^

The symmetric difference operation will take two sets, A and B, and return a set containing the elements in set
A or set B but not both
...


Exercise - Selecting a Language
Bob is looking for a programming language to learn
...

Find and print out the set of languages he could learn
...

interpreted = {'Python', 'JavaScript', 'Ruby', 'Maple', 'R'}
compiled = {'C++', 'C', 'Go', 'Rust', 'Haskell', 'Java'}
mathematical = {'Maple', 'R'}
beginner_friendly = {'Python', 'JavaScript', 'Ruby', 'Java', 'R'}
# Code to produce the set of languages Bob could learn
#
...


Hint 2
We can use the different operator

-

to find the result of one set without any elements within the second set
...


82

interpreted = {'Python', 'JavaScript', 'Ruby', 'Maple', 'R'}
compiled = {'C++', 'C', 'Go', 'Rust', 'Haskell', 'Java'}
mathematical = {'Maple', 'R'}
beginner_friendly = {'Python', 'JavaScript', 'Ruby', 'Java', 'R'}
# Create the set of languages that is interpreted and beginner friendly
# and then finally remove any mathematical languages
possible_languages = (interpreted & beginner_friendly) - mathematical
print(possible_languages)

User Interaction
Taking User Input
A Python program can take user input from the keyboard using input()
...

input()

input()

will return any keyboard input back to us for us to assign to a variable and use in our program
...
This prompt should be placed between the
parenthesis within input() , for example input('Please enter your password: ')
...
It will then wait for the user to enter a name followed by the
Enter key
...
We can then use this
string in our program
...

When we run this program, we first see the prompt, suggesting we enter a name, followed a flashing cursor
waiting for our input
...


83

If the user enters a number, unfortunately it will still be returned from

input()

as a string (e
...
,

'23'

)
...

Converting between data types
Python can attempt to convert a value of a data type into another data type
...

To do this you need to write the data type keyword ( int ,
then wrap the value to convert within parentheses
...


can convert a value into a float
...
0

value to variable

x


...


For example,
bool()

,

can convert a value into an integer
...
2)

would assign a string

'150
...


can convert the a value into a Boolean
...

When converting values to a Boolean using
None

,

0

,

0
...


int()


...
Once we convert

Python For Beginners

'23'

'23'

by 3, the multiplication operator ( * ) just repeats the

to an integer, we can then use it as a number
...
23'
float_number = float(float_string)

float()


...
23

Guess the Number
Now we have covered taking user input with

input()

, we can walk through the creation of a simple guessing

game that brings many of the concepts we've just covered together
...


1
...
This would make the number easier to
change if we wanted to try the game with a different number as we would only have to change the value in one
place
...
We should print an introduction to the game to tell the player what the game involves
...
This game will involve doing the same action (allowing the user to guess a number) five times
...

number_to_guess = 8
print('Welcome to Guess the Number!')
print('You have 5 guesses to guess the correct number between 1 and 10')
for i in range(5):
# Allow player to guess a number

4
...
This will allow them to make five
guesses one after the other
...
However, their input will be in the form of a string
...



...
We now need to check the player's guess to see whether they guessed correctly and take an action based on
whether they did
...
If the player has guessed correctly, there is no need for them to continue guessing
...
break can be placed on a line within a loop and if this line is ever reached, the
for loop will exit immediately, no matter how many more times it was expected to loop
...
It will not take another guess input from the player and begin executing the next line of
code below the for loop
...
We could make a final improvement to this game by randomising the number to guess
...
We can generate a random number by importing some code that can
generate a random number for us (more about this later)
...
This will import a function (called
randint ), that somebody else has already written for us
...
We can then call this function and assign whatever random number it

generates to our number_to_guess variable
...
Although, the maximum value is
not included
...

from random import randint

# Import the randint function for us to use

# Generate a random number between 1 and 10 (inclusive)
number_to_guess = randint(1, 11)
print('Welcome to Guess the Number!')
print('You have 5 guesses to guess the correct number between 1 and 10')
for i in range(5):
# Receive the player's guess
players_guess = int(input('Guess a number: '))
# Check the player's guess
if players_guess == number_to_guess:
print('You guessed correctly!')
break # Exit the for loop if we have guessed correctly
else:
print('Incorrect!')

If we save and run it, we can play the game
...


Functions
When building a large program, your code can begin to get complex
...
'Functions' are one of the ways Python allows
us to keep our program easy to maintain
...

Functions are useful as they can remove duplicated blocks of code and they can be reused in your program
any number of times
...
They allow you to package up code based on the
basic function it is designed to have
...
Take any number of optional input values,
2
...
and finally return a result

Defining a Function
We can create a function using the

def

keyword, meaning 'define a function'
...
This can be anything, and
it is just a label that allows us to use the function we will create
...
If they are multiple words long, they should be joined with an underscore character ( _ )
After the function name, we place any input values within parentheses
...
Now, below this first line, any continuous block of
indented code 'belongs' within this function
...


The name of the function is

add_two_numbers

The input values are held within the variables

number1

and

number2

Within the function we add the two input values together and assign the result to the new
Finally, on the last line of the function, we can use the
that uses this function
...


number2

) and variable

So far, we have only defined a function
...
When we run either of the code snippets above, nothing will happen
...


Using a Function
Once we have 'defined' our function, and specified what we want it to do, it will just sit there ready for us to use
...
To use a function in your code,
(called 'calling a function') we write the function name, followed by parentheses
...
For example, add_two_numbers(4, 5) will call the
add_two_numbers

Python For Beginners

function with input values of 4 and 5
...
Python looks at the add_two_numbers function and sees that, to run, it will require two variables to hold its
input values ( number1 and number2 )
2
...
The value within variable

x

is copied into the new variable

number1

4
...
Now the function has been set up, it is ready to execute
6
...
The function reaches the last line and returns the value held within the

result

variable

8
...
Outside of the function, back in the main code where the function was called ( add_two_numbers(x,
function returns the value (the sum of x and y) and it is assigned to the

first_sum

y)

), the

variable

The variable x is completely separate from the variable number1 , and the variable y is completely separate
from the variable number2
...
The variables number1 , number2 and result can only be used
within the add_two_numbers function
...


Essentially, a function is a block of code that we can 'call' at any time and jump to that block of code and begin
executing it
...


Python For Beginners

89

So far, adding two numbers is a fairly straightforward process, and it doesn't make that much sense to package
this code up into a function, as it would be fine to write x + y whenever we needed to add two numbers
...

Using a function to package up a block of code also means that, if we later decide to change how the function
code block works, we only have to modify the program in a single location (the code block within the function)
...
Instead, if we hadn't used a function and had duplicate code scattered across our program,
we would have to make this same change to many places across our entire program, and it's possible we may
even accidentally miss one of these places and create a bug in our code
...
To do this we just leave the parentheses empty
...

Functions do not have to return a result either
...
Doing this would mean we would not need to assign the function to a variable when
we are calling the function, as there will be no result returned for us to assign
...
The function below
simply prints 'Hello!' once it is called
...
Then, whenever we need to convert units,
we can just plug the value into the function we have created, rather than trying to remember the formula
...
54
return cm
def convert_to_inches(cm):
inches = cm / 2
...
0 cm
47
...
Then every time we want to calculate the area of a circle for a new radius, we can simply call the
function we have already written and give it the radius, rather than write out the formula all over again
...
14
area = PI * radius * radius
return area
# Use the function the area of the circle for radius 2, 5 and 7
# and print each of the returned values to screen
print(area_of_circle(2))
print(area_of_circle(5))
print(area_of_circle(7))

Once run, the code above will print:

12
...
5
153
...
We can call this function

is_even

as it checks whether a number is even
...
We can check whether the number is odd or even using an if statement
...

def is_even(number):
if number % 2 == 0:
return True
else:
return False

# Check if number is even

Now, whenever we want to check whether a given number is even, all we have to do is call the

Python For Beginners

is_even

function
...
Currently, function evaluates whether
number % 2 == 0 is True or False
...
If it is False it returns False
...
Therefore, we can completely remove the if statement,
and return number % 2 == 0 itself
...

def is_even(number):
return number % 2 == 0

Is Odd?
We could make a similar function to is_even, but for odd numbers
...

def is_odd(number):
if number % 2 == 1:
return True
else:
return False

# Check if number is odd

Or
def is_odd(number):
return number % 2 == 1

It's possible to use a function within another function
...
All we would need to do is call the is_even function and pass the input number to it and return the
opposite of whatever it returns
...


def is_even(number):
return number % 2 == 0
def is_odd(number):
return not is_even(number)

Python For Beginners

92

numbers = [100, 13, 3, 44, 6]
for number in numbers:
if is_odd(number):
print(number, 'is odd')

Once run, the code above would print:

13 is odd
3 is odd

Email Body
We can make a function that generates and returns a formatted body of an email that can change depending on
the variables we pass in
...

New line character

\n

This example below uses the new line character '\n'
...
Instead, it will cause Python to move to the next line before continuing
to print the remaining text
...


Maximum and Minimum
We can build a function to find and return the maximum or minimum number in a list of numbers
...

Note:

max()

and

min()

are already functions

Finding the maximum and minimum of a list is a common task in programming so max() and min() are
functions already built-in to Python
...
Due to this, the names max and min are already taken, meaning we should avoid
these names for our own functions (or variables) and use alternatives like maximum and minimum
...
8, 52, 16
...
5, 60, 109]
max_value = maximum(my_list)
print(max_value)
print(minimum(my_list))
print(minimum([2, 4, 6, 8, 10, 12]))
print(maximum([1, 3, 5, 7, 9, 11]))

Once run, the code above would print:

109
10
...
In an ideal scenario we would set these values to positive or negative infinity
...
If we were to use the minimum() function with
a list of massive values, these functions may not work correctly
...

Therefore, use of the built-in max() and min() functions should always be preferred, as they do not have this
issue
...
g
...

my_list = [2, 51, 18, 40, 99]
my_tuple = (101, 90, 5, 81, 34)
my_set = {500, 3, 1, 50, 19}
print(maximum(my_list))
print(minimum(my_tuple))
print(maximum(my_set))

Once run, the code above would print:

99
5
500

Libraries
Importing Your Own Files
Another way of organising your code is to split your code across multiple Python files
...

Typically, a Python project will have the main file called main
...
This will be the file that you run using the python
command in the terminal (e
...
, python main
...
This main
...


If we create a Python file called maths_functions
...
py file for us to use
...
py file nice and
clean
...
py

file must be in the same folder as the

main
...


maths_functions
...
py
# It contains a few maths functions for us to call

# Function to compute and return (1 x 2 x 3 x
...
g
...
14
area = PI * radius * radius
return area
def area_of_rectangle(width, height):
area = width * height
return area
def area_of_triangle(base, height):
area = (base * height) / 2
return area

main
...
py file for us to use
from maths_functions import *
#
x
y
z

We can now any of the maths functions within maths_functions
...
py

file, we must use an asterisk ( * ), as

from maths_functions import *

If you only wish to import a particular function (e
...
, area_of_rectangle ) from within the
can explicitly state the name of the function instead, as follows:

maths_function
...
Not only can we import code from the files we have written
ourselves, but it also allows us to download other programmer's Python files and quickly import their functions to
use in our code
...
When we're trying to solve a problem, there no point trying to completely reinvent the wheel when an

Python For Beginners

96

expert has already produced a great solution that you could use
...


import

keyword, without having to manually copy and paste the parts that

A collection of related code files that can be imported and used within a program is called a 'library'
...
Python has libraries for everything from data visualisation
and graphing to image manipulation to libraries that can make web page requests
...
These code files will live somewhere within the directory that Python is installed and
can be easily imported into any program you write
...
csv files

The full list and information about each library can be found here:
The Python Standard Library - Python 3
...
5 documentation
While The Python Language Reference describes the exact syntax and semantics of the Python language, this library reference manual
describes the standard library that is distributed with Python
...

https://docs
...
org/3/library/index
...


import

followed by the

For example:
# Import all of the functions from within the math
...
py library
from random import *
# Code using the math and random libraries
#
...

'pip' is a package manager for Python, and it can be used to fetch and download a specific library onto your
machine for you to use in your code
...
However, you're
highly likely to require pip if you continue to use Python beyond a beginner level
...


Python For Beginners

97

An installation guide to install pip for Windows, MacOS and Linux:
Installation - pip documentation v21
...
2
pip is already installed if you are using Python 2 >=2
...
9 or Python 3 >=3
...
org or if you are working in a Virtual
Environment created by virtualenv or
...

https://pip
...
io/en/stable/installing/

Once you have installed pip, you can install a package by opening your terminal and entering one of the
following (depending on your system):
pip install
pip3 install

Or the Python 3 command for your system ( python ,

py

,

python3

) followed by

-m pip install

Example Programs
Compound Interest
We can build a function to calculate compound interest of an investment over a certain number of years
...

Investing £10,000 at with a 5% interest rate over 3 years:
First year: we make 5% of £10,000 (= £500 interest)
Second year: we make 5% of £10,500 (= £525 interest)
Third year: we make 5% of £11,025 (= £551
...
25

We can calculate the compound interest using the formula:

initial × (1 + rate/100)years
£10, 000 × (1 + 5/100)3 = £11, 576
...


# A function to calculate compound interest using the formula
def compound_interest(initial, rate, years):
new_amount = initial * ((1 + rate / 100) ** years)
interest = new_amount - initial
return interest
# A function to calculate compound interest by repeatedly multiplying by
# the rate for each year
def alternative_compound_interest(initial, rate, years):
new_amount = initial
for i in range(years):
# Multiply by the (1 + the rate as a decimal)
new_amount *= (1 + rate/100)

Python For Beginners

98

interest = new_amount - initial
return interest

# Take user input
initial = input('Enter your initial investment: ')
rate = input('Enter your interest rate: ')
years = input('Enter your the number of years to invest: ')
# Convert each of the string inputs to their correct data types
initial = int(initial)
rate = float(rate)
years = int(years)
# Print the compound interest made from investing £10k at 4
...
We can use this to
make a die
...


random

library can generate a random integer number from between two input

would generate a random integer between 5 and 10 (including both
with an equal probability for all possibilities and assign it to the random_number variable
...
py library
from random import randint
# Define function to roll a random number between 1 and 6
def roll():
number = randint(1, 6)
return number
# Roll a dice 10 times and print the result
for i in range(10):
print(roll())

Word Frequency
We can take a string and build a dictionary that records the frequency that each word within the string is used
...
Just like with lists, we
can use a 'for each' loop on a string
...
For example:
my_string = 'hello'
# Loop through each character in the string
for character in my_string:
print(character)

Once run, the code above would print:

Python For Beginners

99

h
e
l
l
o

If we loop through each character in the string and record each one we find until we see a space character

' '

,

we will be able to extract each word from the string letter-by-letter
...
add the word to the dictionary as a key, with a corresponding value of 1
2
...
lower() # Convert to lowercase
# Update the frequencies dictionary
if word in frequencies
...
We'll
take it one step at a time
...


1
...
This
repetition means we will require some kind of loop
...
If the player guesses a letter correctly, they will not lose a life
...
This means we require a

while

loop
...
If the guess is incorrect, we will need to take 1 off the
lives

variable within the loop
...
Is the guess correct?
We can make a function that analyses the player's guess and can tell us if they have guessed correctly
...
If we find this letter anywhere, we can
immediately return True and exit the function
...

def guess_correct(guess, word_to_guess):
# Loop through each letter in the word to guess
for letter in word_to_guess:
# If this letter matches the letter the player guessed
if guess == letter:
return True # Correct guess -> return True and exit the function
return False # Incorrect guess -> return False and exit the function

As this function will either return
False

True

or

False

, we can use this function within an

if

statement
...


Whole program:
# FUNCTION THAT CHECKS WHETHER A GUESSED LETTER IS WITHIN A WORD
def guess_correct(guess, word_to_guess):
for letter in word_to_guess:
if guess == letter:
return True
return False

# Start the game
word_to_guess = 'Butterfly'
lives = 9
while lives > 0:
guess = input('Guess a letter: ')
# IF GUESS INCORRECT, LOSE A LIFE
if not guess_correct(guess, word_to_guess):
print('Incorrect!')
lives -= 1

Python For Beginners

101

3
...
All the letters they haven't guessed yet should be blank, and only the letters they have guessed should be
displayed
...
What we will do is create a set called previous_guesses that will contain
each of the letters that have been guessed by the player so far
...
Then, every time we want to display the word, we can check each letter in the string and only
print it if it is contained within the set of guessed letters, otherwise we can print a blank character such as
an underscore
...
This function will take the word the player needs to
guess and the set of previous letter guesses
...
If the letter is in the set, it
will print the letter, otherwise it will print an underscore
...
If the player then guesses
an 'e', we will want to print '_ _ _ _ e _ _ _ _'
...


By default, a print statement will secretly finish everything you print with a newline character '\n'
...
This is due to this secret newline character '\n' that the print() automatically includes
...


As we want to display a word using multiple print statements to print each character all on the same line,
we will replace the '\n' with a space character ' '
...

For example:
'_ _ _ _ _ _ _ _ _'

for an unrevealed world

'b u t t e r f l y'

for the completely revealed world

However, this will mean once we print the final letter of the word it will not be finished with a newline
character like a print statement would usually do
...
To avoid this, we will finish the function with a blank print statement ( print() )
without setting our own end value
...


def display_word(word_to_guess, previous_guesses):
for letter in word_to_guess:
if letter in previous_guesses:
print(letter, end=' ')
else:
print('_', end=' ')
print() # Print newline character to finish the word

At the beginning of each loop, we can use this function to print the word containing only the letters they have
guessed
...
add(guess)
if not guess_correct(guess, word_to_guess):
print('That letter is not in the word!')
lives -= 1

4
...
The game will be over when either:
The player has guessed the word correctly
Or the player is out of lives
We can create a function to check whether the player has guessed the entire word
...
We can return
False here and immediately exit the function
...
When this happens, the game must have been won and we can return True on the last line of the
function
...
If it returns

True

True

or

False

, we can call it within an

we can print 'You win!' and then use the

if

statement at the end of each loop of the

break

keyword to break out of the while

loop
# Use won_game function to check if the game is complete
if won_game(word_to_guess, previous_guesses):
display_word(word_to_guess, previous_guesses) # Display the completed word
print('You win!')
break # Break out of the while loop and exit the game

Python For Beginners

103

elif lives < 1:
print('GAME OVER\nYou lose!')

Whole program:
def guess_correct(guess, word_to_guess):
for letter in word_to_guess:
if guess == letter:
return True
return False

def display_word(word_to_guess, previous_guesses):
for letter in word_to_guess:
if letter in previous_guesses:
print(letter, end=' ')
else:
print('_', end=' ')
print()
# FUNCTION TO CHECK IF THE WHOLE WORD HAS BEEN GUESSED
def won_game(word_to_guess, previous_guesses):
for letter in word_to_guess:
if letter not in previous_guesses:
return False
return True

# Start the game
word_to_guess = 'Butterfly'
previous_guesses = set()
lives = 9
while lives > 0:
display_word(word_to_guess, previous_guesses)
guess = input('Guess a letter: ')
previous_guesses
...
Validation - Ensure the guess is a single letter
It's currently possible for the player to guess more than a single letter
...
We need to validate the player's guess input and only proceed if the guess is only one
character long
...


will return the number of letters within the guess string
...
If so, we can inform

them that there was an issue with their guess
...


Whole program:
def guess_correct(guess, word_to_guess):
for letter in word_to_guess:
if guess == letter:
return True
return False
def display_word(word_to_guess, previous_guesses):
for letter in word_to_guess:
if letter in previous_guesses:
print(letter, end=' ')
else:
print('_', end=' ')
print()
def won_game(word_to_guess, previous_guesses):
for letter in word_to_guess:
if letter not in previous_guesses:
return False
return True

# Start the game
word_to_guess = 'Butterfly'
previous_guesses = set()
lives = 9
while lives > 0:
display_word(word_to_guess, previous_guesses)
guess = input('Guess a letter: ')
# VALIDATION - CHECK IF THE GUESS IS NOT 1 CHARACTER LONG
if len(guess) != 1:
print('You must guess a single letter!')
else:
# GUESS IS VALID - PROCESS AS NORMAL
previous_guesses
...
Validation - Ensure the guess has not already been tried
It is also possible for the player to make repeated guesses
...
We can do this by immediately checking whether each guess is already within the
previous_guesses set
...
Otherwise, we should process the guess as normal
...
add(guess)
if not guess_correct(guess, word_to_guess):
print('That letter is not in the word!')
lives -= 1
if won_game(word_to_guess, previous_guesses):
display_word(word_to_guess, previous_guesses)
print('You win!')
break # Exit
elif lives < 1:
print('GAME OVER\nYou lose!')

7
...
If a word contains a capital letter, for
example 'Butterfly', the player will have to guess a capital 'B', as 'b' would not be accepted
...
But we will remove this feature and limit all letters we use in the game to
be uppercase
...

We can convert any string to all upper case using
word = 'Butterfly'
word = word
...
upper()


...

Whole program:

Python For Beginners

106

def guess_correct(guess, word_to_guess):
for letter in word_to_guess:
if guess == letter:
return True
return False
def display_word(word_to_guess, previous_guesses):
for letter in word_to_guess:
if letter in previous_guesses:
print(letter, end=' ')
else:
print('_', end=' ')
print()
def won_game(word_to_guess, previous_guesses):
for letter in word_to_guess:
if letter not in previous_guesses:
return False
return True

# Start the game
word_to_guess = 'Butterfly'
word_to_guess = word_to_guess
...
upper() # CONVERT GUESS LETTER TO UPPER CASE
if len(guess) != 1:
print('You must guess a single letter!')
elif guess in previous_guesses:
print('You have already guessed that letter!')
else:
previous_guesses
...
Print the status of the game
We can print more to keep the player informed:
A welcome message when the game begins
print('Welcome to hangman!')

The number of lives the player starts with
print('You start with', lives, 'lives
...
')

Use an empty print statement to print a blank line to create separation between each guess
print()

Python For Beginners

107

Whole program:
def guess_correct(guess, word_to_guess):
for letter in word_to_guess:
if guess == letter:
return True
return False
def display_word(word_to_guess, previous_guesses):
for letter in word_to_guess:
if letter in previous_guesses:
print(letter, end=' ')
else:
print('_', end=' ')
print()
def won_game(word_to_guess, previous_guesses):
for letter in word_to_guess:
if letter not in previous_guesses:
return False
return True

# Start the game
print('Welcome to hangman!')

# WELCOME MESSAGE

word_to_guess = 'Butterfly'
word_to_guess = word_to_guess
...
\n')
while lives > 0:
display_word(word_to_guess, previous_guesses)
guess = input('Guess a letter: ')
guess = guess
...
add(guess)
if not guess_correct(guess, word_to_guess):
print('That letter is not in the word!')
lives -= 1
# REMIND PLAYER HOW MANY GUESSES THEY NOW HAVE
print('You have', lives, 'lives left
...
Final Program: Put the game into its own function
We can put this game into its own function, with input values for the word to guess and the number of lives
...
To start the game, we can simply call this
function at the bottom of the page
...
upper()
previous_guesses = set()
print('You start with', lives, 'lives
...
upper() # Convert to lower case
if len(guess) != 1:
print('You must guess a single letter!')
elif guess in previous_guesses:
print('You have already guessed that letter!')
else:
previous_guesses
...
')
if won_game(word_to_guess, previous_guesses):
display_word(word_to_guess, previous_guesses)
print('You win!')
break # Exit
elif lives < 1:
print('GAME OVER\nYou lose!')
print()

# Start the game
play_hangman('Butterfly', 9)

We can save this file as hangman
...
py


...


Copy and complete the code below to find the length of the

fruit

tuple
...

# Print the length of the fruit tuple

Hint 1

Python For Beginners

110

We can use a 'for loop' to loop over each element in the tuple
...


Answer
Your code should print

14


...
Each time, instead of using the fruit string
for anything, we can just increment a counting variable
...

fruit = ('apples', 'oranges', 'pears', 'grapes', 'strawberries',
'blueberries', 'bananas', 'apricots', 'blackberries',
'grapefruit', 'kiwi', 'peaches', 'plums', 'pomegranate')

length = 0
for fruit_string in fruit:
length += 1
print(length)

Exercise 2 - Out of Stock
You are given a dictionary that contains keys that are the names of items for sale in a shop, and their
stock quantity as each item's associated value
...


Copy and complete the code below containing the stock dictionary
...


Hint 1
We could use a 'for loop' to loop over stock
...
Alternatively, we could
loop over stock
...


Answer
Your code should print out

oranges

,

grapes

and

wine


...
items()

to iterate over each item and its associated stock value
...
items():
if stock_level == 0:
print(item, 'is out of stock')

Answer 2
We can use


...


# A dictionary containing items for sale and their stock levels
stock = {'bananas': 6, 'milk': 8, 'newspapers': 10, 'apples': 7,
'magazines': 2, 'oranges': 0, 'chocolate bar': 5,
'grapes': 0, 'eggs': 18, 'wine': 0, 'bread': 4,
'beans': 25, 'shower gel': 9, 'tinned tomatoes': 3}
# Iterate over each key in the dictionary
for item in stock
...


Copy and complete the code below containing the function to complete and the numbers list
...
We can do this using a 'for
loop'
...
Then if we find a new value greater than this current maximum, we're going to need overwrite it with this

Python For Beginners

112

new maximum value
...


maximum

to store the current maximum value we have

Note: The word 'max' in Python is the name of a function defined within Python (like print() or len() ),
therefore we cannot use 'max' as a variable name
...
Using the
using it!

max()

function for this question would make it very easy so try and avoid

Answer
Your code should print

145


...

The first 20 Fibonacci numbers are:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Create a function that can take a number

n

and print the first

n

Fibonacci numbers on the same line

separated by spaces
...


Copy and complete the code below containing the function to complete
...


# Print the first 20 Fibonacci numbers
fibonacci(20)

Python For Beginners

113

Hint 1
Fibonacci finds the next number in the series by summing together the previous two numbers
...
Therefore, we'll have to initially store
these first two values in two variables
...

Hint 2
Once we have the first two values of the series stored in variables (i
...
previous = 0 and current = 1 ), we
can create a 'for loop' that sums these two variables together each time (i
...
next_value = previous + current )
...

previous will need to take the value held by current , and current will need to take the next_value
...
During the next
loop, the new values held in

previous

and

current

will be summed to create the next value, and so on
...
For

Answer
To work out any single value in the Fibonacci series, all we need are the two previous consecutive values
...

Initially previous will be 0, and current will be 1
...
We can then 'shift' these two variables along the series, and set:
the new

previous

to be the value held by

the new current to be equal to

current

previous + current

(the next value in the series)

# Define a function to print the first n fibonacci numbers
def fibonacci(n):
previous = 0
current = 1
# Print the first two numbers (0, 1) to begin with
print(previous, current, end=' ')
# Loop n-2 times, as we have already printed the first two numbers
for i in range(n-2):
next_value = previous + current # Calculate the next number in the series
# Shift previous and current along to the next two numbers
previous = current
current = next_value
print(current, end=' ') # Print the new current value

fibonacci(20)

In the fibonacci function above, the code within the 'for loop' will never execute unless n is at least 3
...
g
...

Note: This solution does not work correctly when n=1, as it will always initially print both previous and
current before we reach the loop
...

# Define a function to print the first n fibonacci numbers
def fibonacci(n):

Python For Beginners

114

previous = 0
current = 1
if n == 1:
print(previous)
elif n > 1:
# Print the first two numbers (0, 1) to begin with
print(previous, current, end=' ')
# Loop n-2 times, as we have already printed the first two numbers
for i in range(n-2):
next_value = previous + current # Calculate the next number in the series
# Shift previous and current along to the next two numbers
previous = current
current = next_value
print(current, end=' ') # Print the new current value

fibonacci(20)

Exercise 5 - Duplicate Value
Create a function that takes a list of values and returns a set containing the values that are duplicates
within this list
...


Copy and complete the code below containing the function to complete and the two testing lists
numbers
...

# return the duplicates set

animals = ['cat', 'dog', 'owl', 'dog', 'parrot', 'worm', 'owl']
duplicate_animals = duplicate_value(animals)
print(duplicate_animals)
numbers = [11, 4, 15, 17, 22, 8, 4, 10, 11, 17, 17]
duplicate_numbers = duplicate_value(numbers)
print(duplicate_numbers)

Hint 1
To find duplicate values, we're going to need to examine each item in the
'for loop'
...
We can do this using a

Hint 2
Whilst checking each item in the values list, we're going to need to maintain a set of items that we have
seen before
...
e
...


Python For Beginners

115

If it is, it's a duplicate value that we need to add to the

duplicates

set to return
...


Answer
Your program should output:

{'owl', 'dog'}
{17, 11, 4}
We can loop over each value in the values list
...
If a value is already in this set, we know it is a duplicate and we can instead add it to a set that
holds duplicate values called duplicates
...

# Define a function that takes a list of values and returns a set of
# its duplicate values
def duplicate_value(values):
seen_values = set() # For values we have seen
duplicates = set() # For values that we have seen more than once
for value in values:
if value in seen_values:
# If we have seen this value before add it to the
# duplicates set to return later
duplicates
...
add(value)
return duplicates

animals = ['cat', 'dog', 'owl', 'dog', 'parrot', 'worm', 'owl']
duplicate_animals = duplicate_value(animals)
print(duplicate_animals)
numbers = [11, 4, 15, 17, 22, 8, 4, 10, 11, 17, 17]
duplicate_numbers = duplicate_value(numbers)
print(duplicate_numbers)

Exercise 6 - Sorting
You are given a function called sort_pass
...
If the number is larger than the number to its right, it
swaps the two numbers around
...

def sort_pass(numbers):
for j in range(len(numbers) - 1):
# If two numbers next to each other are the wrong way around
if numbers[j] > numbers[j+1]:
# Swap the two numbers at index j and j+1
temp = numbers[j+1]
numbers[j+1] = numbers[j]
numbers[j] = temp
return numbers

Python For Beginners

116

numbers = [5, 1, 9, 8, 3, 2, 6]
print(numbers)
numbers = sort_pass(numbers)
print(numbers) # Prints [1, 5, 8, 3, 2, 6, 9]
numbers = sort_pass(numbers)
print(numbers) # Prints [1, 5, 3, 2, 6, 8, 9]
numbers = sort_pass(numbers)

For example, using the

sort_pass

function on the list

[5, 1, 9, 8, 3, 2, 6]

1
...
Compare

5

and

9

, and leave them, making

[1, 5, 9, 8, 3, 2, 6]

3
...
Compare

9

and

3

, and swap them, making

[1, 5, 8, 3, 9, 2, 6]

5
...
Compare

9

and

6

, and swap them, making

[1, 5, 8, 3, 2, 6, 9]

it would:

The largest number (9) was moved to the far-right position
...
The

[1, 5, 3, 2, 6, 8, 9]

If we use this function multiple times on the same list, eventually we would end up with a completely sorted list
...
Your

sort

function must call the

sort_pass

the correct number of times, each

time updating the list of numbers, until it results in a sorted list
...


def sort_pass(numbers):
for i in range(len(numbers) - 1):
# If two numbers next to each other are the wrong way around
if numbers[i] > numbers[i+1]:
# Swap the two numbers at index i and i+1
temp = numbers[i+1]
numbers[i+1] = numbers[i]
numbers[i] = temp
return numbers
# Define a function to sort a list of numbers
def sort(numbers):
# Sort the numbers list using the sort_pass function
#
...

# Return the sorted numbers list

numbers = [5, 1, 9, 8, 3, 2, 6]
sorted_numbers = sort(numbers)
print(sorted_numbers)

Hint 1
If we have a list of 4 numbers:
After the first use of

Python For Beginners

sort_pass(numbers)

, the largest number is in it's final sorted position
...


sort_pass(numbers)

, the two largest numbers are in their final sorted

After the third use of sort_pass(numbers) , the three largest numbers are in their final sorted positions,
which means the final fourth number must also be in its final position
...
On the N-1th time, placing the next largest value into it's correct place will also force the smallest
value into it's correct position on the far left
...


sort_pass

function N-1

On the first use, the largest number will be moved into place
On the second use, the second largest number will be moved into place
On the third use, the third largest number will be moved into place
On the (N-1)th use, the (N-1)th largest number will be moved into place
All numbers except one will have been moved into their final sorted position, which means the last number
would also have to be in its sorted position!
If we apply the sort_pass function any more than N-1 times, the list would still be fully sorted
...

We can find the length of the list using

len(numbers)


...


Python Crash Course - Eric Matthes
Covers many of the topics within this course but also contains great walkthroughs of a handful of more
advanced, medium-sized Python projects
...
If you get stuck, a quick Google
search will nearly always give you a solution
...

You can store the phone book as a dictionary, with a person's full name as the key, and their phone number
as the associated value
...

If they enter 'add', you should allow them to enter the name and phone number they would like to add to
the phone book
...

If they enter 'exit', you should break out of the

while

loop using the

break

keyword and exit the program
...

Allow the user to enter either 'rock', 'paper' or 'scissors'
...
You could use a
calculate the overall winner at the end
...

1
...
When the program first starts, print the items the shop is
selling
...
They could name the item by name (e
...
, 'teddy
bear') or print a number next to each item and let them select an item by its number
...
Your program should check whether that item is stored within the dictionary, and if so, fetch its price and
tell the user how much that item is by printing to screen
...
g
...
30 in total
...
Convert the string inputted by the user into integer values and sum up the coins that have been entered to
find the total money given to the shop by the customer
...
You'll need to work out if the customer has given the right amount, too much, or not enough money
...
Take
this difference and try and find a method to convert the value of change into values of real coins to return
...
Your code would need to handle
all change in coins for all cost differences, some are harder than others!
Change of 40 (40p) could be represented as 20 and 20, as 40p coins don't exist
Change of 70 (70p) could be represented as 50 and 20
Change of 250 (£2
...


Thank You!
Thank you for taking this course! If you have any feedback, please fill out the form below!
Course Feedback

https://docs
...
com/forms/d/e/1FAIpQLSfrZqysWdmawcCnpS22umOX_fS0huG7_WC
815s5Pfsak0aZLw/viewform?usp=pp_url&entry
...
notion
Title: Python for Beginners
Description: The ultimate introduction to Python programming. Over 12 hours of content, including diagrams, exercises and project walkthroughs! Suitable for all levels of ability, even if you have never coded before! This PDF includes a link to the interactive Notion-based version of the course. This course covers: - Getting Python running on your machine - Variables and data types - If statements - For loops and while loops - Data structures (lists, dictionaries, tuples and sets) - Functions - Walkthroughs of coding exercises - Python project suggestions