Python Helper
Python Helper
Y10 / Y11 / 12 / 13
ABILITY LEVEL
NOVICE
AMATEUR
INTERMEDIATE
EXPERT
NOVICE
Getting Started Running Our Program
KEYWORDS
AMATEUR
Mathematics 2 For
Lists Elif
Boolean Indentation
KEYWORDS
INTERMEDIATE
File Handling Try/Except
Random Imports
Functions Numpy
KEYWORDS
EXPERT
Lambda Global / Local
Iterators PANDA
KEYWORDS
Next Lesson: IDE
Getting Started
Python
What isin the real world
Python?
• Web development (server-side)
•Python Software development language, this means that as a developer you
is a programming
•write Mathematics
Python (.py) files in a text editor and then put those files into the
•python
System scriptingto be executed.
interpreter
What
We cancan Python
write do? using a text editor or any IDE that can handle
programs
•ourPython can be used on a server to create web applications.
code effectively.
•Working
Pythonwith
can Python
be usedisalongside softwareif to
straightforward youcreate workflows.
are using an editor.
•Below
Python
are can
someconnect to database systems. It can also read and modify
options:
files.
replit.com
online-python.com
Next Lesson: Variables
IDE
Interface
What is an IDE?
Your code willdevelopment
An integrated be written inenvironment
the editor. All(IDE)
calculations, etc. will
is a software be performed
application within
that provides
the IDE so be aware
comprehensive that to
facilities you won’t see
computer anything appear
programmers 1)software.
for File Manager-
within the console Allows
unlessmeyou
program the
In other words,code
it to
is do
the so.
environment that allows you to to organise,
create and create
write code. and
Fordelete
the
1 2 3
IDE toolsof this tutorial, we will be working within replit.com.
purposes files. It is in your best
•interests
Debuggers-
to createshow you thebecause
an account errors within your code
the website 2) you
allows Editor- Where
to save youryou
work will
as
•‘repls’.
Colour Coding- Highlight key words and phrases to help writeyou
codekeep track
•OnceTranslators-
you have madeTranslates your and
an account codeyou
from Python
have 3)your
into
created Console- Where
machine-readable
first Python you can
code. see
This
application,
we means that awhat
will review computer canare
features now understand
involved it and more
in IDEs the specifically,
results of yourthecode
tools
•within
Filereplit.com.
Management- Internal file management means you can organise a large
project a lot easier.
Figure 1.1- A typical Replit.com layout
Next Lesson: Mathematics
Variables
A Noteis a variable?
What
Variables
A variableare
is aone word.
data storeWhen we giveaavalue.
that contains variable
Weacan
name, ensure
create and that
call itvalues
is oneby
word or
giving
that a variable
a name has aitname
and giving separated
a value. Ie: by underscores.
A=5
There are some words in Python that are predefined. This means that these words are
u
We
usedhave just created
by Python the variable
to create code. We‘A’ and given
cannot it a valuethese
give variables of 5. When we manipulate
particular names
‘A’ we will
because youbewill
manipulating the number 5. Variables are case-sensitive. This means
run into errors.
that the variable ‘a’ is different from the variable ‘A’. Variables should be named
appropriately.
Python works As you are creating
sequentially a largeitfile,
which means keeping
reads track
the code of yourIfvariable
in order. we give names
‘A’ a is
extremely
value of 5 important and yourselfgive
and then underneath, in the
it along
valuerun!
of 7, A’s value is now 7.
Next Lesson: Running Our Program
Mathematics
Mathematics
Further Operators
Manipulating in Python
Variables
Pythonis**
Below isanbest suited
Exponentiation
example to
of perform complex
two variables thatmathematic operations.
have been added We I
together.
can manipulate
have //
a variable; Integer
numbers
A and Division
and variables
a variable; quite
B. Both of easily in Python
them have by using a
an assigned
series and
value of== traditional
I haveEqualsums
To toand
chosen addequations.
them together
<>
The calculation Less Than / More
is happening Than
within the IDE which means that we are
Operators
not seeing the result of the calculation
The
Usingsymbols
Operators used within Python to perform mathematical operations
We can +use operators
Addition Note
relatively easily. Just like in mathematics, we
simply declare
- a number, an operator andIfanother
Subtraction you want to seeie:
number an output,
*4+4 Multiplication you need to tell the program to
We can /also manipulate
Division variables. produce the calculation.
Next Lesson: Common Errors
Note
You must use the print command or you won’t be
able to see your results. The print function is
always lower case.
Next Lesson: Data Types
Common Errors
NameErrors
Errors
Type Error
A much can
Coding
Another more becommon
common error type
challenging ifofyou
to find error
is is known
aaren’t
‘type error’.as
aware of awhat
This‘NamemayError’
is where whereor
goa wrong
user
a variable
if
attempts tohas
you don’t been ‘called’
understand
combine twothe (used
errors
data typesfor a calculation)
asthat
they arise.work
don’t but
Errors hasn’t
will been
tellWe
together. you
can
‘defined’
which
add twoline(no
thevalue
numbers errorwas
togetherassigned
occurred and to
or two it). type
what
words of error
together butitnot
is.
The example
Figure 1 shows
interchangeably. shows a line 2 error
a mathematical where
error ‘B’ has
in ‘line not been
4’ where defined
a user attempted
to divide
This by zero.
example shows an error on line 4. It states you cannot concatenate
Note
(combine) a str and an int. We will explain what that means soon.
Python is case
Note
sensitive.
There ‘A’ is errors
are more
different
that to ‘a’We will
can arise.
look at them later
Next Lesson: Inputs & Controls
Data Types
Using Boolean
Data Types
Formatting your Data Types
In
Data
If programming
you Types
want are you
the
to create aoften
dataneed
‘format’ to
that the
type know
withdata if anbeen
has
a word, expression
you is True
represented
will have to in. or
It isFalse.
create aimportant to is
variable that
You can evaluate
aunderstand
string– any
what type
naturally. expression
of data
Ensure thatyou in
whenarePython,
areand
working
you get so
with
creatingone of you
athat twovariable
string answers,
can True
manipulate
that youortheFalse.
use
When you
variables
speech compare
that
marks you twocreated.
have
to represent values, the you
it. When expression is evaluated
are creating andsquare
a list, use Python returnswith
brackets the
Boolean
elements answer:
separated by commas. Not formatting it this way will create errors.
Note
Figure 1 compares two integers and
then produces the Boolean value.
Note
Example
We use two
Prompts to dobrackets to represent
not influence the codenumber inputs.
and you canOne after
write the data type
in anything andprompts.
into the then one
The example takes in an input: A on line 1. Line 2 prints out the world “Hello”
after input.
They Remember
just allow to close
the end-user to itunderstand
off with two
the brackets.
program
followed up by whatever the end-user types into the console.
Keywords
An integrated development environment (IDE) is a software application that provides
IDE comprehensive facilities to computer programmers for software development
A program used to test and debug programs. The main use of a debugger is to run the
Debugger program under conditions that tell the programmer to track its execution and monitor
changes
Variable A data store that contains a value and a name.
Operators A symbol used in mathematical calculations. Operators allow for multiplication, addition,
subtraction etc.
Syntax The syntax of a computer language is the rules that defines the combinations of symbols
that are considered to be correctly structured
Data Types The format that data is represented. Python has many in-built programming data types ie:
integer, float, Boolean, list etc.
Next Lesson: Lists
Mathematics 2
Examples
Incrementing
Look
We at use
can the several
figures below…
operators in our calculations. We often use the ‘+=‘ operator to
increment. This means that we can add onto a variable
Figure 1 easily and produce new results.
An example that asks the program whether 6
is more than or equal to 6. Because it is, it
produces true.
NoteFigure 2
Figure 1: More than or equal to TheAn‘+=‘ is shorthand
example of thefor ‘A=A+5’.
modulus We can
operator. dois
This
the same thing for after
the remainder minus, multiplication
a whole or
number division.
division.
5 willSimply
producechange thebeing
a 1 after operator.
integer divided.
Lists
Python
IndexingCount
Appending
Python
When
You may begins
want aits
making count
tolist,
add we from 0, which
can print
something toout means
the
a list. that
entire listifuse
We must wethe
but wanted
what to select
if we
‘append’ only
the
want1sttoelement
function use/ in a list, we
manipulate
to add something would
part thehave
of to
new list.to
a list? index
This the 0thwe
is where term.
useTo call a
indexing.
specific element, we must call the list and then where in the index.
0 1 2 3
Removing
Note
You may want to remove something from a list. We must use the
Use square brackets within the
‘remove’ function
Multiple Elements to remove an element from a list.
round brackets and use a number
We can select multiple elements with a comma
to referie:
to mylist[2,3] or awe
an element in can
list.
set a range using a colon ie: mylist[0:3].
Next Lesson: While Loops
Boolean
Formatting
If & Else
If
Anstatements
else statement
should
allowfollows
always
for moreupbefrom
lower
complex theprogramming.
if We can check
case.
statement.
whetherWesomething
can
If an
set‘if
ourstatement’
iscriteria,
true by toischeck
not up some condition then we can
setting
whether
fulfilled,
follow upsomething
the
theelse statement
is equal,
condition withwill
more bethan,
a result.
less
fulfilled.
than etc. and then we finish our
statement
The ‘else’with
statement
a colon must
at the
be in
end.line with Figure 1: Comparing strings
Note
Our
the ifstatement
statementthat
or you
follows
will must
run into
be an In the example, we are checking
underneath
‘indentationthe error’.
if statement and be whether ‘A’ is more or equal to
‘indented’.
Else statementsIndented
mustmeans
also bethe
lower case5. Because it is, we can run the
statement
and are finished
has a space
with afrom
colon.
the left. result: to print “hello”.
Review the examples. Figure 2: Not equal
Next Lesson: For Loops
While Loops
Combining
While Loops
Stopping Concepts
While Loops
You
Therecan
While areput
two
loops ‘if
types
are statements’
of loops:
not only within
built for and
loops. Line 6 declares that variable
to print
‘x’
while.
should
We increase
something will be looking
forever. by 1 can
You each
atstop
the
time.
latter.
Line
a code A 4 states that if ‘x’ is equal to
3,
while
by thenloop
usingthe code
occurs should
mathematics. whenThe‘break’.
a condition
variable,has ‘i’
The
been
is break
met.
1 and function
while ‘i’ is stops the 6,
less than loop.
the This Figure 1:
codeactivates Iteration
once and 3.
x reaches
Much like
should run.an if statement; a loop’s loops
statement
Every timemust be indented
the loop occurs, as is Note
‘i’ well. In
the example,
printed, we from
Starting have created
1. On Line a loop4,A‘i’loop inside another loop is
under the by
increases condition
1. So the that A iswill
loop equal tocalled
happen 4. a nested loop.
Because
until the A is always
variable going5.to be 4, we
reaches
print ‘hello’
Have a look forever.
at another example Figure 2: Printing 6 times
Next Lesson: Elif
For Loops
Manipulating ‘x’
Count-Controlled
For
Also loops
We can known areasused
manipulate athe
‘count lotcontrolled’
because that
variable ofloops
their
we mean
just created
that fortoloops
keep set
count of our for
a criteria loop.
howThe
versatility.
ability
long Youshould
thetoloop can loop
manipulate the through
last.variable about
is the reason
This is known as the that for or
‘count’ loops
the are usedWe
range. souse
often.
a lower
anything.
case ‘for’,Look
use aatvariable
the examples
to keepand
countnote
ie:x and then set the range.
that we can loop through a string or a list.
All we have to do is set the ‘range’ as the list
Scenario
name or the string itself.
I can take my ‘x’ variable and manipulate itNoteFigure 1: Looping through a string
Note
with maths
Printing theto
‘x’simulate
variableameans
times table.
we can printYou must use a whole number (integer)
Beginning
the elements from 0, xrange.
in the will always increase byin order to set up the loop’s length.
1. Each ‘x’ is then told to multiply by 6 after
a string. Figure 2: Looping through a list
Next Lesson: Indentation
Elif
Elif
Elif is
conditions
a shorthandare statement
applied afterusedthetoifrepresent
condition. Python will evaluate
the
‘else’ifif’.
condition’
In regardsandtoifif/else
it evaluates to False
statements, we then it will evaluate the elif blocks and
execute
can imagine the elif
thatblock whose
‘if’ and expression
‘else’ evaluates to True. If multiple elif conditions
are inherently
become
linked. True, then the first elif block will be executed. The below examples illustrate
the differences
If the ‘if condition’ is not fulfilled, we want the
else statement to run but what if there are
several criteria that I want to check for?
Observe the example structure
Indentation
Nested Loops
Indentation
Sometimes
Indentation
Indented you
is the
statements want to place
spacing
should that a loop
have inside a conditional
an attaching statement
statement; for or all
instance, maybe
the a
conditional
follows after
statements statement
a loop or
indented within another
a conditional
below form conditional
a block and belongstatement.
to the ifWhen we have
statement. Thismore
is than
one, we call
statement
applicable forthis
(if/else). a nested
while,Without loop.
the
for, functions, classes, etc in python. The below example makes
spacing,
this pointyou
clear.will run into the
Although an error
code but
works, Line 3 does not run based off of the if
when we are creating another loop/
statement.
Indentation
conditional statement, we have to
Even in this scenario, we must still be very
ensure that all of it is level or we will
aware of our indentation and ensure that it is
Noteinto
run errors.
consistent.
Python uses 4 spaces as indentation by default.
This example illustrates Note
However, the number ofhow
spacesweiscan
up correctly
to you, but a
indent our of
nested loops. Notice line 4’s spacing is inconsistent with
minimum 1 space has to be used.
line 2.
Combining Ideas
Solving
Lists and
Strings for
& Loops
‘n’
Boolean
Python
Combining
In is good
concepts
the example for Mathematics.
below,iswe
how we combined
have can
Saycreate
we wanted
acomplexto add
for loop,programs.
up Boolean,
some all of
Wethe
take
digits
onefrom
example,
indentation 0and
to
10,
and we
some apply
should
it to
maths use
others.
a forFor
operations. loop.
example,
A for loop
we can
willcombine
go through
for the
loops
digits
withifawe
listset
andthethen
range
use
to
conditional
10. statements to check the list
Example
Iterating
In order to keep count, we must also
We should
assign an add
emptyall variable.
the numbersLineto7 an
is not
empty variable
indented ‘total’.
because if it On
wasline 5, we
within theprint
the totalit but
loop, alsoprint
would mustasadjust
manytotimes
account
as
Note for
then.loop
Because the for loop stops at 9, we
iterates.
The if statement checks the ‘x’ variable. The xmust
actsadd
as a‘n’.
counter that cycles through
the list.
Keywords
Shorthand for ‘else if’ allows user to create a conditional statement with an outcome outside
Elif of the ‘if and else’ comparison. Runs if an if statement is not fulfilled.
Indentation The short space following a loop/ function. Required in Python’s syntax
A loop within a loop/ a function. Further levels of indentation mean that more complex
Nest loops/ functions can be written to one block of code.
Loops A function that allows users to repeat a block of code. ‘For and while’ loops limit the code
to be repeated based off of a count (how many times the user dictates) or a condition
respectively.
Increment A block of code repeating or increasing based off of the previously stated condition.
Increment means that a value or variable can increase
List A data type where several elements can be stored in one variable. Retrieving the individual
parts of the list is called ‘indexing’
Next Lesson: Random
File Handling
Serial
Example Files&& File
File Directories
Directories
There
On theareleft,many times
we can seewhen
a newyou filemay
has want to createcalled
been created a file ‘demofile.txt’.
in Python ie: a We
saveuse
filethe
for
a‘a’game, a document
function to add a from yourand
new file calculations
then we can etc.write whatever we want. In the
A file directory
example, is where
we create all ofstring
a simple the files in practice,
but in your project are stored.
we can Your main
write anything project
to the file.
file
Lineis4going
is howtocan
naturally be called
effectively ‘save’‘main.py’. ‘Py’
the file and refers
move to Python
onto anotherfiles. Wethe
part of can use
several
project. functions
The variableto create new documents.
‘f’ is used to effectively control the new file.
Commands
"r" - Read - Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it doesn’t exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
Next Lesson: Functions
Random
Random Functions Random Functions
Importing
We canwe
Before use‘random’ means
the ideathat
the random.choice
approach you
usinghave brought
offunction a libraryfunction
The shuffle into Python. Because
does not require a
Python
to pick acannot
random inrandom dochoice
Python, everything, we use libraries
from discuss
we should a list. the to do extra
variable and stuff outside
allows you toofrandomise
Python’s a
limitations.
Call of
idea the‘randomness’.
list within the brackets list
We can produce
Computers randomand
take inputs integers using a function;
naturally Note-“randint”.
There are To perform
more randint, we
functions
must reference
generate outputsthe library. on what
dependent
information is put into it. However, Python
creates a ‘random’ output based off of
several factors. Example
Note
To that end, with complex calculations, do WeIncan manipulate
order to work the
withvariable
random‘a’
not depend on this. further.
variables, we must import random.
Next Lesson: Functions Cont.
Functions
Making your Functions
Calling Parameters
Parameters
A function
By (also
default, is called
a block
a function arguments)
ofmust
codebewhich are
called specified
only
with runs afteritnumber
when
the correct the function
is called.
ofYouname, inside
can pass
arguments. the
data,
parentheses.
known asthat
Meaning You can function
parameters,
if your add
intoasa many arguments
function.
expects A as you
function
2 arguments, want,
canyoureturn just
have toseparate
data as athe
call them
result. with
function
awith
comma.
There2 are times where
arguments, you may
not more, andneed code to repeat in large structures. In order to
not less.
minimise how much repetitive code we write, we use functions. In Python a
function is defined using the def keyword:
Example
The error states we are missing 1
The following example has a function with one argument argument (fname). When the
function is called, we pass along a first name, which is used inside the function to
print the full name:
Next Lesson: Try / Except
Functions Cont.
Default
Arbitrary
Functions Parameter
Arguments
in PracticeValues
*
The
If you
following
do not
Functions are know
aexample
block how
ofshows
many how
arguments
code that to use
can that
a default
be used will be
parameter
passed
to repeat code into
value.
or recall
If
your
wefunction,
call later
functions the function
add
in a alarge
* before
without
bodytheargument,
of parameter
code butitituses
name the
in default
the function
is important value:to:
practice
definition.
1. Name the program’s variables and functions properly.
2. Code according to your style. You can also import code from other
files into your document without needing to write functions.
Keywords
You
Bothcan also send
example arguments
codes with the do
still effectively keythe
= value syntax. This way
same thing.
the order of the arguments does not matter.
Example
We can use default values to replace incorrect user inputs or we
could use this to format data correctly.
Next Lesson: Imports
Try / Except
Try and
Try and Except
Except
Theseisfunctions
This replace
also known errorhandling’
as ‘error codes. Ifwhich
a user limits
were to
theenter data
errors incorrectly,
that can follow.instead
In of
the code crashing,
combination we could
with human use we
input, a series of functions
can create to cancel
more robust these issues.
code.
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The else block lets you execute code when there is no error.
Else
The else statement follows the statement as the
‘except’ statement was not called.
Next Lesson: Numpy
Imports
CommonImports
Custom Imports/ Modules
There
Wethe
In are a series
previously of common
looked
‘mymodule.py’ we modules
at imports
file, that‘import
with the
have reoccurrandom’
in Python. Onebut
library of itthem is
is important to
‘datetime’.
discuss aother
created Weimports
canand
function import
that datetime.
thenPython In the example I have imported it as ‘dt’ to save
have uses.
space.
You can
later usedimport your own
that function intolibrary
our (also known as modules). By creating your own file,
giving itcode.
original a name followed
This by the ‘.py’ file type, we can create our own libraries which
keeps your
we can
code later
less reference.
crowded and organised Renaming Modules
especially if certain parameters You can create an alias when you import a
will be reused over and over. module, by using the as keyword
Note
We can rename any module that we can import. Datetime has a lot more
considerations within Python so research further for extended learning.
Next Lesson: Distribution
Numpy
Arrays
NumpyIndexing
Array
Arrays
When can
is abe
Numpyaccessing considered
vast we‘3d
and complex
arrays, lists’.
Python
must We can
library.
declare create
which moreof
Consider
‘’row’ complex
this
theasarrayarrays
we arebyaccessing.
using
an introduction to
square
Numpy,
First brackets
not an
number androw,
entire
calls commas
use-case
secondtoofdivide
all ofits
number its values. Below are two examples of a 2d
potential.
calls element.
array
NumPy andisaa3d arraylibrary.
Python respectively.
NumPy is short for "Numerical Python".
It gives us access to the data type; array. Put simply, imagine a list that can contain
more complex data
Reshaping
You can use Numpy to
convert a list into an
array by calling how many rows and elements within your new array.
Distribution
Random
Example Distribution
Normal (Gaussian) Distribution
Data
Named Distribution
Generate Gaussian
a 1-D arrayis a containing
list ofafter
Distribution all possible
the
100 German values,
values, andeach
where how value
mathematician oftenFriedrich
Carl eachtovalue
has be 3,occurs.
Gauss,5,it7fits the
or 9.
probability
Such
The distribution
lists are
probabilityimportant
for theofvalue
many
whento events,
be 3 eg.
working IQ Scores,
with
is set Heartbeat
tostatistics
be 0.1The and etc. science.
data
probability for the value to
Use5can
We
be the random.normal()
generate
is set to be 0.3. Themethod
random numbersto getbased
probability afor
Normal Data to
on value
the definedDistribution.
probabilities. The
be 7 is set to be probability
0.6. The is
It has three parameters:
set by a number
probability between
for the value to 0 and
be 91,is where
set to be 0 means
0 that the value will never occur and
loc - (Mean) where the peak of the bell exists.
1 means that the value will always occur.
scale - (Standard Deviation) how flat the graph distribution should be.
You
size -can
Thereturn arrays
shape of of any array.
the returned shape and size by specifying the shape in
the size parameter.
Note
You can build graphs using the Seaborn module
Keywords
Files created in Python that are an off-shoot of the functions necessary to write, open, close
Serial Files or append to a file.
Random A library/ module within Python that allows for random choices and numbers to be
generated.
A function is a block of code which only runs when it is called. You can pass data, known
Function as parameters, into a function.
Modules A Python module is a file containing Python definitions and statements. A module can
define functions, classes, and variables. A module can also include runnable code.
Distribution A normal distribution is a type of probability distribution in which most data points cluster
toward the middle of the range, while the rest taper off symmetrically toward either
extreme.
Seaborn Seaborn is a library that uses Matplotlib underneath to plot graphs. It will be used to
visualize random distributions.
Next Lesson: Classes/Objects
Lambda
Lambda Functions
Say you have
A lambda a function
function is adefinition that takes one
small anonymous argument,
function. and that
A lambda function
argument will number
can take any be multiplied with an unknown
of arguments, but cannumber:
only have one expression.
Classes/Objects
__str__()
The __init__()
Classes/ function
function
Objects
The __str__()
The previous
Python function
examples
is an object controls what
are classes
oriented programming language. Almost everything in
should
and
Python be
isreturned
objects when
aninobject,
their theits
simplest
with class
form,
properties and methods. We can define a ‘class’
object
and
using is not
aretherepresented as a string.
reallykeyword
‘class’ useful and In
large the several variables within the class.
have
example, we want
applications. We the
haveagetoto be
surrounded by brackets.
understand the built-in __init__() Example
function. We have created a class and indented all of
Object Methods
Use the can
__init__() function to the variables within the class. We still must
Objects also contain methods.
assign
Methods values to object
in objects that give the class over to a variable in order to
properties,
are functions
or othertooperations
belong the object. that are call the elements within the class.
necessary
Let us create to ado wheninthe
method theobject
Personis
class: created:
being
Next Lesson: Classes/Objects
Inheritance
Super & Adding Properties
Inheritance
Inheritance
Python alsoallows
has aussuper()
to define a class that inherits all the methods and properties from
function
another
that willclass.
make the child class inherit
Parent
all the class
methodsis theand
classproperties
being inherited
fromfrom, also called base class.
Child class is the class that inherits from another class, also called derived class.
its parent.