Learning Goals
By the end of this section you will:
remembered the basics of Python that have been covered in previous courses.
Algorithms¶

Algorithms are the commands that make up our programs.
There are 6 basic building blocks that an algorithm consists of. Each of them serve a particular purpose.
Sequence: a number of instructions that are processed one after the other.
Assignment: used to store the value of an expression into a variable.
Condition: the way that a computer asks a question which can only generate two possible responses:
True(yes) orFalse(no).Selection: a statement that uses a condition to select, or determine, whether the next line of the program is to be executed.
Iteration: the repetition of a number of instructions. These are generally referred to as loops and refer to a section of code that is repeated.
Modularisation: refers to the process of breaking a large, unwieldy programming task into separate, smaller, more manageable subtasks or modules. Individual modules can then be cobbled together like building blocks to create a larger application.
In designing your algorithm, you will need to decide how to arrange these building block to achieve you outcome. To do this it is wise to follow good programming practices.
Algorithms Activities
What is the purpose of an algorithm in a program?
What does the sequence building block do in an algorithm?
How does assignment work in a program? What is the role of a variable?
What is the difference between condition and selection in an algorithm?
How is iteration different from sequence?
Give an example of a simple algorithm that uses selection and iteration.
Why is modularisation important when designing large programs?
Which building block(s) would you use to design a quiz program that gives feedback after each question? Why?
What could go wrong if you forget to use modularisation in a large project?
Variables¶
Variables are the names you give to computer memory locations which are used to store values in a computer program. Variables can store data of different types, and different variable types can do different things.
Variable Types¶
Variable can be of different types. The type of a variable indicates what kind of data is stored at that memory location.
Dynamic vs Static Variables
In programming languages, there are two different type variable systems:
dynamic: type checking only occurs as the code runs, and the type of a variable is allowed to change over its lifetime.
static: type checks are performed without running the program. In most statically typed languages this is done as your program is compiled. The type of a variable is not allowed to change over its lifetime.
Python is a dynamically typed language. This means that you can store any type of data in a variable, irrespective of the type of data that is already stored there.
The Python data types that we will be using are:
Strings:
strings are sequences of character data
the string type in Python is called
strstring literals may be delimited using either single or double quotes
Integers:
integers are whole numbers
the integer type in Python is called
intthere is effectively no limit to how long an integer value can be, but it is constrained by the amount of memory your system has.
Floating-Point Numbers:
float values are numbers specified with a decimal point
the
floattype in Python designates a floating-point numberoptionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation
Boolean Type:
objects of Boolean type may have one of two values,
TrueorFalsethe Boolean type in Python is called
boola value that is true in Boolean context is sometimes said to be “truthy” and one that is false in Boolean context is said to be “falsie”
the “truthiness” of an object of Boolean type is self-evident: Boolean objects that are equal to
Trueare truthy (true), and those equal toFalseare falsy (false)
Truthiness and Falseness of Variables¶
In Python, variables have an associated truthiness (evaluated as True) or falseness (evaluated as False) when used in a Boolean context like an if statement.
Falsy values in Python
Evaluate to False | Evaluate to True |
|---|---|
NoneFalse0 (all numeric types, e.g. 0, 0.0, 0j)'' or "" (empty string)[] (empty list){} (empty dictionary)set() (empty set)() (empty tuple)range(0) | Everything else including: Non-zero numbers: 1, -5, 3.14Non-empty strings: "hello"Non-empty lists [1]Non-empty tuples (0,)Non-empty sets {1}Non-empty dicts {'a': 1} |
For example, the following code:
if []:
print("Truthy")
else:
print("Falsy")outputs:
FalsyScope: Local and Global Variables¶
When writing code, scope means where in your program a variable can be used.
Global variables are made outside of functions and can be used anywhere in your code.
Local variables are made inside functions and can only be used inside those functions.
Older languages like BASIC didn’t use local variables, so every part of the program could change any variable at any time. This made debugging hard.
Modern languages like Python use scope to avoid problems like this. In Python, you can’t use a variable everywhere unless it’s global. Where you create the variable decides where you’re allowed to use it. This helps keep your code more organised and easier to manage.
Python Scope and the LEGB Rule
Python follows a rule called LEGB to figure out which variable to use when you refer to a name. LEGB stands for:
Local – Variables made inside a function. Only that function can use them. Each time the function runs, a new local scope is created.
Enclosing – Variables made in outer functions, when you have functions inside functions. The inner function can use these variables, but can’t change them unless declared
nonlocal.Global – Variables made at the top of your program. They can be used anywhere, but only changed inside a function if declared
global.Built-in – Variables and functions that come with Python, like
print()orlen(). These are always available.
Python checks for a name in this order: Local → Enclosing → Global → Built-in. If it finds the name, it stops there. If not, it gives an error.
What You Can Do in Different Scopes
| Action | In Global Code | In a Function (Local Code) | In a Nested Function |
|---|---|---|---|
| Use global variables | Yes | Yes | Yes |
| Change global variables | Yes | No (unless global) | No (unless global) |
| Use local variables | No | Yes (its own only) | Yes (its own only) |
| Change built-in names (not recommended) | Yes | Yes (while running) | Yes (while running) |
| Use variables from the enclosing function | N/A | N/A | Yes |
| Change variables from the enclosing function | N/A | N/A | No (unless nonlocal) |
Variable Activities
What is a variable used for in a computer program?
What does the type of a variable indicate?
What is the difference between dynamic and static variable types?
Why is Python described as a dynamically typed language?
How are string values written in Python?
What type in Python is used for whole numbers?
What Python type represents numbers with a decimal point?
What are the two possible values of the Boolean type in Python?
What does “truthy” and “falsy” mean in Python?
Name three values in Python that evaluate to
False.What will the following code output?
if []: print("Truthy") else: print("Falsy")What does scope mean in programming?
What is the difference between a global and a local variable?
How does Python use scope to help manage code?
What does each letter in the LEGB rule stand for?
In what order does Python look for a variable using the LEGB rule?
What happens if you create a function with the same name as a built-in like
print?Can you change a global variable inside a function without declaring it
global?Can a nested function change a variable from its enclosing function without using
nonlocal?What kind of variables are available everywhere in your program?
Control Structures¶
Flow of control through any given function is implemented with three basic types of control structures:
Sequential¶
Sequential code runs line by line from top to bottom. The program starts with the first line, then moves to the next, and keeps going in order until it finishes.
Conditions¶
A condition is how a computer checks if something is true or false. It’s like asking a yes/no question. The answer will always be either True or False.
In Python, conditions are used in if and while statements. They follow this pattern: value operator value
There are six main comparison operators in Python:
| Operator | Condition example |
|---|---|
| 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 |
Selection¶
Selection is when a program makes a choice between different paths based on a condition. Only one path is taken — the others are skipped. After the selected path runs, the program continues with the next line after the selection block. This is also called branching, like how a tree or river splits into different directions.
Python has two main types of branching:
statements
This type checks conditions in order and chooses one path to run.
| Component | Features |
|---|---|
if | Must come first Only one allowed Always required |
elif | Comes after if and before elseOptional Can have as many as needed Runs only if all conditions above are False |
else | Must come last Optional Only one allowed Runs only if all previous conditions are False |
W3Schools: if...elif...else refresher
statement
Checks a variable against different fixed values
Similar to
switchin other languagesAdded in Python 3.10
Iteration¶
Iteration means repeating a block of code. This is also called a loop. There are two main types:
Indefinite iteration – used when you don’t know how many times the loop will run
Pre-test loop (
whileloop): checks the condition before running the codePost-test loop (like
do...whilein other languages): runs the code then checks the condition — Python does not have this type
Definite iteration – used when you know how many times to run
Counted loop (
forloop): repeats for a fixed number of times or through each item in a sequence
Python has two loop types
| Loop type | Features |
|---|---|
while loop | Checks the condition first Repeats while the condition is TrueIs used for infinite loops W3Schools: while loop refresher |
for loop | Loops through a sequence (like a list or range) Uses each item one at a time Stops when there are no more items W3Schools: for loop refresher |
What is an iterable?
In Python, an iterable is a container you can move through one item at a time, like going through pages in a book. Built-in iterables include lists, tuples, strings, dictionaries, and sets.
Control Structures Activities
What are the three basic types of control structures in programming?
How does sequential code execute?
What is a condition in programming?
What kind of answer does a condition always give?
What Python statements commonly use conditions?
What pattern do Python conditions follow?
What operator would you use to test if two values are not equal?
Which operator checks if one value is greater than or equal to another?
What is selection in programming?
What is another name for selection?
How does Python decide which path to follow in an
if ... elif ... elseblock?Can you have more than one
elifin a selection block?What happens if none of the
iforelifconditions are true and there’s noelse?What does the
elseblock do?What does the
match casestatement do in Python?Which version of Python introduced
match case?What is iteration in programming?
What is another word for iteration?
What is the difference between definite and indefinite iteration?
What kind of loop is used when you know how many times to repeat?
What kind of loop is used when the number of repetitions is unknown?
Which type of loop does Python not support?
What type of loop is used for infinite loops in Python?
What does a
forloop do with items in a sequence?What is an iterable in Python?
Name three built-in Python types that are iterables.
Data Structures¶
Data structures are used to store data in an organized form. No matter what problem are you solving, in one way or another you have to deal with data — whether it’s an employee’s salary, stock prices, a grocery list, or even a simple telephone directory. ulhaq_2018_the
The easiest way to understand data structures is to see them as collections of related data — like a list of shopping items or a group of contacts with phone numbers. In fact they are frequently referred to as collections.
In Python, we commonly use these four data structures:
| Data structure | Features |
|---|---|
| Lists | Ordered collection of items Created using square brackets [] with items separated by commasExample: [1, 2, 3, 4]Items can be changed, added, or removed (mutable) Each item has an index, starting at 0 Lists refresher |
| Tuples | Ordered collection like lists, but cannot be changed (immutable) Created using parentheses () with items separated by commasExample: (1, 2, 3, 4)Good for fixed data and faster performance Indexing starts at 0 Tuples refresher |
| Sets | Collection of unique items with no specific order Created using curly braces {} with items separated by commasExample: {1, 2, 3, 4}Mutable — you can add or remove items Useful when you care about presence, not order or duplicates Sets refresher |
| Dictionaries | Collection of key-value pairs Created using curly braces {}, with a colon : between each key and valueExample: {"Doh": "Doherty", "Fly": "Flynn"}Keys must be uniqueUseful when each value has a unique label or ID Mutable — values can be added, updated, or deleted Dictionary refresher |
Data Structures Activities
What is a data structure used for?
How can data structures be understood in simple terms?
What are the four common data structures in Python?
What type of collection is a list?
How is a list created in Python?
What does it mean that lists are mutable?
What index does Python start counting from in a list?
What is one key difference between a list and a tuple?
Why are tuples good for fixed data?
How is a tuple created in Python?
What is a set in Python?
What makes sets different from lists and tuples?
Can you add or remove items from a set?
Why might you use a set instead of a list?
What is stored in a dictionary in Python?
How is a dictionary written in Python?
What must be true about the keys in a dictionary?
Can you update the values in a dictionary?
What is syntax in programming?
Why is syntax important in Python?
Syntax¶
Syntax is the set of rules a programming language follows to write commands properly. It decides which combinations of words, symbols, and punctuation are valid in that language.
Libraries¶
A library is a collection of code — like functions, modules, or scripts — that you can use in your own programs. Python includes a standard library with many useful tools. You can also install extra libraries using pip, or even create your own.
Classes¶
In object-oriented programming, a class is a blueprint for creating objects. It defines the attributes (data) and methods (actions) that all objects of that type share.
For example, a Car class might include:
attributes like
colourandwheelsmethods like
drive()andbrake()
You can then create many car objects from that one class, like ferrari = Car().
A Truck class might share some features with Car but have differences. Both could inherit from a more general Vehicle class, which contains shared code. This avoids repeating code while still allowing for differences.
Inside a class:
attributes store data, like
speedorsizemethods perform actions, like
drive()orturn_left()
To use a method, you create an object and call it like this:
ferrari.drive(distance)
We covered classes and object-oriented programming in the Deepest Dungeon course.
Classes Activities
What is a class in object-oriented programming?
What two things does a class define?
What is an attribute in a class?
What is a method in a class?
Give two examples of attributes in a
Carclass.Give two examples of methods in a
Carclass.What is the purpose of using a class like
Car?How do you create an object from a class?
What does the line
ferrari = Car()do?What is one benefit of having a
Truckclass inherit from aVehicleclass?What does inheritance help you avoid?
What does the method call
ferrari.drive(distance)do?Why might a
Truckclass share code with aCarclass?How are objects related to classes?
Where did we cover classes and object-oriented programming?
Operations¶
Operators are symbols used to perform actions on variables or values in Python. These actions can include math, comparisons, logic checks, and more.
Python includes several types of operators:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators¶
Used to do basic maths with numbers.
| Operator | Action | Example |
|---|---|---|
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x / y |
% | Modulus (remainder) | x % y |
** | Exponentiation | x ** y |
// | Floor division (whole number result) | x // y |
Note: brackets () work just like in maths to control order.
Assignment Operators¶
Used to assign or update the value of a variable.
| Operator | Example | Same As |
|---|---|---|
= | 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 |
Comparison Operators¶
Used to compare values and return True or False.
| Operator | Action | Example |
|---|---|---|
== | Equal | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Logical Operators¶

