# COMP1010 Exam Notes

## Run Server
uv run python tournament_app/server.py
---
# Flask
## Basic Flask
```python
import pyhtml as p
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
    return "Hello"
if __name__ == "__main__":
    app.run(port=5001)
```
## Route With POST
```python
@app.route("/login", methods=["POST"])
def login():
    return "Logged in"
```
## Route With URL Value
```python
@app.route("/player/<player_id>")
def player(player_id):
    return player_id
```
## Redirect
```python
from flask import redirect
return redirect("/")
```
## Import Request
```python
from flask import request
```
## Get Form Data
```python
name = request.form["name"]
```
## Get Optional Form Data
```python
name = request.form.get("name")
```
---
# Flask Form Example
## Server
```python
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def index():
    return """
    <h1>Form</h1>
    <form action="/result" method="POST">
        <label>Name:</label>
        <input name="name">
        <button>Submit</button>
    </form>
    """
@app.route("/result", methods=["POST"])
def result():
    name = request.form["name"]
    return f"<h1>Hello {name}</h1>"
app.run(port=5001)
```
---
# PyHTML
## Basic PyHTML Page
```python
from pyhtml import *
page = html(
    head(
        title("Page")
    ),
    body(
        h1("Title"),
        p("Text")
    )
)
return str(page)
```
## PyHTML Form
```python
from pyhtml import *
page = html(
    body(
        h1("Form"),
        form(action="/result", method="POST")(
            label("Name:"),
            input_(name="name"),
            button("Submit")
        )
    )
)
return str(page)
```
## PyHTML List
```python
items_html = []
for item in items:
    items_html.append(li(item))
page = html(
    body(
        h1("Items"),
        ul(items_html)
    )
)
return str(page)
```
## PyHTML Table
```python
rows = []
for player in players:
    rows.append(
        tr(
            td(player["name"]),
            td(player["score"])
        )
    )
page = html(
    body(
        table(
            tr(
                th("Name"),
                th("Score")
            ),
            rows
        )
    )
)
return str(page)
```
---
# HTML
## Basic Page
```html
<!DOCTYPE html>
<html>
    <head>
        <title>Page</title>
    </head>
    <body>
        <h1>Title</h1>
         <p>Text</p>
    </body>
</html>
```
1. Heading
```html
<h1>Main Title</h1>
<h2>Small Title</h2>
```
2. Paragraph
```html
<p>Hello</p>
```
3. Image
```html
<img src="/static/image.jpg">
```
4. Link
```html
<a href="/">Home</a>
```
5. list
ol123
ul···
li（items）
6. Table
```html
<table>
    <tr>
        <th>Name</th>
        <th>Score</th>
    </tr>

    <tr>
        <td>Lola</td>
        <td>100</td>
    </tr>
</table>
```
7. Button
```html
<button>Submit</button>
```
8. Form
```html
<form action="/result" method="POST">
    <input type = "text">
</form>
```
other type
```html
<input type="radio" name="fav_colour" value="red">
<input type="checkbox" name="pets" value="cats">
```
## Get One Form Value
```python
name = request.form["name"]
```
## Get Checkbox Values
```python
pets = request.form.getlist("pets")
```
---
# Python Basics
1. Variable
```python
name = "Lola"
age = 20
```
2. Print
```python
print(name)
```
3. Input
```python
name = input("Name: ")
```
4. Convert To Integer
```python
age = int(age)
```
5. Convert To Float
```python
amount = float(amount)
```
6. Convert To String
```python
text = str(age)
```
7. type()
8. len()
9. .count()
10. .replace()
---
# If Statements
## If
```python
if age >= 18:
    print("adult")
```
## If Else
```python
if age >= 18:
    print("adult")
else:
    print("child")
```
## If Elif Else
```python
if score >= 65:
    print("CR")
elif score >= 50:
    print("PS")
else:
    print("FL")
```
## And
```python
if age > 18 and has_id == True:
    print("allowed")
```
## Or
```python
if colour == "red" or colour == "blue":
    print("valid")
```
## Not
```python
finished = False
if not finished:
    print("keep going")
```
---
# Loops
## For Loop
Use a for loop when looping through a list.
```python
for item in items:
    print(item)
```
## While Loop
Use a while loop when the loop continues until a condition changes.
```python
while len(password) < 8:
    password = input("Password: ")
print("excellent")
```
## Range
```python
for i in range(5):
    print(i)
```
## Count Items
```python
count = 0
for item in items:
    count += 1#num = num + 1
```
## Total Numbers
```python
total = 0
for number in numbers:
    total += number
```
---
# Lists
## List
```python
foods = ["apple", "rice", "egg"]
```
## Empty List
```python
items = []
```
## Add Item
```python
items.append("new_item")
```
## Check If Item Exists
```python
return item in items
```
## Search Item In List
```python
for player in players:
    if player["id"] == target:
        return player
return None
```
## Search With Two Conditions
```python
if item["id"] == target_id and item["time"] == target_time:
```
## Filter List
```python
result = []
for item in items:
    if condition:
        result.append(item)
return result
```
## show all items
```python
items_html = []
for item in data:
    items_html.append(...)
```
## Return None For Invalid Input
```python
if value not in valid_values:
    return None
```
## Loop Through List
```python
for food in foods:
    print(food)
```
## count things
```python
count = 0
for item in data:
    if condition:
        count += 1
```
## find highest
```python
best = data[0]

for item in data:
    if item["score"] > best["score"]:
        best = item
```
---
# Dictionaries
## Dictionary
```python
player = {
    "id": "p1",
    "name": "Lola",
    "score": 100
}
```
## Get Value
```python
player["name"]
```
```python
player.get("name")
```
## Change Value
```python
player["score"] = 120
```
## Add New Key
```python
player["faculty"] = "science"
```
## List Of Dictionaries
```python
players = [
    {
        "id": "p1",
        "name": "Lola",
        "score": 100
    },
    {
        "id": "p2",
        "name": "Sam",
        "score": 90
    }
]
```
## Loop Through List Of Dictionaries
```python
for player in players:
    print(player["name"])
```
## Build Dictionary
```python
machine_id = "A123"
time = "10:30"
alert = {
    "type": "unknown_machine",
    "machine_id": machine_id,
    "time": time
}
```
## Add Dictionary To List
```python
alerts = []
alerts.append(alert)
```
---
# Functions
## Function
```python
def add(a, b):
    return a + b
```
## Call Function
```python
answer = add(2, 3)
```
## Function With If
```python
def pass_or_fail(score):
    if score >= 50:
        return "pass"
    else:
        return "fail"
```
## Function With Loop
```python
def total(numbers):
    result = 0
    for number in numbers:
        result += number
    return result
```
## Search Function
```python
def get_player_by_id(players, target_id):
    for player in players:
        if player["id"] == target_id:
            return player
    return None
```
## Filter Function
```python
def get_high_scores(players):
    result = []
    for player in players:
        if player["score"] > 50:
            result.append(player)
    return result
```
---
# JSON
## Import JSON
```python
import json
```
## write JSON File
filename -> data.json
```python
def write_json_file(filename, info_to_save):

    my_file = open(filename, "w")

    json.dump(info_to_save, my_file)

    my_file.close()
```
## read JSON File
```python
def read_json_file(filename):

    my_file = open(filename, "r")

    information = json.load(my_file)

    my_file.close()

    return information
```
## create_if_not_exist()
```python
def create_if_not_exist(filename, empty_data):

    if not os.path.exists(filename):

        write_json_file(filename, empty_data)
```
## e.g.
### write json
```python
from jsonhelpers import *
restaurants = {...}
write_json_file("restaurants.json", restaurants)
```
### have json(read)
```python
from jsonhelpers import *
restaurants = read_json_file("restaurants.json")
print (restaurants)
```
### doesn't have json(read)
```python
from jsonhelpers import *
create_if_not_exist("parks.json")
parks = read_json_file("parks.json")
print (parks)
```
## JSON String -> Python
```python
data = json.loads(text)
```
## Python -> JSON String
```python
text = json.dumps(data)
```
## Load File
```python
import json
def load_data():
    try:
        with open("data.json") as file:
            return json.load(file)
    except:
        return []
```
## Save Function
```python
import json
def save_data(data):
    with open("data.json", "w") as file:
        json.dump(data, file)
```
---
# Cookies And Session
## Import Session
```python
from flask import session
```
## Secret Key
```python
app.secret_key = "secret"
```
## Read Session List
```python
history = session.get("history", [])
```
## Save Session List
```python
session["history"] = history
```
## Add To Session List
```python
history = session.get("history", [])
history.append("new item")
session["history"] = history
```
## Most Recent First
```python
history.insert(0, "new item")
session["history"] = history
```
## Clear Session
```python
session.clear()
```
## Clear Route
```python
@app.route("/clear")
def clear():
    session.clear()
    return redirect("/")
```
---
# CSS
main.py:
```python
import pyhtml as p
from flask import Flask
app = Flask(__name__)
@app.get("/")
def home():
    response = p.html(
        p.head(
            p.title("CSS Demo")
            p.link(rel="stylesheet", href="static/style.css")
        )
        p.body(
            h1()
        )
    )
    print(str(response))
    return str(response)
```
style.css:
```html
h1 {
    color:...;
    text-align: center:...;
}
body {
    background-color:...;
}
```
## Link CSS
```html
<link rel="stylesheet" href="/static/style.css">
```
```python
p.link(rel="stylesheet", href="static/style.css")
```
## Body
```css
body {
    font-family: Arial;
    background-color: #eef5ff;
    margin: 20px;
}
```
## Heading
```css
h1 {
    color: navy;
}
```
## Button
```css
button {
    padding: 8px;
    margin-top: 10px;
}
```
## Input
```css
input, select, textarea {
    display: block;
    margin: 8px 0;
    padding: 6px;
}
```
## Card
```css
.card {
    border: 1px solid black;
    padding: 12px;
    margin: 10px 0;
}
```
## Flexbox
```css
.container {
    display: flex;
    gap: 10px;
}
```
## Grid
```css
.container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
}
```
## Table
```css
table {
    border-collapse: collapse;
}

td, th {
    border: 1px solid black;
    padding: 8px;
}
```
---
# Errors
## KeyError
- Cause: The dictionary key does not exist.
player["name"]
- Fix:
player.get("name")
or check spelling.
## NameError
- Cause: The variable does not exist.
print(score)
- Fix: Create the variable before using it.
score = 0
print(score)
## IndentationError
- Cause: Python spacing is wrong.
Wrong:
if age > 18:
print("adult")
Correct:
if age > 18:
    print("adult")
