CS1026 Notes
CS1026 Notes
Computer Programs
Input: receive data from a file, keyboard, network
Process: perform computations on that data, such as addition, subtraction
Output: place that data somewhere, such as a file, screen
An algorithm is
1. Unambiguous: No “assumptions are required to execute the algorithm. The algorithm
uses precise instructions
2. Executable: The algorithm can be carried out in practice
3. Terminating: The algorithm will eventually come to an end, stop or halt
Basic Definitions
Statement: a single line of code that represents an instruction the program will carry out
Expression: code that returns a value when evaluated (commonly part of a larger statement)
Operation: special symbols or keywords that designate some type of computation (e.g. =, *)
Variable: containers for storing data values and references to objects
Function: a reusable block of code with defined inputs and outputs (e.g. int, input, print)
Comment: a human-readable note that is ignored by the computer
Variable Identifiers
- An identifier is a name given to variables or functions
1. Case sensitive
2. Must start with a letter or underscore
3. Can only contain letters, digits, or underscores
4. Can not be identical to a built-in keyword (e.g. False, and, from)
Constants
- Constants are variables whose value should never change after its initial value is set
- Use SCREAMING_SNAKE_CASE for constants
- E.g. BOTTLE_VOLUME = 2.5
Data Types
- One variable can be assigned values of different types
Built-In Types
int: Used for whole numbers
float: Used for real numbers (with decimal points)
booL: Stores a True or False Value
str (string): Used for text
list: Used to store a collection of items of any type
set: Unordered collection of unique elements
Casting
- Converting values from one type to another
- Can be either Implicit or Explicit
- Implicit casting occurs automatically when some operation is performed on an object
- Explicit casting requires the programmer to manually used a built-in data type functions
(int(), float(), str())
- Use when you wish to input a numerical value but the input() function returns a
string, and when you wish to add a numerical value to a string but strings can not
be added to numerical types
Assignment Operator
- The value of the expression on the right is evaluated and the result is stored in the
variable on the left
- Arithmetic operators follow a set order of operations: PEMDAS
+=: e.g. x+= 5 (shorthand for x = x + 5)
//: Integer Divison; the left expression divided by the right expression e.g. 10 // 4 = 2
**: Exponentiation: The left expression raised to the power of the right expression
-x: Negation: The value of x but with the opposite sign (+/-)
%: Modulo: The remainder of the left expression divided by right expression e.g. 10 % 2 = 0
Modules
- A python module is a file containing Python code, such as functions, classes, and
variables
Week 2 Videos
Strings: immutable (non-changeable) sequences of characters that store text (letters, digits,
symbols)
- String literals are always surrounded by quotation marks
Escape Sequences
- Used to represent special characters within strings, starts with a backslash (\)
String Length
- The built-in len() function takes a collection or sequence value and returns the length of
that value
String Indexing
- Uses brackets [] after the variable name that contains the index of the character we want
String Methods
- Methods define the behaviours of objects or the actions we can perform on them
- E.g. s = “all lower case” s = s.upper() print (s)
Docstrings
- Used to document a module (file), function, method, or class (in addition to comments0
Surrounded by triple quotes: “ “ “
Comparison Operators: used to compare two values and return a Boolean (True or False) value
Logical Operators: used on Boolean statements (either True or False)
Order of Evaluation
E.g. A student can only pass if 1) their average is over 65 2) they submitted 2 or more
assignments and 3) they attended at least 5 lectures or 4 labs
Let’s say: Average = 72.5 Assignments = 2 Class_attended = 3 Labs_attended = 9
Average > 65 and assignments >2= 2 and (attended >=5 or labs_attended >= 4)
*must use parentheses when applying to “or”
= True and True and True = True
Chain Comparisons
(a < b and b <a) equal to a < b < c
Membership Operators
in: Returns True if the target value is present in a collection of values. Otherwise, returns False
not in: Returns True if the target value is not present in a given collection of values. Otherwise, it
returns False
e.g. “hello” in “Hello World” = False (lowercase “h”)
Week 3 Videos
String Formatting and Advanced print ()
Advanced print()
- Can change what character(s) the print() command prints after a line by using the end=
argument
- e.g. (no line breaks):
print(“A”, “B”, “C”, “D”, end=””). Replaces the line break with an empty string
- /n: line break
- sep=””: double space
- sep=”-”: separates the items with a dash
F-string Basics
- F-strings start with a f and values can be interpolated directly in the string by surrounding
them with brackets {}
- e.g. print(f”Hello{name}, you are {age} years old and have an account balance of $
{money} as of today.”)
Format Specifiers
- Can specify how many digits a floating-point value should have
:.2f = causes value to be rounded to two decimal places
% String Interpolation
- Replaces placeholder with variable values
- %s: String
- %d: Integer
- %.2f: Floating point number
While Loop
Loop Basics
- Loops are control structures that allow us to iterate over the same block of code multiple
times
- 2 types of iteration
- Indefinite Iteration: the number of times the loop is executed isn’t set in advance.
The block of code is executed repeatedly until a condition it met
- Defintie Iteration: the number of times the block code will be executed is set
explicitly at the time the loop starts
- 2 types of loops
- While Loops: Repeatedly executes a block of code as long as a specified
condition remains true, typically used for indefinite iteration
- For Loop: Iterates over a sequence of elements, such as characters in a
string/list/range
While Loops
Syntax:
while condition:
# statements to execute
e.g.
print(“Counting from 1 to 10:”) Output:
count = 1 Counting from 1 to 10:
while count <= 10: 1
print(count) 2
count += 1 …
10
Infinite Loops
- Common error: A condition that is never False causes an infinite loop
Sentinel Values
- A special value used to signal the end of a loop, especially in situations where the
number of iterations isn’t known in advance
.strip(): removes any trailing or leading space
For Loops: Best for iterating over a known sequence of items (e.g. lists, strings). Automatically
stops: iterates through every element of the sequence and stops when the end is reached
While Loops: Best for repeating an action while a condition is true. Condition based: The loop
continues as long as the condition evaluates to True and stops when it becomes False
Range() Function
- Generates a sequence of numbers, commonly used for looping a specific number of
times
- The numbers generated are inclusive of the start value but exclusive of the stop value
Syntax:
range(stop)
range(start, stop)
range(start, stop, step)
start = inclusive, stop = exclusive, step = increasing the integer by the amount
Week 4 Videos
Debugging
What is a Bug?
- A bug is an error or flaw in a program that causes it to behave unexpectedly or
incorrectly
Randomness
Pseudorandom Number Generators
- PRNG are algorithms that generate sequences of numbers that have the properties of
random numbers
- May produce random numbers that are uniformly distributed between a minimum and
maximum number
Seed Values
- A seed: the initial value used by a PRNG to start the number generation process
- The same seed will always produce the same sequence of random numbers
Week 5 Videos
Functions as Black Boxes
Math Functions vs. Programming Functions
- Math functions define a rule that assigns exactly one output to each valid input. Always
produce the same result for the same input
- Programming functions are reusable blocks of code that performs a specific task. Can
return different values for the same inputs. Can also return no values/take no inputs
User-Define Functions
Function Declaration
Consists of two main parts
- Function Header: First line of the function and includes
- The def keyword
- The function’s anime
- A list of parameters the function takes any input
- A colon (:) at the end of the line
- Function Body: An indented block of code that follows the header containing the
statements that will be executed when the function is called
e.g.
def line(length):
for i in range(length):
print(“*”, end=””)
print()
line(10)
- A function can only be called after it is defined (line (10)) must be after the code)
Return Statement: used to send a value back from a function to the caller, allows us to use the
result of a function in other parts of our code
No Return Statement: Functions without a return statement return a None value.
Pass by Assignment: Arguments are passed by assignment, meaning the reference to the
object is assigned to the parameter
Parameter Types
- Dynamic Typing: variable types are determined at runtime, rather than being declared
explicitly
Default Parameter Values: Allows a function to have optional arguments; useful when providing
a default behaviour
Incremental Development
- Involves breaking a problem into smaller, manageable parts
- Can organize code across multiple files (modules) and reuse functions in these modules
by importing them
if __name__ == “__main__”: ensures that certain code runs only when the file is executed
directly, not when imported as a module
Pass Keywrod: Used as a placehold to maintain code structure while developing incrementally
Variable Scope
- Scope refers to the region of the code here a variable is accessible
Three Levels of Scope
1. Built-in Scope: Scope of Python’s built-in functions and objects, always available e.g.
print
2. Global Scope: Variables defined at the top level of a script or module, accessible
throughout the module e.g. discount_rate, total
3. Local Scope: Variables defined inside a function, only accessible within the function
where they are declared e.g. discount
When to Use Global Variables: Values that never change (constants), configuration
When Not to Use: Avoid Modifying Globals inside functions, tracking state
Week 6 Videos
Lists and Tuples
Containers: Objects that hold references to other objects e.g. sets, lists, tuples, strings,
dictionaries
Sequences: Specific type of container that holds items in a defined order e.g. lists, tuples,
strings
Lists: Mutable (can be changed), extensive, use when the data needs to be modified
Tuples: Immutable (cannot be changed), limited (only basic methods like count(), index(), used
for fixed collections of data that should not change
Creating Lists
- Lists are defined using square brackets []
- Can modify elements of a list without creating a new list using [] and =
e.g. fruits = [“apple”, “banana”, “cherry”], mixed = [1, “apple”, 3.14, True]
Indexing Lists
e.g. mixed = [1, “apple”, 3.14, True]
print(“mixed[0]:”, mixed [1]
output: mixed[0]: 1
mixed [-1]: True
List Methods
list.append(x): add the item x to the end of list
list.index(x): return the index of first item in list with value x
list.count(x): count the number of times value x is in list
Tuples
Syntax: my_tuple = (1, 2, 3)
When iterating over a list, the loop variable is a temporary copy of the list element. Changing
this variable inside the loop does not affect the original list
Using for Loop (direct access): Accesses elements directly, syntax: for element in list:, best for
when you need the element values
Using range() with for (Index Access): Accesses elements by their index, syntax: for i in
range(len(list)):, best for when you need both the index and the value
Dictionary: A built-in Python data structure that maps keys to values. Keys cannot be duplicates,
but two different keys can map to the same value
Creating a Dictionary
- Created using curly braces {}
- Keys and values are separated by a : and pairs are separated by commas
e.g. person_ages = {
“Alice”: 27,
“Bob”: 20}
Checking Key Membership: Using “in” will verify if a key exists in a dictionary
e.g. if “1984” in book_inventory:
print(“The book ‘1984’ is available.”)
Passing Dictionaries to Functions: Any modifications to the dictionary inside the function will
affect the original dictionary outside the function
Week 7 Videos
Sorting Algorithms: Goal is to place all elements of a collection in order
Bubble Sort: Repeatedly swaps the adjacent elements if they are in the wrong order, until the
whole collection is sorted
e.g. input A: A collection of sortable items
swapped = True
while swapped is true:
swapped = false
for all items in A:
if the current item in A is greater than the next item in A:
swap the current items A with the next item
swapped = true
Sorting a Dictionary
- Dictionaries do not have a .sort() method
- Can used sorted() function, but be careful of what is being sorted (values or keys)
- e.g. new_dct = dict(sorted(my_dct.items()))
.Join(): Combines a list of strings into a single string with a specified delimiter
syntax: string.join(iterable)
Iterable: Required; any iterable object such as a list where all values are strings
e.g. headers = [‘name’, ‘age’, ‘city’]
csv_string = ‘,’.join(headers)
print(csv_string)
output: name,age,city
Text files: Files that contain plain text and are human-readable. Can be opened and edited with
any text editor
Binary Files: Files that contain data in a format intended for computers and not meant to be read
by humans. Requires specific software to read and interpret
Reading Files
open(): takes a file name and access mode as parameters and returns a file object that allows
you to read from or write the file
Syntax: open(file_name, mode)
read(): reads the entire contents of a file into a string
readline(): reads one line from a file at a time
readlines(): reads all lines in a file at once into a list of strings
Week 8 Videos
Exception Handling in Python
Exception: An event that occurs during program execution, disrupting the normal flow
Raising Exceptions
- Use the raise keyword and specify an exception type to cause an exception of the given
type
- The raise keyword can also be used to re-raise an exception
Syntax:
raise ExceptionType(“Error message”)
e.g. age = int(input(“Input your age: “))
if age <0:
raise ValueError(“Age cannot be negative.”)
Propagating Exceptions
- Unhandled exceptions in a function move up the call stack to the caller
- This continues until the exception is handled or the program terminates
Week 9 Videos
Sets in Python
Set: A collection that contains only unique elements, meaning each item appears only once.
Unordered
- Set operations are much faster than the equivalent list operations
- Mutable, curly braces {}
Creating Sets
e.g. belgium_languages = {“Dutch”, “French”, “German”}
another_set = belgium_languages
- The set()function can also be used to create a set from an iterable, like a list or string
- An empty set by calling the set() function with no arguments e.g. empty_set = set()
- Can’t access or update elements in a set by position, but can loop through the element
Union: The union of two sets is a new set containing all unique elements from both sets
.union(): returns a new set with all unique elements from both sets
Intersection: The intersection of two sets is a new set containing only the elements that both
sets have in common
.intersection(): returns a new set with elements common to both sets
Difference: The difference of two sets is a new set containing elements that are in the first set
but not in the second set
.difference(): returns a new set with elements in the first set but not in the second
Recursion
- A process where a function calls itself directly or indirectly
Recursion vs Iteration
Recursion: More intuitive for recursive problems, shorter code, can be less efficient, ideal for
problems naturally defined recursively
Iteration: Can be less intuitive for recursive problems, more lines of code, more efficient, best for
problems with definite iterations
Common Pitfalls
Infinite Recursion: Occurs when a recursive function lacks a proper base case or the base case
is never reached. Leads to the function calling itself indefinitely
Stack Overflow: Each recursive call consumes stack memory. Excessive recursion depth can
exhaust the available stack space resulting in a stack overflow error, causing the program to
crash
Week 10 Videos
Introduction to Object-Oriented Programming (OOP)
- A paradigm that uses “objects” to design software
- Objects encapsulate data (attributes) and behaviour (methods)
- Attributes: Data or properties that describe the object’s characteristics
- Methods: Actions or behaviours that the object can perform
- Attributes and methods together define what an object is (its state) and what it can do
(its behavior)
OOP In Python
- Use the class keyword followed by the class name to define a class
e.g. class Book:
# Code that defines the methods and class attributes should go here
Instance Methods: functions defined inside a class that operate on instances (objects)
- Defined within methods using self, typically in the __init__ method
Self Keyword: Self refers to the current instance of the class and is used to access attributes
and methods
The __init__Method
- Initiates a new object when it is created
- Call automatically when a new instance of the class is instantiated
Encapsulation: Bundling data (attributes) and methods within a class to protect the internal state
of objects
Importing Classes
- Organize code by placing classes in separate files called modules
- Use the import statement to bring classes from one file into another
Syntax:
from module_name import ClassName
Week 11 Videos
Class Attributes and Methods
- Class attributes are variables shared across all instances of a class
- Can access/modify the value of a class attributes via the class name and dot nation(.)
Syntax:
ClassName.class_attribute_name
Class Methods
- Bound to the class rather than its instances
Object References
- Variables hold a reference to an object’s location in the computer’s memory
e.g.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
my dog = Dog(“Laddie”, “Collie”)
print(my_dog)
Output: <__main__.Dog object at 0x0000020DB0BD9640>
Comparing Objects
- Can use the is and is not keywords to check if objects share a common reference
is vs. ==
is Operator
- Compares Identity: Checks if two objects are the same object in memory
- Returns True if both references point to the exact same object
== Operator
- Compares Values: By default, checks if two objects are the same object in memory (just
like is)
- If a class defines __eq__, it uses that method to compare contents or values
isinstance() Function
- A built-in function used to check if an object is an instance of a given class or a subclass
of that class
- Returns True only if the object is an instance of 1) the specified class or 2) a subclass of
the specified class
Syntax: isinstance(object, class)
self Reference
- Refers to the instance of the class that is calling the method, allowing access to the
instance’s attributes and other methods
None Object
- A singleton (only one instance) object representing “nothing” or “no value”
- Often used to signify the absence of a value, default initialization, or a placeholder for
objects or values not yet assigned
Object Lifestyle
- The object lifecycle refers to the stages an object goes through during its existence in a
Python program: creation, usage, and destruction
Creation:
- An object is created when a class is instantiated
- Memory is allocated for the object, and it’s __init__method is called
Usage:
- The object exists and can be accessed, modified, and used in operations
- During this stage, attributes and methods of the objects can be accessed/called
Destruction:
- An object is destroyed when it is no longer referenced in the program
- If the class defines a __del__method, it will be called before destruction
Reference Counting: An object is destroyed when its reference count drops to zero
- Each reference created to the object increases the count by 1. Each deleted reference
lowers the count by 1
- Re