Used to combine or modify condition results.
| Operator | Description | Example |
|---|---|---|
and | True if both are True | x < 5 and x < 10 |
or | True if at least one is True | x < 5 or x < 3 |
not | Reverses the result | not(x < 5) |
Identity Operators¶
Check whether two variables are actually the same object in memory.
| Operator | Description | Example |
|---|---|---|
is | True if same object | x is y |
is not | True if not same object | x is not y |
Membership Operators¶
Check if a value exists in a sequence like a list or string.
| Operator | Description | Example |
|---|---|---|
in | True if value is present | 'a' in 'apple' |
not in | True if value is not present | 5 not in [1, 2, 3] |
Bitwise Operators¶
Used with binary numbers. Rarely needed in basic Python, but good to know they exist.
| Operator | Name | Description |
|---|---|---|
& | AND | 1 if both bits are 1 |
| | OR | 1 if at least one bit is 1 |
^ | XOR | 1 if bits are different |
~ | NOT | Flips all bits |
<< | Left shift | Moves bits left, adds 0s on the right |
>> | Right shift | Moves bits right, keeps leftmost bit |
Operations Activities
What is an operator in Python used for?
Name three types of Python operators.
What do arithmetic operators do?
What does the
+operator do?What is the result of
x // y?What is the purpose of parentheses
()in arithmetic expressions?What does the
**operator do?What does an assignment operator do?
What does
x += 3mean?What is the difference between
=and+=?What does a comparison operator return?
What does the
!=operator check for?What is the result of
x >= yif x is 5 and y is 3?What is the
andoperator used for?What does
not(x < 5)do?What will
x < 5 or x < 3return ifx = 4?What do identity operators check?
What does
x is ymean in Python?What is the result of
x is not yif x and y point to different objects?What does the
inoperator check?What does
'a' in 'apple'return?When would
not inbe used?What will
5 not in [1, 2, 3]return?