## TypeError
- Cause: Wrong data type
Example:
age = "20"
age + 1
- Fix:
age = int(age)
age + 1
## NoneType Error
- Cause: A function returned None.
player = get_player_by_id(players, "abc")
print(player["name"])
- Fix: if player != None:
    print(player["name"])
## File Not Found
- Cause: The file path is wrong.
- Fix: Check the file name and folder.
---
# Q &. A note
## if-else vs for loop
An if-else statement is used to make a decision based on a condition.
A for loop is used to repeat code multiple times.
Example of if-else:
if age >= 18:
    print("Adult")
else:
    print("Child")
Example of for loop:
for number in [1, 2, 3]:
    print(number)

## HTML vs CSS vs Python
- HTML creates the structure and content of a web page.
- CSS controls the appearance and layout of the web page.
- Python handles logic, calculations, data, and server behaviour.
Example:
HTML creates a button. e.g.
<h1>Hello</h1>
CSS changes the colour of the button. e.g. h1 {
    color: blue;
}
Python decides what happens after the button is clicked.

## For Loop vs While Loop
- A for loop is used when the number of repetitions is known, or when looping through a list.
- A while loop is used when repetition continues until a condition changes.
Example for loop:
for item in items:
    print(item)
Example while loop:
while password != "correct":
    password = input("Password: ")
