SHUMIN GONG (Z5723587)



## if..if and if..elif difference (2)
The core difference is how they handle cases where both conditions are true.

Example A uses two separate `if` statements. Both conditions are evaluated independently:
- If both `condition1` and `condition2` are `True`, both `print("Condition 1")` and `print("Condition 2")` will execute.
- The two checks do not interfere with each other.

Example B uses an `if-elif` structure, which is mutually exclusive:
- If `condition1` is `True`, only `print("Condition 1")` runs, and the `elif` branch is never checked, even if `condition2` is also `True`.
- The `elif` branch only runs if `condition1` is `False` and `condition2` is `True`.


## HTML and CSS different (3)
HTML (HyperText Markup Language) and CSS (Cascading Style Sheets) are the two core technologies for building websites, but they serve completely different purposes.

### 1. Core Difference & Purpose
- **HTML** is the **markup language** that defines the *structure, content, and meaning* of a web page. It answers the question: *"What is this content?"* (e.g., a heading, a paragraph, an image).
- **CSS** is the **style sheet language** that defines the *presentation, layout, and visual appearance* of HTML elements. It answers the question: *"How should this content look?"* (e.g., color, size, spacing, position).

### 2. Examples
- **HTML Example**: This code creates a basic heading and paragraph, defining the content but not its style:
  ```html
  <h1>Welcome to My Page</h1>
  <p>This is my first website.</p>

## check_word return True (5)
The function `check_word(word)` returns `True` if **at least one of the following two conditions is satisfied**:

1.  **Condition 1 (Length and 'n')**:
    - The length of the string `word` is exactly 7 characters (`len(word) == 7`).
    - The string contains the character `'n'` (`'n' in word`).
    - Example: `'penguin'` (length 7, contains 'n') returns `True`.

2.  **Condition 2 (Character pattern)**:
    - The second character (index 1) is `'m'` (`word[1] == 'm'`).
    - The first character (index 0) is equal to the third character (index 2) (`word[0] == word[2]`).
    - Example: `'amaze'` (index 1 is 'm', index 0 and 2 are both 'a') returns `True`.

A word will return `False` only if it fails both conditions. For example, `'test'` (length too short, does not match the pattern) returns `False`.


## two major for dictionaries (2)
The two major uses of dictionaries in data structure design are:

1.  **Fast key-based lookups (associative mapping)**
    Dictionaries store data as key-value pairs, allowing near-constant time (O(1)) access to values using their corresponding keys. This makes them ideal for building index structures, such as:
    -   A phone book, where names (keys) map to phone numbers (values)
    -   A frequency counter, where words (keys) map to their occurrence counts (values)
    They eliminate the need to search through lists sequentially, which drastically improves lookup efficiency.

2.  **Structured data representation**
    Dictionaries can be used to model complex, structured data by grouping related attributes together. Each key represents a property, and its value stores the corresponding data. This allows you to create self-documenting, flexible records, such as:
    -   A user profile, with keys like `'name'`, `'age'`, and `'email'`
    -   A game state, with keys like `'score'`, `'lives'`, and `'inventory'`
    They act like lightweight objects, making the data easier to read, modify, and pass around.


## cause for this error (3)
The error shown is a Python `KeyError: 'Simon'`, which occurs at line 18 in the function `validate_login`, where the code tries to access `login_data_store[username]`.

### Potential Cause
The crash happens because the dictionary `login_data_store` does not contain the key `'Simon'`. When the program tries to retrieve the password for the username `'Simon'` using square bracket notation (`dict[key]`), Python throws a `KeyError` if the key is not present.

Common reasons for this include:
- The user `'Simon'` is not registered in the system and was never added to the dictionary.
- The username is misspelled (e.g., case differences like `'simon'` vs `'Simon'`).
- The login data store is incomplete or failed to load properly.

### Prevention
The error can be prevented by safely checking for the key before accessing it, using one of these methods:
1.  **Use the `.get()` method** to safely retrieve values with a default fallback:
    ```python
    user_password = login_data_store.get(username, None)


## assess q3_server (5)
The form in `q3_server.py` uses several usability heuristics to prevent user error, primarily through input constraints, clear guidance, and structured interaction:

