KEMBAR78
CS1026 Notes | PDF | Control Flow | Class (Computer Programming)
0% found this document useful (0 votes)
24 views22 pages

CS1026 Notes

Uploaded by

Sophie Wang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views22 pages

CS1026 Notes

Uploaded by

Sophie Wang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Week 1 Videos

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

What are Algorithms?


Source Code
- Step by step instructions, have to follow a specific syntax and grammar a computer can
understand, typically an implementation of an algorithm
Algorithms
- Given an input, it always produces an output, no set syntax or grammar

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

Sequences: A series of actions that are completed in a specific order


Selections: Ask a question in order to figure out which path to take next
Loops: Repeat over and over again until a certain condition is met

The History of Python


- The Python Programming Language was created by Guido van Rossum
- First version was released in 1991

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

Variables and Data Types


Variables
- Named area in a computer’s memory that can store a value
- In Python everything is an object
- Variables point to an object stored in the computer’s memory

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

Type() Function: Takes an object and returns its type

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

Operators and Arithmetic


Operators
- Used to perform operations on objects and values, represented as special symbols or
keywords

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 and Operations


String concatenation: Creates a new string by adding two strings together e.g. “Cat” + “Dog” =
“CatDog”
String repetition: creates a new string that is the result of repeating the string on the left the of
times it is multiplied by an integer value e.g. “Ha “ * 5
String formatting: Formats the string on the left with the format given on the right

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

Branching and The if Statement


The if Statement: takes a Boolean expression and only executes the code contained in the
statement if the expression evaluates to True
Syntax:
if condition:
# body of if statement
e.g. if age >= 18:
print(“Adult”)

The if…else Statement


- The else statement can be added to an if statement to run a block of code if the Boolean
expression evaluates to False
Syntax
if condition
# Run this block of code if condition is true
else:
# Run this block of code if condition is False

The if…elif…else Statement


- Elif: stands for “else if” and allows us to run a block of code if the statements before it
were False and its Boolean statement evaluates to True
Syntax
if condition 1:
# Run this block of code if condition 1 is True
elif condition 2:
# Run if all previous lines are False and condition 2 is True
(zero or more elif statements)
elif condition N:
# Run if all previous lines are False and condition N is True
else:
# Run this block of code if condition is False
Nested Statements
- If statements can be nested inside of other If statements, allows for more complex
branching and programs

String Comparison Operators


>: comes later in the alphabet
- Lowercase letters are considered to come after uppercase letters alphabetically
- E.g. “a” > “Z” = True; “a” == “A” = False

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

String format () Method


This method supports 3 different ways to replace brackets {} with values
1. Empty Replacement Fields Example
- Each bracket is replaced in the same order we give it the values
2. Replacement Fields with Indices Example
- Numbers represent indices and are ordered according to the indices given
3. Replacement Fields with Named Arguments
- Words in the brackets correlate to the items

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

Break and Continue