## If vs Elif
Separate if statements are checked independently.
elif only runs if the previous if condition was false.
Use separate if statements when more than one condition can be true.
Use elif when only one option should happen.

## Cookies vs Files
Cookies are better for storing small user data on the browser, such as login sessions or preferences.
Files or databases are better for storing large, permanent, or shared data.
Use cookies when:
•	data is small
•	data belongs to one user
•	data needs to stay in the browser
Use files/databases when:
•	data is large
•	data must be secure
•	multiple users need access

## Python package vs Web API
A Python package must be installed and used in Python programs.
A web API can be used by different programming languages through HTTP requests.
A package is faster and works offline.
A web API is more accessible and easier to share with many developers.
I would recommend a web API because more developers and applications can use it easily.
## Dictionaries
Dictionaries are useful for storing related information together.
They are also useful for looking up values using keys.
Saving example:
student = {
    "name": "Amy",
    "age": 20
}
Finding example:
player["name"]

## Prompt In Input
The prompt tells the user what information to enter.
It improves usability and reduces user confusion and input mistakes.
Example:
name = input("Enter your name: ")

## Designing a movie library
1.	Identify the data to store, such as title, genre, and rating.
2.	Use a dictionary to represent one movie.
movie = {
    "title": "Frozen",
    "genre": "Animation",
    "rating": 8
}
3.	Use a list to store multiple movies.
movies = [movie1, movie2]
4.	Test whether the structure is easy to search, update, and add data.
5.	Improve the structure if more information is needed.