1.  **Mandatory field enforcement**
    Required fields (marked with the `required` HTML attribute) ensure users cannot submit the form without completing essential questions, preventing incomplete submissions.

2.  **Restricted input types and ranges**
    The form uses specific input types to eliminate invalid data at the source:
    - `type="number"` for the salt question, ensuring only numeric values can be entered.
    - `type="range"` (sliders) for the potato weight questions, limiting values to a predefined 0–5 kg range, which prevents typos and out-of-range entries.
    - The sliders also include visual ticks (via `<datalist>`) to guide the user toward valid values.

3.  **Clear labels and question structure**
    Each input has an explicit, descriptive label (e.g., "Recipe name:", "Minimum potato weight:"). This reduces ambiguity, ensuring users understand exactly what information is needed.

4.  **Password input security**
    The password field uses `type="password"`, which masks input characters. This prevents accidental shoulder-surfing and reduces the risk of exposing sensitive information, even though the password is not validated.

5.  **Form validation and feedback**
    The server provides immediate feedback after submission, confirming whether the answers were correct. This helps users learn from mistakes and correct their responses, aligning with the heuristic of "error prevention and recovery".

Overall, the design prioritizes preventing errors before they happen by guiding and restricting user input, rather than just handling errors after submission.

## when using input (2)
In Python's `input()` function, the `prompt` parameter is the text shown to the user before they type. It is critical in terminal-based programs for the following reasons:

1.  **User guidance and clarity**
    Without a prompt, the terminal will only show a blank cursor, leaving the user unsure of what to enter. The prompt explicitly tells the user what kind of input is needed (e.g., "Enter your age: " or "Please type a number: "), preventing confusion and guesswork.

2.  **Preventing user error**
    By clearly stating the required format or type of input (e.g., "Enter a whole number between 1 and 10: "), the prompt helps users provide valid data on the first try, reducing invalid inputs that could cause the program to crash or behave unexpectedly.

3.  **Improving usability and user experience**
    A good prompt makes the program feel responsive and interactive. It creates a natural conversation flow in the terminal, making the program easier to use, even for users who are not familiar with the code.

In short, the prompt is essential for making terminal-based programs usable, clear, and robust.


## Pythn package or web API (3)
Roger has two main options to share his Elvish translation code: as a Python package or as a web API. They differ significantly in how other developers will use his work.

### 1. Python Package
A Python package is distributed as installable code (e.g., via PyPI). Developers use it by:
- Installing it directly into their Python environment (e.g., `pip install elvish-translator`).
- Importing it into their own code (e.g., `from elvish_translator import translate`).
- Calling functions or classes locally, without needing an internet connection.

**Key traits**: Tied to Python, fast (no network overhead), and requires the user to manage updates and dependencies themselves.

### 2. Web API
A web API exposes the functionality over HTTP, usually via a server endpoint (e.g., `POST /translate`). Developers use it by:
- Sending HTTP requests to the API server with input text.
- Receiving translated text as a response, usually in JSON format.
- Working with it from any programming language or platform, as long as they have internet access.

**Key traits**: Language-agnostic, requires network access, and relies on the API server being online and maintained.

### Recommendation
Since Roger wants to make his work accessible to *other software developers in their own software*, a **web API** is the better choice. It allows developers using any language (not just Python) to integrate the translator, making it far more widely usable. If Roger expects most users to be Python developers only, a package would be simpler, but for maximum accessibility, the API is preferred.

## using Python lists and dictionaries (5)
To design a data structure for a movie library using only lists and dictionaries, we combine the two to create a clear, organised, and practical structure.

First, a **dictionary** is used to represent one individual movie. Each dictionary uses keys such as 'title', 'genre', 'year', 'rating', and 'director' to store related values. This allows easy access to each detail of a movie and keeps the data well-structured.

Second, a **list** is used as the main movie library to store all the movie dictionaries. The list acts as a collection, making it simple to add new movies, remove movies, loop through all items, and access any movie by its position.

Together, the list provides order and collection management, while dictionaries provide clear attribute storage for each movie. This structure is easy to understand, efficient to use, and fully meets the requirements of modelling a movie library.

Example structure:
[
    {"title": "Movie A", "genre": "Action", "year": 2020},
    {"title": "Movie B", "genre": "Comedy", "year": 2021}
]


