Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Basic Features

Learning Goals

By the end of this section you will:

  • remembered the basics of Python that have been covered in previous courses.

Algorithms

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.

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.


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.

The Python data types that we will be using are:

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 FalseEvaluate to True
None
False
0 (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.14
Non-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:

Falsy

Scope: Local and Global Variables

When writing code, scope means where in your program a variable can be used.

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:

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

ActionIn Global CodeIn a Function (Local Code)In a Nested Function
Use global variablesYesYesYes
Change global variablesYesNo (unless global)No (unless global)
Use local variablesNoYes (its own only)Yes (its own only)
Change built-in names (not recommended)YesYes (while running)Yes (while running)
Use variables from the enclosing functionN/AN/AYes
Change variables from the enclosing functionN/AN/ANo (unless nonlocal)

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:

OperatorCondition example
Equalsa == b
Not Equalsa != b
Less thana < b
Less than or equal toa <= b
Greater thana > b
Greater than or equal toa >= 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.

ComponentFeatures
ifMust come first
Only one allowed
Always required
elifComes after if and before else
Optional
Can have as many as needed
Runs only if all conditions above are False
elseMust come last
Optional
Only one allowed
Runs only if all previous conditions are False

W3Schools: if...elif...else refresher

statement

Iteration

Iteration means repeating a block of code. This is also called a loop. There are two main types:

Python has two loop types

Loop typeFeatures
while loopChecks the condition first
Repeats while the condition is True
Is used for infinite loops
W3Schools: while loop refresher
for loopLoops 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

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 structureFeatures
ListsOrdered collection of items
Created using square brackets [] with items separated by commas
Example: [1, 2, 3, 4]
Items can be changed, added, or removed (mutable)
Each item has an index, starting at 0
Lists refresher
TuplesOrdered collection like lists, but cannot be changed (immutable)
Created using parentheses () with items separated by commas
Example: (1, 2, 3, 4)
Good for fixed data and faster performance
Indexing starts at 0
Tuples refresher
SetsCollection of unique items with no specific order
Created using curly braces {} with items separated by commas
Example: {1, 2, 3, 4}
Mutable — you can add or remove items
Useful when you care about presence, not order or duplicates
Sets refresher
DictionariesCollection of key-value pairs
Created using curly braces {}, with a colon : between each key and value
Example: {"Doh": "Doherty", "Fly": "Flynn"}Keys must be unique
Useful when each value has a unique label or ID
Mutable — values can be added, updated, or deleted
Dictionary refresher

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.

Python syntax refresher


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:

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:

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.


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:

Python operations refresher

Arithmetic Operators

Used to do basic maths with numbers.

OperatorActionExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulus (remainder)x % y
**Exponentiationx ** 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.

OperatorExampleSame As
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
//=x //= 3x = x // 3
**=x **= 3x = x ** 3

Comparison Operators

Used to compare values and return True or False.

OperatorActionExample
==Equalx == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Logical Operators

logic gates

Used to combine or modify condition results.

OperatorDescriptionExample
andTrue if both are Truex < 5 and x < 10
orTrue if at least one is Truex < 5 or x < 3
notReverses the resultnot(x < 5)

Identity Operators

Check whether two variables are actually the same object in memory.

OperatorDescriptionExample
isTrue if same objectx is y
is notTrue if not same objectx is not y

Membership Operators

Check if a value exists in a sequence like a list or string.

OperatorDescriptionExample
inTrue if value is present'a' in 'apple'
not inTrue if value is not present5 not in [1, 2, 3]

Bitwise Operators

Used with binary numbers. Rarely needed in basic Python, but good to know they exist.

OperatorNameDescription
&AND1 if both bits are 1
|OR1 if at least one bit is 1
^XOR1 if bits are different
~NOTFlips all bits
<<Left shiftMoves bits left, adds 0s on the right
>>Right shiftMoves bits right, keeps leftmost bit