# COMP1010 EXAM NOTES, Maddy (z5583311)

Basics:

- Indentation:
    - Refers to the spaces at the beginning of a line of code. Indicates a block of code
    - Must be 4 spaces!!!! Have to use the same number of spaces in the same block of code otherwise an error will occur
- Variables:
    - Created when a variable is applied to it
    - Example:
        - y = 3
- Casting:
    - Performed manually by using built-in functions to ensure a variable matches the required data type for an operation
    - Example:
        - y = int(3)   (y will be 3), z = float(3)  (z will be 3.0)
- Global variables:
    - Variables that exist outside of a function
    - If you create a variable with the same name inside a function, this variable will be local and can only be used inside the function while the global variable will remain unchanged
- F strings
    - Formats a string, able to combine strings and numbers
    - Example:
        - age = 20
        - x = (f"My name is Maddy, I am {age}")
        - print(x)
- Boolean values:
    - bool() function allows evaluation of a value, returning either True or False
    - Most values will return True if it has some sort of content, except empty strings and the number 0
- Loops
    - Used to repeat code multiple times
    - Two different types: **for** and **while**
    - For loop:
        - Repeats code over a sequence (such as a string, range or list)
            - for x in “meow”:
            - print(x)
    - While loop:
        - Repeats code while a condition is True
            - x = 1
            - while x < 5:
            - print(x)
            - x += 1
        - Condition is checked before each loop
        - Must eventually become false (or it loops forever!!!!!)
- Lists
    - Used to store multiple items in a single variable, created using square brackets: [   ]
    - Ordered: if new items are added to a list, they will be placed at the end of the list
    - Allows duplicate values

functions/keywords/statements

| Thing | What it does | Example |
| --- | --- | --- |
| print(…) | prints | **print**(”Hello World!”) |
| len(…) | finds the length of a string | x = "meow"
print(**len**(x)) |
| .upper + .lower | returns the string in upper/lower case | a = "Meow"
print(a.upper()) |
| if | evaluates a condition and executes the indented block below if the condition is True | x = 10
if x > 5:
    print(f"{x} is greater than 5") |
| elif | “else if”, checks multiple conditions in order | x = 10
if x > 10:
    print("Greater than 10")
elif x == 10:
    print("Exactly 10") |
| else | only runs if all previous conditions are False | x = 3
if x > 5:
    print("Big")
else:
    print("Small") |

data types