## if-else VS for (2)
The key difference between an `if-else` statement and a `for` loop lies in their purpose: one makes decisions, the other repeats actions.

- An `if-else` statement is used for **conditional decision-making**. It checks whether a condition is true or false, and runs different blocks of code based on the result.
  Example: We might use it to decide if a student has passed or failed an exam.
  ```python
  if score >= 50:
      print("Passed")
  else:
      print("Failed")


## cookies VS file (2)
When choosing between cookies and server-side storage (files/databases) in a web application, the key factors are data size, persistence, sensitivity, and access location.

**When to use cookies:**
- The data is small (max ~4KB), such as session IDs, user preferences, or a simple "remember me" flag.
- The data only needs to be stored on the client side, and the server does not need to keep a permanent record.
- The data is non-sensitive and can be safely sent with every HTTP request.
Example: Storing a user's preferred language setting so the site loads in their language on every visit.

**When to use a file or database:**
- The data is large or complex, such as user profiles, order history, or uploaded content.
- The data needs to be stored securely on the server and persist across devices.
- The data is sensitive (like passwords or personal information) and should never be exposed to the client.
Example: Storing a user's account details and past purchases in a database.

In short, cookies are best for small, client-side preferences, while files/databases are for larger, permanent, or sensitive data.


## data structures (6)
When comparing the two data structures for storing course prerequisites, each has distinct advantages and disadvantages for implementing the `find_prereqs()` function.

### Structure 1 (List of dictionaries)
**Advantages:**
- This format is explicit and self-contained: each dictionary clearly lists a course code and all the courses it is a prerequisite *for*.
- It is flexible and can easily be extended to include additional metadata about each relationship if needed.
- It is human-readable and closely mirrors the way the diagram is drawn.

**Disadvantages:**
- Finding the prerequisites for a given course requires iterating through the entire list and checking every dictionary. This linear search is inefficient (O(n)) for large datasets.
- The logic for `find_prereqs()` becomes more complex, as you must loop through all entries to build the prerequisite chain.

---

### Structure 2 (Dictionary of lists)
**Advantages:**
- This format is optimised for direct lookups. You can immediately get the prerequisites for any course using `prereqs_2[course_code]`, which is very fast (O(1)).
- Implementing the recursive logic for `find_prereqs()` is far simpler. You can directly access the prerequisites list for a course without looping through unrelated data.

**Disadvantages:**
- It is less flexible if you need to add more information about each relationship.
- It is a direct mapping from course to prerequisites, which is less explicit about the reverse relationships shown in the diagram.

---

### Recommendation
For the `find_prereqs()` function, **Structure 2 is strongly preferred**.

The primary task of the function is to take a course code and find its prerequisites. Structure 2 directly supports this use case with its fast lookups, making the implementation both more efficient and simpler to write. The recursion becomes trivial, as you can always get the prerequisites list for any course in constant time.



## for VS while (3)
The core difference between a `for` loop and a `while` loop lies in how they control iteration:
- A `for` loop is used to iterate over a known sequence (like a list, range, or string). It automatically manages the iteration variable and terminates when the sequence is exhausted.
- A `while` loop runs as long as a given condition remains `True`. It is controlled by an external condition, and you must manage the loop variable and termination yourself.

---

**When to prefer a `for` loop over a `while` loop:**
Use a `for` loop when you know the number of iterations in advance, or when you need to process every item in a collection.
Example: Printing every item in a list of student names.
- ```python
    for name in student_names:
    print(name)

## html VS css VS python (3)
When building a web page, HTML, CSS, and Python each serve distinct purposes and are introduced at different stages of development:

1.  **HTML is always necessary as the foundation**
    HTML (HyperText Markup Language) defines the structure and content of the page. It is required for every web page, as it creates the basic elements like headings, paragraphs, images, and links. Without HTML, there is no page to display.

2.  **CSS is introduced when styling is needed**
    CSS (Cascading Style Sheets) controls the visual appearance of HTML elements, such as colors, fonts, spacing, and layout. It is needed when you want to make the page look clean, responsive, and visually appealing, rather than using the default browser styling.