Break Statement: Used to exit the loop immediately, regardless of the loop’s condition
Continue Statement: Used to skip the current iteration and move to the next iteration of the loop.
For Loops
Processing Strings with Loops
- Can process strings using a while loop by accessing individual characters at their given
index
e.g. s = “Hello World:
i=0
while i < len(s):
print(s[i])
i += 1
The output will have 1 letter of the phrase per line, total 11 lines (including the space_

For Loops vs. While Loop


For Loops
- Handles iterating over a collection of items, no need to manually manage an index
Syntax:
for variable in collection:
# Code block to execute
e.g. s = “Hello World”
for char in s:
print(char)
Same output as using While Loop

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

Using range() with a for Loop


e.g. for i in range(2, 10, 2):
print (i)
Output is 2, 4, 6, 8
e.g. for i in range (10, 0, -1)
print(i)
Output is 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
Nested Loops: Loops inside of other loops
- Any type of loop (for or while) can be placed inside another loop
- The inner loop runs completely for every single iteration of the outer loop
e.g. for i in range(2):
for j in range(3):
print(i,j)
Multiplication Table Example
for row in range (1, 11):
for col in range(1, 11):
print(row * col, end=”\t”)
print()

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

Errors (COME BACK)


Logic Errors: logical flaws in a program’s algorithm rather than its implementatiom
Syntax Errors: violations of a programming language’s rules (syntax) such as not following its
grammar, misspelling function/command names, etc
Indentation Error: error that occurs when indentation is inconsistent or incorrect
NameError: when using a variable or function hat hasn’t been defined
AttributeError: when trying to access an attribute or method that doesn’t exist for a module or
object
IndexError: when trying to access an index in a sequence (like a list or a string) that doesn’t
exist
TypeError: when an operation or function is applied to an object of an inappropriate type
ValueError: when a function receives an argument of the correct type but with an inappropriate
value
Runtime Errors: errors that occur while the program is running. Typically caused by cases
where the syntax is correct but the operation being performed is not possible

Using print() for Debugging


- A technique where you insert print(statements) into your code
Key points where they should be placed:
1. Before and after loops
2. Inside conditional blocks
3. At the beginning, middle, and end of functions

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

Basic Random Functions


- Python’s random module provides functions to generate pseudorandom numbers
- Must import the module before using any random functions:
import
random

Setting the PRNG Seed


- The seed of the PRNG can be set to force the set of numbers returned by
random.randint() to always occur in the same order
Syntax:
random.seed(seed_val)
where seed_val is an integer value or None

Random Characters From a String


- random.choice returns an element from a sequence and strings are a type of sequence
e.g
import random
rand_char = random.choice(“ABCEFGHJKLMNPQRSTUVWXYD”)
print(rand_char)
e.g. Output: T

random.choice also works on other sequences such as lists and tuples

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

The Black Box Analogy


- The user inputs something into the box, adn the box does some processing inside and
then gives you an output. THey are not required to understand how the function works

Arguments, Parameters, and Return


Parameters: An input to a function specified in the function’s definition e.g. base, exp, mod
Arguments: A value provided to a function’s parameter during a function call e..g 2 and 5 in the
function pow(2, 5)
Return Value: The output that a function sends back to the part of the program that called it
Nested Function Calls: When a function is used as an argument within another function
Keyword Arguments: Allow you to pass values to a function by explicitly specifying the name of
the parameter
e.g.
power = pow(exp=2, base=10)
print(power)
= 100

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

The main() Function


- Acts as the entry point of your program to organize your code and makes it more
readable. Has no special meaning and does not run on its own

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

Shadowing Variable Names


- Shadowing occurs when a local variable has the same name as a global variable or a
variable in an outer scope
- Causes the variable in the outer scope to be inaccessible within the current scope
- Avoid shadowing, espeically between global and local scopes

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(): creates a new list


e.g. list (“abc”) would result in a list of characters [“a”, “b”, “c”]

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

Built-In List Functions


len(my_list): returns the number of elements in the given list
max(my_list): returns the maximum element in the given list by value
sum(my_list): returns the sum of the value of the elements in the given list
all(my_list): returns true if every element in list is true or if the list is empty
any(my_list): returns true if any element in list is true or if the list is empty

Tuples
Syntax: my_tuple = (1, 2, 3)

Common Tuple Operations


Accessing Elements: Use indexing like lists
my_tuple = (10, 20, 30) print(my_tuple[1]) #Outputs: 20
Membership Testing: Use in to check if an item exists in a tuple
print(20 in my_tuple) # Outputs: True
Equality Testing: Use == to check if two tuples are equal
tuple1 = (1, 2, 3) tuple2 = (1, 2, 3) print(tuple1 == tuple 2) #Outputs: True

Working with Lists: Iteration and Nesting


Iterating Over a List with a For Loops
e.g. fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
output: apple, banana, cherry

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

Don’t Modify a List While Operating Over it


Unpredictable Behaviour: Add/removing elements from a list (e.g. using append(), remove(), or
pop()) during iteration can lead to unexpected results
- Should create a list() before iterating so we iterate over the copy rather than the original
list

Lists and Functions


Pass by Assignment: When a list is passed to a function, a reference to the original list is sent
(pass by assignment)
Creating and Returning: Functions can create lists internally and return them to the caller
Using Returned Lists: The returned list can be assigned to a variable, enabling further
manipulation or access outside the function

Nested List: A list that contains other lists as its elements

Using len() with Nested Lists


len(nested_list): Returns the number of rows in the outer list
len(nested_list[0]): Returns the number of columns in the first inner list

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}

How to Set or Update Values


- = will set/update the value.
e.g. person_ages = …

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

Iterating Over a Dictionary


Iterating Over Keys
e.g. for employee in employee_role:
print(employee, “has the role of”, employee_role[employee])
Iterating Over Values with .values()
e.g. for role in employees_role.values():
print(role)
Iterating Over Key-Value Pairs with .items()
e.g. for employee, role in employee_rule.items()
print(employee, “has the role of, role)

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 Using Built in Functions/Methods


e.g. my_list =[24, 70, 42, 61, 36, 96, 36, 24]
print(“Before sort: “, my_list)
my_list.sort()
print(“After sort: “, my_list)

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()))

Sorting a Complex Structure


- Needs to define a function that returns the value to sort by e.g. def by_final_grade(item):
- Can still use the .sort() method if outer collection is a list

String Splitting and Joining (*add strip to sheet)


.Split(): Breaks a string into a list of substrings based on a specified delimiter
syntax: string.split(delimiter, maxsplit)
Delimiter: specificies the delimiter to use when splitting the string. If no separator is given
whitespace is used at the separator
Maxsplit: Specifies how many splits to do. Default value is -1, which is “all occurrences”
e.g. csv_data = “name,age,city”
fields = csv_data.split(“,”)
print(fields)
output: [‘name’, ‘age’, ‘city’]

