IGCSE Python Complete Notes
IGCSE Python Complete Notes
IGCSE Python Complete Notes
PROGRAMMING
Programming and Problem
Solving Through Python
Language
IGCSE - PYTHON
1
IGCSE - PYTHON
Introduction to Programming
Before we understand what programming is, you must know what a computer is. A
computer is a device that can accept human instruction, processes it, and responds
to it or a computer is a computational device that is used to process the data under
the control of a computer program. Program is a sequence of instruction along with
data.
The basic components of a computer are:
Input unit
Central Processing Unit(CPU)
Output unit
The CPU is further divided into three parts-
Memory unit
Control unit
Arithmetic Logic unit
Most of us have heard that CPU is called the brain of our computer because it accepts
data, provides temporary memory space to it until it is stored (saved) on the hard
disk, performs logical operations on it and hence processes (here also means
converts) data into information. We all know that a computer consists of hardware
and software. Software is a set of programs that performs multiple tasks together.
An operating system is also software (system software) that helps humans to interact
with the computer system.
A program is a set of instructions given to a computer to perform a specific operation.
Or computer is a computational device that is used to process the data under the
control of a computer program. While executing the program, raw data is processed
into the desired output format. These computer programs are written in a
programming language which are high-level languages. High level languages are
nearly human languages that are more complex than the computer understandable
language which are called machine language, or low level language. So after knowing
the basics, we are ready to create a very simple and basic program. Like we have
different languages to communicate with each other, likewise, we have different
languages like C, C++, C#, Java, python, etc. to communicate with the computers.
The computer only understands binary language (the language of 0’s and 1’s) also
called machine-understandable language or low-level language but the programs we
are going to write are in a high-level language which is almost similar to human
language.
Step 1
Variable 1001001
Step 2
if 1000111
Problem Step 3 Solve
while 1011111
Step 4
print 1000110
..
2
IGCSE - PYTHON
Algorithm
A sequential solution of any program that written in human language, called
algorithm. Algorithm is first step of the solution process, after the analysis of
problem, programmer writes the algorithm of that problem.
It can be understood by taking an example of cooking a new recipe. To cook a new
recipe, one reads the instructions and steps and execute them one by one, in the
given sequence. The result thus obtained is the new dish cooked perfectly. Similarly,
algorithms help to do a task in programming to get the expected output.
The Algorithm designed are language-independent, i.e. they are just plain
instructions that can be implemented in any language, and yet the output will be the
same, as expected.
Characteristics of Algorithm:
Clear and Unambiguous: Algorithm should be clear and unambiguous. Each
of its steps should be clear in all aspects and must lead to only one meaning.
Well-Defined Inputs: If an algorithm says to take inputs, it should be well-
defined inputs.
Well-Defined Outputs: The algorithm must clearly define what output will be
yielded and it should be well-defined as well.
Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite
loops or similar.
Feasible: The algorithm must be simple, generic and practical, such that it can
be executed upon with the available resources. It must not contain some future
technology, or anything.
Language Independent: The Algorithm designed must be language-
independent, i.e. it must be just plain instructions that can be implemented in
any language, and yet the output will be same, as expected.
3
IGCSE - PYTHON
Advantages of Algorithms:
It is easy to understand.
Algorithm is a step-wise representation of a solution to a given problem.
In Algorithm the problem is broken down into smaller pieces or steps hence, it
is easier for the programmer to convert it into an actual program.
Disadvantages of Algorithms:
Writing an algorithm takes a long time so it is time-consuming.
Branching and looping statements are difficult to show in Algorithms.
Example of Algorithm?
Algorithm for add two numbers entered by the user.
Step 1: Start
Step 2: Declare 3 variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum ← num1+num2
Step 5: Print sum
Step 6: Stop
Flowchart
Flowchart is a graphical representation of an algorithm. Programmers often use it
as a program-planning tool to solve a problem. It makes use of symbols which are
connected among them to indicate the flow of information and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.
4
IGCSE - PYTHON
Flow lines: Flow lines indicate the exact sequence in which instructions are
executed. Arrows represent the direction of flow of control and relationship
among different symbols of flowchart.
Advantages of Flowchart:
Flowcharts are better way of communicating the logic of system.
Flowcharts act as a guide for blueprint during program designed.
Flowcharts helps in debugging process.
With the help of flowcharts programs can be easily analyzed.
It provides better documentation.
Flowcharts serve as a good proper documentation.
Disadvantages of Flowchart:
It is difficult to draw flowchart for large and complex programs.
In this there is no standard to determine the amount of detail.
Difficult to reproduce the flowcharts.
It is very difficult to modify the Flowchart.
Example: Draw a flowchart to input two numbers from user and display
the larger of two numbers
5
IGCSE - PYTHON
Programming Language
As we know, to communicate with a person, we need a specific language, similarly
to communicate with computers, programmers also need a language is called
Programming language.
Before learning the programming language, let's understand what is language?
What is Language?
Language is a mode of communication that is used to share ideas, opinions with
each other. For example, if we want to teach someone, we need a language that
is understandable by both communicators.
6
IGCSE - PYTHON
Compilation
The compilation is a process of converting the source code into object code. It is
done with the help of the compiler or interpreter. The compiler checks the source
code for the syntactical or structural errors, and if the source code is error-free,
then it generates the object code.
Introduction of Compiler Design
The compiler is software that converts a program written in a high-level language
(Source Language) to low-level language (Object/Target/Machine Language).
Cross Compiler that runs on a machine ‘A’ and produces a code for another
machine ‘B’. It is capable of creating code for a platform other than the one
on which the compiler is running.
Source-to-source Compiler or transcompiler or transpiler is a compiler that
translates source code written in one programming language into the source
code of another programming language.
Language processing systems (using Compiler) –
We know a computer is a logical assembly of Software and Hardware. The hardware
knows a language that is hard for us to grasp, consequently, we tend to write
programs in a high-level language that is much less complicated for us to
comprehend and maintain in thoughts. Now, these programs go through a series of
transformations so that they can readily be used by machines. This is where language
procedure systems come in handy.
High-Level Language – If a program contains #define or #include directives
such as #include or #define it is called HLL. They are closer to humans but
far from machines. These (#) tags are called preprocessor directives. They
direct the pre-processor about what to do.
Pre-Processor – The pre-processor removes all the #include directives by
including the files called file inclusion and all the #define directives using
macro expansion. It performs file inclusion, augmentation, macro-processing,
etc.
Assembly Language – It’s neither in binary form nor high level. It is an
intermediate state that is a combination of machine instructions and some
other useful data needed for execution.
Assembler – For every platform (Hardware + OS) we will have an assembler.
They are not universal since for each platform we have one. The output of
the assembler is called an object file. Its translate assembly language to
machine code.
Interpreter – An interpreter converts high-level language into low-level
machine language, just like a compiler. But they are different in the way they
read the input. The Compiler in one go reads the inputs, does the processing,
and executes the source code whereas the interpreter does the same line by
line. Compiler scans the entire program and translates it as a whole into
machine code whereas an interpreter translates the program one statement
at a time. Interpreted programs are usually slower with respect to compiled
ones.
Relocatable Machine Code – It can be loaded at any point and can be run.
The address within the program will be in such a way that it will cooperate
with the program movement.
Loader/Linker – It converts the relocatable code into absolute code and
tries to run the program resulting in a running program or an error message
(or sometimes both can happen). Linker loads a variety of object files into a
single file to make it executable. Then loader loads it in memory and executes
it.
7
IGCSE - PYTHON
Testing Debugging
Testing is the process to find bugs and errors. Debugging is the process to correct the bugs
found during testing.
It is the process to identify the failure of It is the process to give the absolution to code
implemented code. failure.
There is no need of design knowledge in the Debugging can’t be done without proper design
testing process. knowledge.
Testing can be done by insider as well as Debugging is done only by insider. Outsider can’t
outsider. do debugging.
It is based on different testing levels i.e. unit Debugging is based on different types of bugs.
testing, integration testing, system testing etc.
Testing is composed of validation and While debugging process seeks to match symptom
verification of software. with cause, by that it leads to the error correction.
Testing is initiated after the code is written. Debugging commences with the execution of a
test case.
8
IGCSE - PYTHON
9
IGCSE - PYTHON
Algorithm Flowchart
Algorithm is complex to
understand. Flowchart is easy to understand.
10
IGCSE - PYTHON
Flowchart for find the largest among three different numbers entered by the user.
11
IGCSE - PYTHON
12
IGCSE - PYTHON
13
IGCSE - PYTHON
Algorithm and flowchart for GCD (Greatest Common Divisor) or HCF (Highest Common
Factor) of two numbers.
Step 1: Start
Step 2: Read n1, n2
Step 3: If n1=n2
Then go to step 5
Step 4: If n1>n2
n1 n1- n2 go to step 3
else
n2 n2 – n1 go to step 3
Step 5: Print n1
Step 6: Stop
14
IGCSE - PYTHON
15
IGCSE - PYTHON
16
IGCSE - PYTHON
17
IGCSE - PYTHON
Introduction to Python
What is Python?
Python is a popular programming language. It was created by Guido van Rossum,
and released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
System scripting.
Why Python?
Good to know
The most recent major version of Python is Python 3, which we shall be using
in this tutorial. However, Python 2, although not being updated with anything
other than security updates, is still quite popular.
In this tutorial Python will be written in a text editor. It is possible to write
Python in an Integrated Development Environment, such as Thonny,
Pycharm, Netbeans or Eclipse which are particularly useful when managing
larger collections of Python files.
Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.
18
IGCSE - PYTHON
To test a short amount of code in python sometimes it is quickest and easiest not
to write the code in a file. This is made possible because Python can be run as a
command line itself.
From there you can write any python, including our hello world example from
earlier in the tutorial:
Whenever you are done in the python command line, you can simply type the
following to quit the python command line interface:
Interpreter converts the byte code into machine code and sends that machine code
to the computer processor for execution.
19
IGCSE - PYTHON
Python Variables
Creating Variables
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type and can even change
type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Example
x = "John"
# is the same as
x = 'John'
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:
20
IGCSE - PYTHON
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output Variables
Example
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z = x + y
print(z)
Example
x = 5
y = 10
print(x + y)
If you try to combine a string and a number, Python will give you an error:
21
IGCSE - PYTHON
Example
x = 5
y = "John"
print(x + y)
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Creating a Comment
Comments can be placed at the end of a line, and Python will ignore the rest of the
line:
Example
print("Hello, World!") #This is a comment
Comments does not have to be text to explain the code, it can also be used to
prevent Python from executing code: Comment shortcut key = ctrl+/
Example
#print("Hello, World!")
print("Cheers, Mate!")
Python does not really have a syntax for multi line comments.
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
22
IGCSE - PYTHON
Since Python will ignore string literals that are not assigned to a variable, you can
add a multiline string (triple quotes) in your code, and place you comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but
then ignore it, and you have made a multiline comment.
Python Numbers
Python Numbers
int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
To verify the type of any object in Python, use the type() function:
Int
Example Integers:
x = 1
y = 35656222554887711
z = -3255522
Float
Example- Floats:
23
IGCSE - PYTHON
x = 1.10
y = 1.0
z = -35.59
i = 35e3
j = 12E4
k = -87.7e100
Float can also be scientific numbers with an "e" to indicate the power of 10.
Complex
Complex numbers are written with a "j" as the imaginary part:
Example Complex:
x = 3+5j
y = 5j
z = -5j
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
Python Strings
String Literals
String literals in python are surrounded by either single quotation marks, or double
quotation marks.
24
IGCSE - PYTHON
Example
print("Hello")
print('Hello')
Python constants
Sometimes, you may want to store values in variables. But you don’t want to
change these values throughout the execution of the program.
Assigning a string to a variable is done with the variable name followed by an equal
sign and the string:
Example
a = "Hello"
print(a)
Multiline Strings
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
25
IGCSE - PYTHON
Note: in the result, the line breaks are inserted at the same position as in the
code.
Like many other popular programming languages, strings in Python are arrays of
bytes representing Unicode characters.
However, Python does not have a character data type, a single character is simply
a string with a length of 1. Square brackets can be used to access elements of the
string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1]) # returns "e"
Example
Substring. Get the characters from position 2 to position 5 (5 position not included):
b = "Hello, World!"
print(b[2:5]) # returns "llo"
print(b[2:5:2]) # returns "lo"
print(b[::-1]) # returns "!dlroW ,olleH"
Example The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
print(a.lstrip()) # returns "Hello, World! " Removes any whitespace from the beginning.
print(a.rstrip()) # returns " Hello, World!" Removes any whitespace from the end.
Example The title() Converts the first character of each word to upper case:
a = "hello, world!"
print(a.title())# returns "Hello, World!"
26
IGCSE - PYTHON
Example The count() Returns the number of times a specified value occurs in a string:
a = "hello, world!"
print(a.count("l")) # returns 3
Example The find() Searches the string for a specified value and returns the position of
where it was found:
a = "Hello, World!"
print(a.find("l")) # returns 2
print(a.find("l",4)) # returns 10
Example The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Format
Example
age = 36
txt = "My name is John, I am " + age
print(txt) # returns error
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them
in the string where the placeholders {} are:
The format() method takes unlimited number of arguments, and are placed into the
respective placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
27
IGCSE - PYTHON
You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
# returns "I want to pay 49.95 dollars for 3 pieces of item 567."
Example
quantity = 3
itemno = 567
price = 49.95
print(f"I want to pay {price} dollars for {quantity} pieces of item {itemno}.")
# returns "I want to pay 49.95 dollars for 3 pieces of item 567."
Note: All string methods returns new values. They do not change the original
string, because string are immutable in python.
Python Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
28
IGCSE - PYTHON
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
29
IGCSE - PYTHON
== Equal x == y
!= Not equal x != y
Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
30
IGCSE - PYTHON
<< Zero fill Shift left by pushing zeros in from the right and let the
left shift leftmost bits fall off
>> Signed Shift right by pushing copies of the leftmost bit in from
right shift the left, and let the rightmost bits fall off
Python List
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.
31
IGCSE - PYTHON
Access Items
You can loop through the list items by using a for loop:
List Length
To determine how many items a list has, use the len() method:
Add Items
To add an item to the end of the list, use the append() method:
32
IGCSE - PYTHON
Remove Item
Example The pop() method removes the specified index, (or the last item if index is not
specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist) # returns ['apple', 'banana']
Example The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only
be a reference to list1, and changes made in list1 will automatically also be
made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
33
IGCSE - PYTHON
List Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of
the current list
index() Returns the index of the first element with the specified
value
34
IGCSE - PYTHON
Python Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
You can access tuple items by referring to the index number, inside square
brackets:
Once a tuple is created, you cannot change its values. Tuples are unchangeable.
You can loop through the tuple items by using a for loop.
Tuple Length
35
IGCSE - PYTHON
To determine how many items a tuple has, use the len() method:
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can delete
the tuple completely:
Python Sets
A set is a collection which is unordered and unindexed. In Python sets are written
with curly brackets.
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Access Items
You cannot access items in a set by referring to an index, since sets are unordered
the items has no index.
36
IGCSE - PYTHON
But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
Example Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
Example Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
To determine how many items a set has, use the len() method.
print(len(thisset)) # returns 3
Remove Item
thisset.remove("banana")
37
IGCSE - PYTHON
thisset.discard("banana")
You can also use the pop(), method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not know
what item that gets removed.
x = thisset.pop()
Note: Sets are unordered, so when using the pop() method, you will not know
which item that gets removed.
del thisset
Python Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
38
IGCSE - PYTHON
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:
Change Values
You can change the value of a specific item by referring to its key name:
Example You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Example Loop through both keys and values, by using the items() function:
39
IGCSE - PYTHON
for x, y in thisdict.items():
print(x, y)
Dictionary Length
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Removing Items
Example The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Example The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):
40
IGCSE - PYTHON
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Example The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will
only be a reference to dict1, and changes made in dict1 will automatically also be
made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
41
IGCSE - PYTHON
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements"
and loops.
Example If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print to screen that "b is greater than a".
Indentation
42
IGCSE - PYTHON
Python relies on indentation, using whitespace, to define scope in the code. Other
programming languages often use curly-brackets for this purpose.
Elif
The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to screen
that "a is greater than b".
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
43
IGCSE - PYTHON
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if
statement.
If you have only one statement to execute, one for if, and one for else, you can put
it all on the same line:
You can also have multiple else statements on the same line:
And
Or
while loops
for loops
44
IGCSE - PYTHON
With the while loop we can execute a set of statements as long as a condition is
true.
The while loop requires relevant variables to be ready, in this example we need to
define an indexing variable, i, which we set to 1.
With the break statement we can stop the loop even if the while condition is true:
With the continue statement we can stop the current iteration, and continue with
the next:
This is less like the for keyword in other programming languages, and works more
like an iterator method as found in other object-orientated programming
languages.
45
IGCSE - PYTHON
With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc.
The for loop does not require an indexing variable to set beforehand.
With the break statement we can stop the loop before it has looped through all the
items:
Example Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
With the continue statement we can stop the current iteration of the loop, and
continue with the next:
46
IGCSE - PYTHON
The else keyword in a for loop specifies a block of code to be executed when the
loop is finished:
Example Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
47
IGCSE - PYTHON
for x in adj:
for y in fruits:
print(x, y)
Python Keywords
Python has a set of keywords that are reserved words that cannot be used as
variable names, function names, or any other identifiers:
Method Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed
no matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator
48
IGCSE - PYTHON
Python Functions
A function is a block of code which only runs when it is called.
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Parameters
Parameters are specified after the function name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname). When the
function is called, we pass along a first name, which is used inside the function to
print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
49
IGCSE - PYTHON
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
You can send any data types of parameter to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as a parameter, it will still be a List when it reaches the
function:
Example
def my_function(food):
for x in food:
print(x)
Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Recursion
Python also accepts function recursion, which means a defined function can call
itself.
Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data
to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip
into writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to programming.
50
IGCSE - PYTHON
Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one
expression.
Syntax
lambda arguments : expression
Example A lambda function that adds 10 to the number passed in as an argument, and print
the result:
x = lambda a : a + 10
print(x(5))
Example
A lambda function that multiplies argument a with argument b and print the result:
x = lambda a, b : a * b
print(x(5, 6))
Example A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that argument will
be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number you
send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
51
IGCSE - PYTHON
Or, use the same function definition to make a function that always triples the
number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Or, use the same function definition to make both functions, in the same program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Use lambda functions when an anonymous function is required for a short period of
time.
Create a Class
Create Object
52
IGCSE - PYTHON
The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.
All classes have a function called __init__(), which is always executed when the
class is being initiated.
Example Create a class named Person, use the __init__() function to assign values for name
and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being
used to create a new object.
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to
the object.
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Note: The self parameter is a reference to the current instance of the class, and
is used to access variables that belong to the class.
53
IGCSE - PYTHON
The self parameter is a reference to the current instance of the class, and is used
to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to
be the first parameter of any function in the class:
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Delete Objects
del p1
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties
from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
54
IGCSE - PYTHON
Any class can be a parent class, so the syntax is the same as creating any other
class:
Example Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname
method:
x = Person("John", "Doe")
x.printname()
To create a class that inherits the functionality from another class, send the parent
class as a parameter when creating the child class:
Example Create a class named Student, which will inherit the properties and methods from
the Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties or
methods to the class.
Now the Student class has the same properties and methods as the Person class.
Example Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
So far we have created a child class that inherits the properties and methods from
it's parent.
Note: The __init__() function is called automatically every time the class is being
used to create a new object.
55
IGCSE - PYTHON
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Now we have successfully added the __init__() function, and kept the inheritance
of the parent class, and we are ready to add functionality in
the __init__() function.
Python also have a super() function that will make the child class inherit all the
methods and properties from it's parent:
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
By using the super() function, you do not have to use the name of the parent
element, it will automatically inherit the methods and properties from it's parent.
Add Properties
Example Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another parameter
in the __init__() function:
56
IGCSE - PYTHON
Example Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
Add Methods
Example Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)
If you add a method in the child class with the same name as a function in the
parent class, the inheritance of the parent method will be overridden.
Python Iterators
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse
through all the values.
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
print(next(myit))
print(next(myit))
print(next(myit))
57
IGCSE - PYTHON
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
for x in mytuple:
print(x)
for x in mystr:
print(x)
The for loop actually creates an iterator object and executes the next() method for
each loop.
Create an Iterator
As you have learned in the Python Classes/Objects chapter, all classes have a
function called __init__(), which allows you do some initializing when the object
is being created.
The __iter__() method acts similar, you can do operations (initializing etc.), but
must always return the iterator object itself.
The __next__() method also allows you to do operations, and must return the next
item in the sequence.
58
IGCSE - PYTHON
Example Create an iterator that returns numbers, starting with 1, and each sequence will
increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
Stop Iteration
The example above would continue forever if you had enough next() statements, or
if it was used in a for loop.
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
59
IGCSE - PYTHON
Python Scope
A variable is only available from inside the region it is created. This is called scope.
Local Scope
A variable created inside a function belongs to the local scope of that function, and
can only be used inside that function.
myfunc()
As explained in the example above, the variable x is not available outside the
function, but it is available for any function inside the function:
Example The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Global Scope
A variable created in the main body of the Python code is a global variable and
belongs to the global scope.
Global variables are available from within any scope, global and local.
Example A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
60
IGCSE - PYTHON
Naming Variables
If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global scope
(outside the function) and one available in the local scope (inside the function):
Example The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Global Keyword
If you need to create a global variable, but are stuck in the local scope, you can
use the global keyword.
Example If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300
myfunc()
print(x)
Also, use the global keyword if you want to make a change to a global variable
inside a function.
Example To change the value of a global variable inside a function, refer to the variable by
using the global keyword:
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
61
IGCSE - PYTHON
Python Modules
What is a Module?
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Use a Module
Now we can use the module we just created, by using the import statement:
Example Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
Example Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
62
IGCSE - PYTHON
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
There are several built-in modules in Python, which you can import whenever you
like.
x = platform.system()
print(x)
There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:
Example List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create
yourself.
You can choose to import only parts from a module, by using the from keyword.
Example The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
63
IGCSE - PYTHON
print (person1["age"])
Reloading modules
reload() reloads a previously imported module. This is useful if you have edited
the module source file using an external editor and want to try out the new version
without leaving the Python interpreter. The return value is the module object.
Note: The argument should be a module which has been successfully imported.
Usage:
For Python2.x
reload(module)
For >=Python3.4
import importlib
importlib.reload(module)
64
IGCSE - PYTHON
Types of namespace
Built-in Namespace It includes functions and exception names that are
built-in in the python.
Global Namespace It includes the names from the modules that are
imported in the code. It lasts till the end of program.
Local Namespace It includes the names defined in the function. It is
created when the function is called and ends when the value returned.
65
IGCSE - PYTHON
The names in the enclosing scope are visible from the code of the inner and
enclosing functions.
Built-in scope
It is a special scope which is created or loaded at script run or opens an
interactive session.
This scope contains names such as keywords, functions, exceptions, and
other attributes that are built into Python.
Names in this scope are also available from everywhere in your code.
Example
var1 = 5 #var1 is in the global namespace
def ABC( ):
var2 = 6 # var2 is in the local namespace
def XYZ( ):
var3 = 7 # var3 is in the nested local namespace
66
IGCSE - PYTHON
A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.
Example Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
Date Output
When we execute the code from the example above the result will be:
2019-09-24 15:35:35.403417
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date
object.
Here are a few examples, you will learn more about them later in this chapter:
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month,
day.
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime() class also takes parameters for time and timezone (hour, minute,
second, microsecond, tzone), but they are optional, and has a default value of 0,
(None for timezone).
67
IGCSE - PYTHON
The datetime object has a method for formatting date objects into readable
strings.
The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string:
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%Z Timezone CST
68
IGCSE - PYTHON
%% A % character %
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and
except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
Example The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
69
IGCSE - PYTHON
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a
special block of code for a special kind of error:
Example Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else
You can use the else keyword to define a block of code to be executed if no errors
were raised:
Example In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
The finally block, if specified, will be executed regardless if the try block raises an
error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
70
IGCSE - PYTHON
except:
print("Something went wrong when opening the file")
The program can continue, without leaving the file object open.
Raise an exception
if x < 0:
raise Exception("Sorry, no numbers below zero")
You can define what kind of error to raise, and the text to print to the user.
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
71
IGCSE - PYTHON
"a" - Append - Opens a file for appending, creates the file if it does not 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
"r+" To read and write data into the file. The previous data in the file will not be deleted
"a+" To append and read data from the file. It won’t override existing data
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to
specify them.
Note: Make sure the file exists, or else you will get an error.
Assume we have the following file, located in the same folder as Python:
demofile.txt
The open() function returns a file object, which has a read() method for reading
the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
72
IGCSE - PYTHON
If the file is located in a different location, you will have to specify the file path, like
this:
By default the read() method returns the whole text, but you can also specify how
many characters you want to return:
Read Lines
By calling readline() two times, you can read the two first lines:
By looping through the lines of the file, you can read the whole file, line by line:
Example
Return all lines in the file, as a list where each line is an item in the list object:
f = open("demofile.txt", "r")
print(f.readlines())
Close Files
It is a good practice to always close the file when you are done with it.
Example Close the file when you are finish with it:
73
IGCSE - PYTHON
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Note: You should always close your files, in some cases, due to buffering, changes
made to a file may not show until you close the file.
To write to an existing file, you must add a parameter to the open() function:
Example Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example Create a file called "myfile.txt":
f = open("myfile.txt", "x")
74
IGCSE - PYTHON
To delete a file, you must import the OS module, and run its os.remove() function:
To avoid getting an error, you might want to check if the file exists before you try
to delete it:
Example Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
With statement
with statement in Python is used in exception handling to make the code cleaner
and much more readable. It simplifies the management of common resources like
file streams. Unlike the above implementations, there is no need to
call file.close() when using with statement. The with statement itself ensures
proper acquisition and release of resources.
# Creating a file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes
75
IGCSE - PYTHON
Output:
Hello
This is Delhi
This is Paris
This is London
The tell() method returns the current file position in a file stream.
Tip: You can change the current file position with the seek method.
The seek() method sets the current file position in a file stream.
The arguments that are given after the name of the program in the command line
shell of the operating system are known as Command Line Arguments. Python
provides various ways of dealing with these types of arguments. The three most
common are:
Using sys.argv
Using getopt module
Using argparse module
76
IGCSE - PYTHON
Using sys.argv
The sys module provides functions and variables used to manipulate different parts
of the Python runtime environment. This module provides access to some variables
used or maintained by the interpreter and to functions that interact strongly with
the interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:
Example Let’s suppose there is a Python script for adding two numbers and the numbers
are passed as command-line arguments.
77
IGCSE - PYTHON
Example
78
IGCSE - PYTHON
Note: As a default optional argument, it includes -h, along with its long version –
help.
79
IGCSE - PYTHON
NumPy Basics
What is NumPy?
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and
matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and
you can use it freely.
NumPy stands for Numerical Python.
80
IGCSE - PYTHON
Installation of NumPy
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.
Install it using this command:
C:\Users\Your Name>pip install numpy
If this command fails, then use a python distribution that already has NumPy
installed like, Anaconda, Spyder etc.
Import NumPy
Once NumPy is installed, import it in your applications by adding
the import keyword:
import numpy
Now NumPy is imported and ready to use.
Example
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same thing.
Create an alias with the as keyword while importing:
import numpy as np
Now the NumPy package can be referred to as np instead of numpy.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
81
IGCSE - PYTHON
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
Nested array: are arrays that have arrays as their elements.
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-
D array.
Example Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the most common and basic arrays.
Example Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
NumPy has a whole sub module dedicated towards matrix operations
called numpy.mat
Example Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
82
IGCSE - PYTHON
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
Example Create a 3-D array with two 2-D arrays, both containing two arrays with the values
1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
83
IGCSE - PYTHON
The indexes in NumPy arrays start with 0, meaning that the first element has index
0, and the second has index 1 etc.
Example Get the first element from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
Example Get the second element from the following array.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[1])
Example Get third and fourth elements from the following array and add them.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[2] + arr[3])
Example Explained
arr[0, 1, 2] prints the value 6.
And this is why:
The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]
84
IGCSE - PYTHON
The second number represents the second dimension, which also contains two
arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]
The third number represents the third dimension, which contains three values:
4
5
6
Since we selected 2, we end up with the third value:
6
Negative Indexing
Use negative indexing to access an array from the end.
Example Print the last element from the 2nd dim:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1])
85
IGCSE - PYTHON
Negative Slicing
Use the minus operator to refer to an index from the end:
Example Slice from the index 3 from the end to index 1 from the end:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
STEP
Use the step value to determine the step of the slicing:
Example Return every other element from index 1 to index 5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])
Example Return every other element from the entire array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[::2])
86
IGCSE - PYTHON
87
IGCSE - PYTHON
If a type is given in which elements can't be casted then NumPy will raise a
ValueError.
ValueError: In Python ValueError is raised when the type of passed argument to a
function is unexpected/incorrect.
Example A non-integer string like 'a' cannot be converted to integer (will raise an error):
import numpy as np
arr = np.array(['a', '2', '3'], dtype='i')
88
IGCSE - PYTHON
COPY:
Example Make a copy, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
The copy SHOULD NOT be affected by the changes made to the original array.
VIEW:
Example Make a view, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr)
print(x)
The view SHOULD be affected by the changes made to the original array.
89
IGCSE - PYTHON
90
IGCSE - PYTHON
Unknown Dimension
You are allowed to have one "unknown" dimension.
Meaning that you do not have to specify an exact number for one of the dimensions
in the reshape method.
Pass -1 as the value, and NumPy will calculate this number for you.
Example Convert 1D array with 8 elements to 3D array with 2x2 elements:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
newarr = arr.reshape(2, 2, -1)
print(newarr)
Note: We can not pass -1 to more than one dimension.
91
IGCSE - PYTHON
92
IGCSE - PYTHON
93
IGCSE - PYTHON
94
IGCSE - PYTHON
95
IGCSE - PYTHON
96
IGCSE - PYTHON
Search Sorted
There is a method called searchsorted() which performs a binary search in the
array, and returns the index where the specified value would be inserted to
maintain the search order.
The searchsorted() method is assumed to be used on sorted arrays.
Example Find the indexes where the value 7 should be inserted:
import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7)
print(x)
Example explained: The number 7 should be inserted on index 1 to remain the sort
order.
The method starts the search from the left and returns the first index where the
number 7 is no longer larger than the next value.
97
IGCSE - PYTHON
Example explained: The number 7 should be inserted on index 2 to remain the sort
order.
The method starts the search from the right and returns the first index where the
number 7 is no longer less than the next value.
Multiple Values
To search for more than one value, use an array with the specified values.
Example Find the indexes where the values 2, 4, and 6 should be inserted:
import numpy as np
arr = np.array([1, 3, 5, 7])
x = np.searchsorted(arr, [2, 4, 6])
print(x)
98
IGCSE - PYTHON
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)
Example Create a filter array that will return only even elements from the original array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
# Create an empty list
filter_arr = []
# go through each element in arr
for element in arr:
# if the element is completely divisble by 2, set the value to True,
otherwise False
if element % 2 == 0:
filter_arr.append(True)
else:
filter_arr.append(False)
99
IGCSE - PYTHON
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)
numpy.arange() in Python
The arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced
elements as per the interval. The interval mentioned is half-opened i.e. [Start, Stop)
Parameters :
start : [optional] start of interval range. By default start = 0
stop : end of interval range
step : [optional] step size of interval. By default step size = 1,
For any output out, this is the distance between two adjacent values,
out[i+1] - out[i].
dtype : type of output array
Example:
import numpy as np
print("A\n", np.arange(4).reshape(2, 2), "\n")
print("A\n", np.arange(4, 10), "\n")
print("A\n", np.arange(4, 20, 3), "\n")
100
IGCSE - PYTHON
numpy.eye() in Python
numpy.eye(R, C = None, k = 0, dtype = type <‘float’>) : –The eye tool returns
a 2-D array with 1’s as the diagonal and 0’s elsewhere. The diagonal can be main,
upper, or lower depending on the optional parameter k. A positive k is for the upper
diagonal, a negative k is for the lower, and a 0 k (default) is for the main diagonal.
Parameters :
R : Number of rows
C : [optional] Number of columns; By default M = N
k : [int, optional, 0 by default]
Diagonal we require; k>0 means diagonal above main diagonal or vice
versa.
dtype : [optional, float(by Default)] Data type of returned array.
Example:
import numpy as np
# 2x2 matrix with 1's on main diagonal
b = np.eye(2, dtype = float)
print("Matrix b : \n", b)
101
IGCSE - PYTHON
Related to Python
eval() Function
The eval() function evaluates the specified expression, if the expression is a legal
Python statement, it will be executed.
swapcase() Method
The swapcase() method returns a string where all the upper case letters are lower
case and vice versa.
x='upciss'
p=x.swapcase()
print(p)
UPCISS
The join() method takes all items in an iterable and joins them into one string.
l=['welcome','to','upciss']
msg=' '.join(l)
print(msg)
welcome to upciss
The partition() method searches for a specified string, and splits the string into a
tuple containing three elements.
The first element contains the part before the specified string.
102
IGCSE - PYTHON
startswith(), endswith()
l='welcome to upciss'
msg=l.startswith('welcome')
print(msg)
True
ceil, floor, trunc function
import math
k=45.1
print(math.ceil(k)) #return 46 integer not greater than k
k=45.59
print(math.floor(k)) #return 45 integer greater than or equal to k
k=45.59
print(math.trunc(k)) #return 45 simply remove the decimals
DocString
def add(a,b):
"""add 2 number and print with f String method"""
print(f'Total : {a+b}')
add(4,5) # return 9
print(add.__doc__) # return add 2 number and print with f String method
103