| Thing | What it does | Example |
| --- | --- | --- |
| str | text: stores text | x = “Hello World” |
| int | numeric: whole numbers | x = 20 |
| float | numeric: decimal numbers | x = 2.0 |
| complex | numeric: real + imaginary numbers | x = 2j |
| list | sequence: ordered, changable | x = [”cat”, “dog”, “hamster”] |
| tuple | sequence: ordered, unchangable | x = (”cat”, “dog”, “hamster) |
| range | sequence: sequence of numbers | x = range(6) |
| dict | mapping: key-value pairs (matches word/key to definition/value) | x = {"name" : "Maddy, "age" : 20} |
| set | set: unordered, unique items | **x = {"cat", "dog", "hamster"}** |
| frozenset | set: unchangable set | x = frozenset({"cat", "dog", "hamster"}) |
| bool | boolean: true or false values | x = True |
| nonetype | none: represents no value | None |

string methods (don’t know if i need these but theyll probs be good to have)

| Thing | What it does  | Example |
| --- | --- | --- |
| capitalize() | converts the first character of a string to upper case | text = "mEOW"
print(text.capitalize()) |
| casefold() | converts string into lower case (stronger than .lower()) | text = “MEOW”
print(text.casefold()) |
| center() | centers a string | text = “meow”
print(text.center(10)) |
| count() | returns the number of times a specified value occurs | text = "meow"
print(text.count("m")) |
| index() | searches the string for the specified value and returns its position | text = "meow"
print(text.index("e"))
(output would be “1”) |
| .isalpha() | returns True if all characters in the string are in the alphabet | text = "Meow"
print(text.isalpha()) |
| .isdigit() | returns True if all characters in the string are digits | text = "12345"
print(text.isdigit()) |
| .isalnum() | returns True if all characters are alphanumeric | text = "Meow123"
print(text.isalnum()) |

List methods:

| Thing | What it does | Example |
| --- | --- | --- |
| .append(…) | adds to the end of a list | list = [1, 2]
list.append(3)
print(list) |
| .insert(…) | adds to a position in a list | list = [1, 2, 4]
list.insert(2, 3)
print(list) |
| .remove(…) | removes a value from a list (by value)  | list = [1, 2, 4]
list.remove(2)
print(list) |
| .pop(…) | removes a value from a list (by index position) | list = [10, 20, 30]
list.pop(1)
print(list) |

operators: used to perform operations on variables and values

| Thing | What it does | Example |
| --- | --- | --- |
| + | adds 2 values, can also add a variable and a value, or 2 variables | total = 10 + 10
total2 = total + 10 |
| - | subtraction | x - y |
| * | multiplication | x * y |
| / | division | x / y |
| % | modulus operator, gives the remainder after division | x % y |
| =  | assignment operator, stores a value in a variable | x = 5 |
| += | compound assignment operator, adds to a variable, then stores the result in the same variable | x = 5
x += 3 |
| -= | compound assignment operator, subtracts a value from a variable, then stores the result in the same variable | x = 5
x -= 3 |
| *= | compound assignment operator, multiplies a variable by a value, then stores the result in the same variable | x = 5
x *= 3 |
| /= | compound assignment operator, divides a variable by a value, then stores the result in the same variable | x = 10
x /= 2 |
| %= | compound assignment operator, takes the remainder of a variable after division and stores it back in the same variable | x = 10
x %= 3 |
| == | comparison operator, checks if two values are equal | x = 5
print(x == 5)
(output would be “True”) |
| != | comparison operator, checks if two values are not equal | x = 5
print(x != 3)
(output would be “True”) |
| > | comparison operator, greater than | x = 10
x > 9 |
| < | comparison operater, less than  | x = 10
x < 15 |
| >= | greater than or equal to | x >= y |
| <= | less than or equal to | x <= y |
| and | logical operator, combines two conditions and returns True, only if both conditions are true | x = 10
print(x > 5 and x < 20) |
| or | logical operator, returns True if at least one condition is true | x = 10
print(x > 5 or x < 3) |
| not | logical operator, reverses the boolean value | x = 10
print(not x > 5) |
| in (opposite is “not in”) | membership operator, used to check if a value is a part of a sequence (such as a list, dict or string) | print("m" in "meow") |

example code that i still dont really understand:

> for x in “meow”:
    print (x)
#prints each character in the string, one at a time with each letter on a new line
>

Web apps!!!!!

- 3 main parts:
    - front end → what the user sees (HTML)
    - back end → Python logic
    - data → lists, JSON files

user inputs data (forms/buttons) → Python processes info → output (web page result)

HTML elements:

| Thing | What it does  | Example |
| --- | --- | --- |
| <!DOCTYPE html> | declares that its HTML 5 | <!DOCTYPE html> |
| <html> | root of the page | <html>…</html> |
| <head> | info about the page, not directly displayed | <head>…</head> |
| <title> | the title thats viewed in the browser tab | <title>Title</title> |
| <body> | visible content on the web page | <body>meow</body> |
| <h1> | main heading | <h1>Meow</h1> |
| <h2> | sub heading | <h2>Meow?</h2> |
| <p> | paragraph | <p>meow meow meow</p> |
| <br> | line break | meow<br>meow |
| <hr> | horizontal rule, renders as a horizontal line | <hr> |
| <strong> | makes text bold | <strong>Hi</strong> |
| <em> | makes text italic (emphasis) | <em>meow</em> |
| <a> | link | <a href=”[https://ar.pinterest.com/pin/1149403136149798999/](https://ar.pinterest.com/pin/1149403136149798999/)”>meow</a> |
| <img> | image insert | <img src=”images/cat.jpg” alt=”funny cat”> |
| <video> | video file insert | <video controls>
    <source src="video.mp4"                            type="video/mp4">
</video> |
| <audio> | audio file insert | <audio src="audio-file.mp3" controls>
    <source src="music.mp3"                            type="audio/mpeg">
</audio> |
| <div> | a block container that defines a division or a segment  | <div>…</div> |
| <span> | similar to <div>, but is an inline container | <p>meow <span style="color:pink">meow</span> meow</p> |
| <header> | represets a container for introductory content | <header>Hello</header> |
| <footer> | defines a footer for a document | <footer>funnyemailthatdefinitelyexists@gmail.com</footer> |
| <section> | defines a section in a document | <section>
<h1>Hi</h1>
<p>meow meow meow</p>
</section> |
| <article> | specifies an independent, self-contained content, i.e. must make sense on its own!!! | <article>
<h2>MEOWWWW</h2>
<p>im getting real tired of typing meow for all these examples</p>
</article> |
| <ul> | unordered list (bullet points) | <ul> 
    <li>meow</li> 
    <li>meow?</li> 
    <li>meow!</li>
</ul> |
| <ol> | ordered list (numbered) | <ol>
    <li>meow…</li>
    <li>MEOW….</li>
</ol> |
| <form> | used to create a HTML form that accepts user input | <form action="/submit" method="post">…</form> |
| <input> | input box!!! | <input type=”text”> |
| <label> | defines a label for an element | <label for=”meow”>Meow:</label> |
| <button> | defines a clickable button | <button type="button">Meow!</button> |
| <select>, <option> | an element used to create a drop-down list (include label in the front!)
options are options… | <select name="cats" id="cats">
<option value="small cat">Small cat</option>
</select> |

other important html stuff:

| href | defines link destination | <a href="..."> |
| --- | --- | --- |
| src | defines file source | <img src="..."> |
| alt | image description (text) | <img alt="cat"> |
| id | unique identifier | <div id="main"> |
| class | group styling | <div class="box"> |
| type | input type | <input type=”password”> |

basic html for signup page:

>
>
>
> <form action="/action_page.php" method="get">
>
> <label for="fname">First name:</label>
>
> <input type="text" id="fname" name="fname"><br><br>
>
> <label for="lname">Last name:</label>
>
> <input type="text" id="lname" name="lname"><br><br>
>
> <input type="submit" value="Submit">
>
> </form>
>

REMEMBER: pyhtml is basically just html things but the <> are brackets instead

Basic CSS stuff:

syntax: selector → property → value

IMPORTANT! everything must be inside one style, i.e.: <h1 style="color:pink; font-family: Arial;">Meow</h1>

Text styling:

| Thing | What it does | Example |
| --- | --- | --- |
| color | changes text colour (must be spelt the american way.. learnt this the hard way) | <h1 style="color:pink;">Meow</h1> |
| font-family | changes text font | <h1 style=”font-family: Arial;”>Hi</h1> |
| font-size | changes text size | <h1 style=”font-size: 80px;”>MEOWWW</h1> |
| text-align | aligns text to a specific position | <h1 style=”text-align: center;”>Hi</h1> |

box model:

| Thing | What it does | Example |
| --- | --- | --- |
| margin | space outside of the element |  <style>
    .box {
        background-color: pink;
        margin: 50px;
    }
</style> |
| padding | space inside an element | padding: 10px;  |
| border | the border around an element | border: 1px solid black; |
| width | the width of an element | width: 200px; |
| height | the height of an element | height: 100px; |

other:

| Thing | What it does | Example |
| --- | --- | --- |
| background-color | changes the background colour of an element | background-color: pink; |
| text-align | aligns text  | text-align: center; |

JSONS!!!!!!!!!!!!

JSONS (Javascript Object Notation): a method of storing structured data

JSON:

> {
”name”: “Maddy”,
”age”: 20,
”student”: true
}
>

Python (dictionary):

> {”name”: “Maddy”, “age”: 20, “student”: True}
>

NESTED JSON!!!!!! kinda similar to SQL????

basically a thing inside a thing, example:

- A class → students → student details

better example of a nested JSON:

> {
    ”class”: {
        “name”: “COMP1010”,
        “students”: [
            {”name”: “Maddy”, “dob”: “2005-10-10”}
        ]
    }
}
>

reading JSON files in Python:

1. import json file

> import json
>
1. open and load the file

> with open(”data.json”) as file:
    data = json.load(file)
>
1. get thing

> data[”class’][”name”]
>
1. output

> COMP1010
>

loop for extracting multiple things?:

> for student in data[”class”][”students”]:
    print(student[”name”])
>

Core Architecture of Applications

Every programming application follows a consistent pattern:

User → Input → Processing → Output → Storage

This pattern appears in every exam and real-world system. The user provides data (via forms or code), the program processes it (using functions and logic), displays results (HTML pages), and optionally saves data persistently (JSON files or cookies).

The full system layers are:
1. Data Layer: Structures like lists, dictionaries, and JSON files hold information
2. Function Layer: Python functions perform calculations, searches, and updates
3. Server Layer: Flask routes handle requests and connect frontend to backend
4. UI Layer: HTML forms and PyHTML generate the user interface
5. Storage Layer: JSON files provide permanent memory; cookies handle per-user temporary data

Data Structures – The Foundation
List

Ordered collection of items
1. Allows duplicates
2. Good for storing multiple items of the same type (tasks, players, numbers)
3. Accessed by index: data[0], data[-1]
  Slow search requires looping through all elements'

Dictionary
1. Key-value pairs – each key maps to a value
2. Fast lookup – O(1) average time
3. Represents one entity (a player, a course, a user)

Example:
player = {"id": "magnus", "elo": 2831, "faculty": "engineering"}

List of Dictionaries – The Most Important Structure
players = [     {"id": "a", "elo": 1000},
    {"id": "b", "elo": 1200}
]

This structure is used when:
1. There are many objects with the same structure
2. Each object has clear properties (dictionary keys)
3. You need to loop through and access specific fields
4. Key takeaway: "List of dictionaries = standard structure for real-world data"

Dictionary of Lists
data = {"wins": [1,2,3], "losses": [0,1]}

1. Used when grouping categories – each key maps to a list of related items.

Comparison
  List of dicts: multiple objects, each represented as a dictionary – best for collections of entities
Dict of lists: grouped data where each category contains multiple values

Core Programming Patterns

1. Add (Create + Append)
data.append(new_dict)
Pattern: Create a structured object, then insert it into a list.

2. Search
for player in data:     if player["id"] == target_id:         return player
Pattern: Loop through items, check a condition, return the matching item.

3. Max Finding
winner = data[0] for player in data:     if player["elo"] > winner["elo"]:         winner = player
Pattern: Initialize with first item, then track the best value while looping.

4. Counting
wins += 1
Pattern: Loop through items, classify each, increment a counter.

Loop + Accumulation
total = 0 for segment in scarf_segments:     total += cost_per_cm * segment["length"]
  Always initialise the accumulator (total = 0)

1. Loop through all items
2. Perform calculation
3. Round at the end for money: round(total, 2) – rounding inside the loop is incorrect

Key idea: "Loop → calculate → accumulate → return"

Filtering Data
result = [] for item in data:     if item["rating"] > 4:         result.append(item)
# Pattern: Create empty list, loop with condition, append matching items.

Functions – Design Principles

Function Pattern

1. def function_name(inputs):     # process     return result

Good design means:
1. Reusable – call the function multiple times with different inputs
2. Clear – name describes purpose (e.g., get_tip, calculate_scarf_cost)
3. Single responsibility – each function does one job and returns a result

Example: Tip Calculator
# def get_tip(amount, percentage):
#   return amount * (percentage / 100)
# def get_total(amount, percentage):     return amount + get_tip(amount, percentage)

Functions can reuse other functions – get_total calls get_tip to avoid repeating code.
1. Key Takeaway
"Functions should do ONE job and return a result."

Flask Web Applications
Skeleton
from flask import Flask, request import pyhtml as p
app = Flask(__name__)
@app.get("/") def home():     return str(         p.html(
            p.body(
                p.form(action="/calculate", method="post")(
                    p.input(name="amount"),
                    p.input(type="submit")                 )
            )
        )
    )
@app.post("/calculate") def calculate():
    amount = request.form["amount"]     return str(p.p(f"You entered {amount}"))
app.run()

Every Route Follows This Pattern
1. GET route (@app.get("/")) – displays a page (form or data)
2. POST route (@app.post("/")) – processes user input, updates system, returns result

Core Lifecycle
User input → request.form → Python logic → update data → return HTML page

Getting Form Data
request.form["field"] – or safer: request.form.get("field")

Important: the input field must have a name attribute to be accessible.
Full Web Server Flow (T2)
1.	GET request – show form
2.	User submits form
3.	POST request – request.form["field"]
4.	Process data (call function)
5.	Return result page

HTML and PyHTML
Form Structure (HTML)
<form method="post">
    <input name="amount">
    <input type="submit">
</form>

Dropdown (Exam Favourite)
<select name="percentage">
    <option value="10">10%</option>
    <option value="15">15%</option>
</select>

PyHTML Equivalents
p.form(action="/add", method="post")(...)
p.input(name="amount")
p.select(name="faculty")(
    p.option("Engineering"),
    p.option("Science") )

1. Key idea: "PyHTML = Python version of HTML"

CSS – Free Marks

Linking CSS
p.link(rel="stylesheet", href="/static/style.css")

Simple Styling
1. body {     text-align: center;     color: #333;     font-family: Arial, sans-serif; }

What to Include
1. Colours – background, text
2. Spacing – margins, padding
3. Centering – layout
4. Table formatting – borders, alignment

Strategy: Keep it simple – spacing, colours, and table formatting are enough.

1. Cookies
- Small data per user
- Stored in browser
- Temporary – cleared when cookie expires or is deleted
- Per-user – each browser has its own cookies

- Used for: login sessions, preferences, saving progress (e.g., scarf design)
- Working with Cookies (Flask)

from flask import make_response
res = make_response("Saved") res.set_cookie("username", "Taf") return res

Getting a cookie: request.cookies.get("username")

Important: Set session.modified = True to tell Flask to save changes; clear with session.pop("key").

Key takeaway: "Cookies = user-specific memory"

2. Files / JSON
- Large data – can hold many records
- Shared data – accessible by all users (if stored on server)
- Persistent – survives server restarts

- Used for: courses, tasks, orders, permanent records

Key takeaway: "JSON = long-term storage"
Persistence Flow (H1)
User clicks order → enters name → server saves to JSON → clears cookie This combines cookies (temporary per-user) with JSON (permanent shared storage).

- JSON
Read JSON
import json
with open("data.json") as f:     data = json.load(f)

Write JSON
with open("data.json", "w") as f:     json.dump(data, f)

Error Prevention Pattern
try:     with open("data.json") as f:
        data = json.load(f) except:     data = []  # or return [] in a function
This prevents crashes when the file doesn't exist.

Algorithm Thinking

Step-by-Step Transformation
Example: Elo rating calculation
1.	Convert result to number – win → 1, loss → 0, draw → 0.5
2.	Calculate probability – win_probability(rating_a, rating_b)
3.	Update rating – new = old + constant * (actual - expected)
4.	Record history – past_games.append({"opponent": id, "result": result})

- Key insight: "Algorithms = step-by-step transformation of data"

The Elo Formula (Conceptual) new_rating = old_rating + K ×(actual_score − expected_score)
If you perform better than expected → gain points
If you perform worse → lose points
Counting Wins/Losses

wins = 0 for game in player["past_games"]:     if game["result"] == "win":         wins += 1
Pattern: Loop → classify → count

Recursion (Prereqs Question)
Pattern (Memorise)
def helper(code):     for prereq in courses[code]:         if prereq not in result:             result.append(prereq)             helper(prereq)
Key idea: Call function inside itself – collects both direct and indirect prerequisites.

Conditions and Control Flow
if vs elif

- Separate if statements – both can run if conditions are true if-elif chain – only one block runs, even if both conditions are true

- Logical Operators
and – both conditions must be true or – at least one condition must be true

Pattern: Lookup Table (Dictionary)
Instead of:
if colour == "pink":     cost = 1.4 elif colour == "blue":     cost = 1.2

Use a dictionary for cleaner, faster, scalable lookups:
colour_costs = {"pink": 1.4, "blue": 1.2} cost = colour_costs[colour]

Common Errors and Fixes
KeyError
data["name"] fails if key doesn't exist
Fix: if "name" in data: or use .get("name")
IndexError
word[1] fails if string is too short Fix: if len(word) > 1:
TypeError
"5" + 5 – cannot add string and integer
Fix: int("5") or str(5)

Usability Heuristics

1. Error prevention – use dropdowns, required fields, number inputs to block mistakes before they happen

2. Consistency – same layout, same button placement, same colours

3. Feedback – show results, error messages, confirmation after actions
4. Recognition vs recall – dropdown menus (recognition) instead of free-text fields (recall)
5. Minimalism – clean UI with only essential elements
6. Clear layout – logical grouping, readable text
7. Simple navigation – easy to move between pages
8. Highlight important info – use bold, colour, spacing

# Key idea: "Good UI reduces user mistakes. Make it easy, clear, and mistake-proof."