.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

Using split() and join() Together


e.g. text = “Python is fun”
words = text.split()
reversed_sentence =” “.join(reversed(words))
print(reversed_sentence)
output: fun is Python

Reading and Writing FIles


File: A container for persistent data on a computer
File name: every file has a unique name within its folder (aka directory)
FIle Extentions: letters after the doc(.) in a file name, like .txt in report.txt
FIle Path: The full location where a file is stored, like a map to its spot on the computer

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

Looping Through Files


- For loop can iterate directly over a file object to read each line one at a time
e.g. file = open(“todo_list.txt”, ‘r’)
for line in file:
print(line.strip())
file.close()
Writing Files
Opening Files for Writing
“w” - Write mode: creates a new file or overwrites an existing file
“a”- Append mode: adds content to the end of an existing file
e.g. file = open(‘example.txt’, ‘w’)
write(): adds text to a file when the file is opened in write (“w”) or append (“a”) mode. Takes a
single string as an argument and writes that string directly to the file

Week 8 Videos
Exception Handling in Python
Exception: An event that occurs during program execution, disrupting the normal flow

The try/except Block


- Catches and handles exceptions that may occur in a block of code
- try Block: contains codes that might raise an exception
- except Block: contains code that executes if an exception occurs in the try block
- The code in the except block is executed only if an exception of the given type is raised
Syntax
try:
# Code that may raise an exception
except ExceptionType as exception_var:
# Code to handle the exception

The else Clause in try/except


- The try/except block also allows for an optional else block
- The else block is only executed when no exceptions are raised in the try block

The finally Clause in try/except


- The try/except block also allows for an optional finally block
- Guarantees execution of code regardless of whether an exception was raised or not
- finally is used to ensure the file is always closed before the program terminates
- The finally block is always run, even if exit() is called, or the return statement is used
within the try block
Syntax:
finally:
# Code that always executes

Handling File Errors


The with Statement: automatically manages resource acquisition and release (context
management)
- No need to explicitly call file.close() when using with
- Exceptions can be caught inside the with block or in an encompassing try/except
Syntax:
with open(“file.txt”, “r”) as file:
# Code to process the file

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

.add(): adds a single element to a set


.update(): adds all elements from an iterable (like a list or another set)
.discard(): removes a specified element from a set, if it it exists
.remove(): also deletes a specified element from a set
len(): returns the number of elements in a set
sorted(): takes a set as input and returns a sorted list
in and not in operators: checks if an element is present or absent in a set

Set Operations and Methods


Subsets: A set where every element is also part of another set
- If all elements of set A are contained in set B, then A is a subset of B
Proper Subset: A subset that is strictly smaller than the set it’s compared to (it cannot be equal)

.issubset(): checks if a set is a subset of another set

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

Basic Structure of a Recursive Function


def recursive_function(parameters):
if base_case_condition:
return base_case_value
else:
return recursive_function(modified_parameters)
e.g. def factorial(n):
if n == 0:
return 1 # Base case
else: return n * factorial(n-1) # Recursive case

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)

Objects and Classes


Classes: A blueprint or template for creating objects with specific attributes and methods
Objects: An instance of a class containing actual data and capable of performing defined
behaviours

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

Private and Public Attributes (Naming Conventions)


- A single underscore prefix (_attribute) indicates an attribute is intended for internal use
only (non-public)

Multiple Instances of a Class


- Can create multiple objects (instances) from the smae class
- Objects operate independently, so changes to one do not affect others

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

Comparing Class and Instance Attributes


- Instance attributes are specific to each object and defined using self. Changing an
instance attribute’s value only affects that specific object
- Class attributes are shared across all instances of the class. Changing a class attribute’s
value affects all instances of that class

Class and Instance Namespaces


- Objects in Python have two distinct namespaces: instance and class

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

Special Methods (aka Magic Methods)


- Predefined methods that have names surrounded by double underscores (e.g. __init__,
__str__)
- Allow objects to define or customize their behavior for built-in operations
__init__(self, params…): Called when an object is created
__del__(self): Called when an object is about to be destroyed

Special Methods for Type Conversion


- Allow classes to behave more like native Python objects
- e.g. __str__(self), __repr__(self), __int__(self), __float__(self)
__repr__:
- Used for developers and debugging
__str__:
- User-friendly, human-readable output
- Complements __repr__: use for end-users
Other type methods (__int__,__float__):
- Use when the object has a logical numeric meaning
- Ensures conversions are accurate and meaningful

Special Methods for Object Comparison


- These method customize how objects are compared and allow classes to define
behaviour for operators like ==, !=, <

- Re

You might also like