## How to use usability heuristics to reduce user errors
The form may use labels and clear instructions to help users understand what to enter.
Validation can prevent invalid input.
Buttons, checkboxes, or clear labels can reduce mistakes.
These features improve usability and help prevent user errors.

---
# Useful experience
---
## Find Maximum
```python
largest = numbers[0]
for number in numbers:
    if number > largest:
        largest = number
```
## Find Player With Highest Score
```python
winner = players[0]
for player in players:
    if player["score"] > winner["score"]:
        winner = player
```
## Search By ID
```python
for item in items:
    if item["id"] == target_id:
        return item
return None
```
## Filter Matching Items(get items we want)
```python
result = []
for item in items:
    if item["type"] == target_type:
        result.append(item)
return result
```
## Check If All Conditions Match
```python
if light in plant["light"] and pet not in plant["toxic_to"]:
    result.append(plant["name"])
```
## Count Wins Draws Losses
```python
wins = 0
draws = 0
losses = 0
for game in games:
    if game["result"] == "win":
        wins += 1
    elif game["result"] == "draw":
        draws += 1
    elif game["result"] == "loss":
        losses += 1
```
## Page With Form
```python
@app.route("/")
def index():
    return """
    <h1>Search</h1>
    <form action="/result" method="POST">
        <input name="query">
        <button>Search</button>
    </form>
    """
```
## Page With Result
```python
@app.route("/result", methods=["POST"])
def result():
    query = request.form["query"]
    return f"""
    <h1>Result</h1>
    <p>You searched for: {query}</p>
    <a href="/">Back</a>
    """
```
## Page With List Result
```python
@app.route("/result", methods=["POST"])
def result():
    query = request.form["query"]
    results = []
    for item in items:
        if item["type"] == query:
            results.append(item)
    html = "<h1>Results</h1>"
    for item in results:
        html += f"<p>{item['name']}</p>"
    html += '<a href="/">Back</a>'
    return html
```
## Page With History
```python
@app.route("/history")
def history():
    history = session.get("history", [])
    html = "<h1>History</h1>"
    for item in history:
        html += f"<p>{item}</p>"
    html += '<a href="/">Back</a>'
    return html
```
---
# Usability
1. Consistency and Standards
The website uses a consistent layout, headings, buttons, and navigation links across all pages.
This helps users learn how to use the website more easily because the design stays similar on every page.
Example:
The home page, result page, and form page all use similar layouts and buttons.
2. Visibility of System Status
The website gives users feedback after they complete actions.
This helps users understand what happened after submitting a form or clicking a button.
Example:
After the user submits a form, the result page displays the submitted information and the result.
3. Error Prevention
The website reduces mistakes by using clear labels, buttons, checkboxes, and simple forms.
This helps prevent users from entering invalid information.
Example:
Users can select options using buttons or checkboxes instead of typing everything manually.
4. Clear Information
The interface shows important information clearly so users do not need to remember information from previous pages.
Example:
The page displays player names, scores, search history, results, or selected options.
5. User Control and Freedom
The website allows users to move between pages easily and clear data if needed.
Example:
The website includes Home links, Back links, or Clear buttons.
6. Readability
The website uses headings, spacing, tables, and simple labels to improve readability.
This makes the interface easier to understand.
Example:
Large headings and tables help users read information more clearly.
7. Aesthetic and Minimalist Design
The website uses a simple design with readable text and clear sections.
This prevents users from feeling overwhelmed.
Example:
The page avoids unnecessary colours, text, or complicated layouts.
## Future Improvements
If I had more time, I would improve usability further by adding better CSS styling, confirmation messages, error messages, or search and filter features.