3.  **Python is introduced for server-side functionality**
    Python is used on the server to handle dynamic logic that cannot be done with just HTML and CSS. It is needed when you require:
    - Dynamic content (e.g., displaying user-specific data)
    - Handling form submissions and database operations
    - Implementing user authentication or APIs
    Python is not required for simple static pages, but it becomes essential for interactive, data-driven web applications.


## data structures (plant)(6)
### Comparison of get_plants_1() and get_plants_2() data structures

#### Structure 1 (get_plants_1)
Structure 1 returns a **list of dictionaries**. Each dictionary represents one plant, with keys for "name", "lighting", and "toxic_to". All information about a plant is grouped together.

#### Structure 2 (get_plants_2)
Structure 2 returns a **dictionary of lists**. It is organised by categories such as "sun", "part shade", "full shade", "dogs", and "cats", with each key mapping to a list of plant names that fit that category.

### Advantages of Structure 1
- All information for one plant is stored together, making it easy to read, loop through, and access full details of any plant.
- It clearly shows which lighting conditions each plant supports and which pets it is toxic to.
- It is simple to add new plants or modify existing ones without breaking other entries.

### Advantages of Structure 2
- It allows **fast lookups** by lighting or pet safety. For example, we can immediately get all sun‑loving plants using data["sun"].
- It is optimised for filtering use cases, such as showing plants safe for cats or plants that grow in shade.
- It avoids looping through the whole dataset when searching by category.

### Best structure for the plant recommender
**Structure 2 is better for the plant recommender.**
The app needs to quickly find plants that match user inputs (lighting and pet safety). Structure 2 supports direct, fast lookups for these categories, making the code simpler and more efficient. Structure 1 would require looping through every plant to filter matches, which is less convenient for this task.


# Usability
## designed to improve usability(5)
#### Usability Assessment of the Tournament App UI

The tournament app’s user interface was designed with several usability heuristics in mind to improve the user experience. Below is a breakdown of the key features and planned improvements:

---

#### 1. Visibility of System Status
The app provides clear feedback to users at every step:
- When a match is saved or a bracket is updated, a success message is displayed.
- When an invalid input is submitted (e.g., a score that is not a number), an explicit error message appears, letting the user know what went wrong.
This follows the heuristic of keeping users informed about what is happening.

#### 2. Match Between System and Real World
The interface uses labels and terminology that align with how users think about tournaments:
- Terms like “Player 1 vs Player 2”, “Winner advances to”, and “Start New Tournament” are used instead of technical jargon.
- The tournament bracket layout visually represents the structure of a competition, making it easy to understand the flow of matches.

#### 3. User Control and Freedom
The app allows users to correct mistakes easily:
- A “Reset” button is provided to clear the form and start over.
- The back button works as expected, letting users navigate away from a page without losing their progress unnecessarily.

#### 4. Consistency and Standards
All interactive elements follow consistent patterns:
- Buttons have a uniform style, so users can quickly identify actionable elements.
- Form fields use the same label placement and error styling throughout the app, reducing the learning curve.

---

#### Planned Improvements (If not fully implemented)
If I were to improve the app further, I would add the following features based on usability heuristics:
1.  **Error Prevention**: Add client-side validation to the score input fields to prevent users from entering non-numeric values before they submit the form.
2.  **Help and Documentation**: Add a simple “How It Works” section to explain how to use the bracket generator, especially for users unfamiliar with tournament structures.
3.  **Flexibility and Efficiency of Use**: Implement keyboard shortcuts for common actions like “Save Match” or “Start Tournament” to speed up use for advanced users.
4.  **Aesthetic and Minimalist Design**: Reduce clutter by hiding less critical information by default and revealing it on hover, making the interface cleaner and less overwhelming.


## critique the usability of your web page（6）
### Usability Critique of the Web Pages

#### ✅ User-Friendly Features
The web pages incorporate several usability principles that make them intuitive to use:

1.  **Visibility of System Status**
    The interface keeps users informed about what is happening at every step.
    - Form submissions provide clear success or error messages, so users know immediately if their action worked.
    - Required fields are marked, preventing users from submitting incomplete forms.

2.  **Match Between System and Real World**
    The design uses familiar, plain language and concepts that align with the user’s mental model.
    - Form labels and page titles use simple, descriptive terms (e.g., "Add New Item" or "View Your List") instead of technical jargon.
    - The layout follows a predictable structure: navigation bar at the top, main content in the center, which users expect.

---

#### 🛠️ Areas for Improvement
The usability could be further enhanced with the following changes, referencing additional Nielsen heuristics:

1.  **Consistency and Standards**
    Currently, some interactive elements like buttons and links have inconsistent styling across pages.
    - *Improvement*: Standardize the appearance of all buttons (colors, size, hover effects) so users can quickly identify actionable items anywhere on the site.

2.  **Error Prevention and Recovery**
    The forms lack proactive measures to prevent user errors.
    - *Improvement*: Add client-side validation to catch invalid inputs (e.g., wrong email format) before submission. Also, implement a confirmation step for destructive actions like "Delete" to prevent accidental data loss.

3.  **Help and Documentation**
    There is no guidance for first-time users.
    - *Improvement*: Add simple tooltips or a short "How to" guide to explain the purpose of each page and form, especially for more complex tasks.

## If your app has these usability issues(5)
### Usability Critique and Improvement Plan

The current UI has usability issues around the distinction between merging a new timeline with the existing one, and validating a new timeline from scratch. This violates the heuristic of **Visibility of System Status** — users are unsure which operation they are performing and what the system is doing.

#### How to resolve the issues
1.  **Clear visual separation of actions**
    - Use distinct buttons for the two operations: "Merge with Current Timeline" and "Validate New Timeline". Each button should have a different style and be placed in separate sections.
    - Add descriptive labels next to each button explaining what it does. This follows the **Match Between System and Real World** heuristic, using clear, real-world terms.

2.  **Display the current timeline state**
    - Use the `timeline_to_html` function from `utils.py` to render the current timeline on the page. This lets users see exactly what they are merging with, improving visibility of system status.

3.  **Confirmation feedback**
    - After an action completes, display a clear success message: "New timeline merged successfully" or "New timeline validated successfully". This confirms the action and keeps the user informed.

#### Planned improvements
The planned changes will make the navigation clear by separating actions, showing the current state, and providing feedback. This addresses the original usability problems and improves the overall user experience.


## If these usability issues are not presen (5)
### Usability Critique of the Timeline App

My app’s UI is designed to be easy to navigate, ensuring users clearly understand the difference between merging a timeline and validating a new one.

#### Design choices for usability
1.  **Distinct actions with clear labels**
    - Two separate, clearly labeled buttons are provided: "Merge with Current Timeline" and "Validate New Timeline". They are placed in separate sections with different styling, so users cannot confuse them. This follows the **Consistency and Standards** heuristic, making the interface predictable.

2.  **Always visible current timeline**
    - The `timeline_to_html` function from `utils.py` is used to display the current timeline on the page at all times. This gives users full visibility of the system state before they perform any operation, adhering to the **Visibility of System Status** heuristic.

3.  **Clear feedback after every action**
    - After any operation, a success or error message is displayed, confirming what happened. Users are always aware of the result of their actions.

Because of these design choices, the interface is intuitive and easy to navigate, with no ambiguity about which operation is being performed.

## list at least two usability（8）
# Usability Features of the Website

This website follows several usability heuristics to improve the user experience. Below are two key examples, with explanations of how they are implemented.

---

## 1. Visibility of System Status
This heuristic means the system should always keep users informed about what is happening, through appropriate feedback within reasonable time.

**Implementation on this site:**
- All form submissions provide clear feedback. When a user submits data, a success or error message is displayed immediately, confirming whether the action worked.
- Required fields are marked with a `*` and error messages explain what needs to be fixed (e.g., "Email is required" or "Password must be at least 8 characters").
- The navigation bar always highlights the current page, so users know exactly where they are in the site.

---

## 2. Consistency and Standards
This heuristic states that users should not have to wonder whether different words, situations, or actions mean the same thing. The site should follow platform conventions.

**Implementation on this site:**
- Interactive elements like buttons and links have consistent styling across all pages. All primary action buttons use the same color, shape, and hover effect, so users can quickly identify them.
- The layout follows a standard structure: a navigation bar at the top, main content in the center, and a footer at the bottom. This familiar pattern reduces the learning curve.
- Terminology is consistent throughout the site (e.g., the word "Submit" is always used for form buttons, not "Save" or "Confirm" interchangeably).
