# COMP1010 Student Notes

## Python Basics

### Variables
```python
x = 10
name = "Tom"
price = 3.14
happy = True
```

### Input / Output
```python
name = input("Name: ")
age = int(input("Age: "))

print(name)
print(age)
print(f"{name} is {age}")
```

### Type Conversion
```python
int("123")
float("3.14")
str(123)
```

---

# Conditions

```python
if x > 0:
    print("positive")
elif x == 0:
    print("zero")
else:
    print("negative")
```

### Comparison Operators
```python
==
!=
>
<
>=
<=
```

### Logical Operators
```python
and
or
not
```

---

# Loops

## While Loop
```python
i = 0
while i < 5:
    print(i)
    i += 1
```

## For Loop
```python
for i in range(5):
    print(i)
```

## Range
```python
range(5)
range(1, 5)
range(1, 10, 2)
```

---

# Strings

## Common Functions
```python
s = "hello"

len(s)
s.upper()
s.lower()
s.strip()
```

## Slicing
```python
s[0]
s[-1]
s[1:4]
s[::-1]
```

## Search
```python
"a" in s
s.find("e")
```

## Split / Join
```python
text = "a,b,c"
lst = text.split(",")

"-".join(lst)
```

---

# Lists

## Create List
```python
nums = [1, 2, 3]
```

## List Operations
```python
nums.append(4)
nums.pop()
len(nums)
```

## Traverse List
```python
for n in nums:
    print(n)
```

## Sorting
```python
nums.sort()
sorted(nums)
```

---

# Dictionaries

## Create Dictionary
```python
student = {
    "name": "Tom",
    "age": 18
}
```

## Access
```python
student["name"]
student.get("age")
```

## Traverse Dictionary
```python
for key, value in student.items():
    print(key, value)
```

## Common Pattern
```python
if key not in d:
    d[key] = []
```

---

# Functions

## Basic Function
```python
def add(a, b):
    return a + b
```

## Call Function
```python
x = add(1, 2)
```

## Default Parameter
```python
def greet(name="Guest"):
    print(name)
```

---

# File Reading and Writing

## Read File
```python
with open("data.txt") as file:
    text = file.read()
```

## Read Line by Line
```python
with open("data.txt") as file:
    for line in file:
        print(line)
```

## Write File
```python
with open("data.txt", "w") as file:
    file.write("hello")
```

---

# Common Algorithms

## Sum
```python
total = 0

for n in nums:
    total += n
```

## Maximum
```python
largest = nums[0]

for n in nums:
    if n > largest:
        largest = n
```

## Count
```python
count = 0

for n in nums:
    if n % 2 == 0:
        count += 1
```

---

# List Comprehension

```python
squares = [x * x for x in range(5)]

evens = [x for x in nums if x % 2 == 0]
```

---

# Common Coding Questions

## Count Characters
```python
count = 0

for ch in s:
    if ch == "a":
        count += 1
```

## Reverse String
```python
s[::-1]
```

## Palindrome
```python
if s == s[::-1]:
    print("palindrome")
```

## Word Count
```python
words = text.split()

print(len(words))
```

## Longest Word
```python
longest = ""

for word in words:
    if len(word) > len(longest):
        longest = word
```

---

# group(strings)

```python
def group(strings):
    result = {}

    for s in strings:
        first = s[0]

        if first not in result:
            result[first] = []

        result[first].append(s)

    return result
```

---

# majority(votes)

```python
def majority(votes):
    counts = {}

    for v in votes:
        if v not in counts:
            counts[v] = 0

        counts[v] += 1

    for name in counts:
        if counts[name] > len(votes) / 2:
            return name

    return None
```

---

# HTML Basics

## Basic Structure
```html
<!DOCTYPE html>
<html>
<head>
    <title>Page</title>
</head>
<body>

<h1>Hello</h1>

</body>
</html>
```

## Common Tags
```html
<h1></h1>
<p></p>
<a href=""></a>
<img src="">
<ul></ul>
<li></li>
<div></div>
<form></form>
<input>
<button></button>
```

---

# CSS Basics

## Colors
```css
color: red;
background-color: blue;
```

## Font
```css
font-size: 20px;
font-family: Arial;
```

## Margin and Padding
```css
margin: 10px;
padding: 10px;
```

## Flexbox
```css
display: flex;
justify-content: center;
align-items: center;
```

---

# Flask Basics

## Basic Flask App
```python
from flask import Flask

app = Flask(__name__)

@app.get("/")
def home():
    return "Hello"

app.run()
```

## Return HTML
```python
@app.get("/")
def home():
    return """
    <h1>Hello</h1>
    """
```

## Routes
```python
@app.get("/")
@app.post("/")
```

---

# pyhtml Basics

```python
import pyhtml as p

page = p.html(
    p.body(
        p.h1("Hello")
    )
)

print(page)
```

---

# Debugging

## Missing Colon
```python
if x > 0:
```

## Indentation Error
```python
IndentationError
```

## Difference Between == and =
```python
== comparison
= assignment
```

## Common Errors
```python
IndexError
KeyError
TypeError
```

---

# Exam Reminders

## Useful Patterns

### Traverse List
```python
for x in nums:
```

### Traverse Dictionary
```python
for k, v in d.items():
```

### Check Membership
```python
if x in nums:
```

### Add to List
```python
lst.append(x)
```

---

# Web Development Notes

## HTML Page Layout
```html
<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>
<body>

<header>
    <h1>Website Title</h1>
</header>

<nav>
    <a href="/">Home</a>
</nav>

<main>
    <p>Hello World</p>
</main>

<footer>
    Footer Text
</footer>

</body>
</html>
```

---

# HTML Forms

## Text Input
```html
<input type="text">
```

## Password Input
```html
<input type="password">
```

## Number Input
```html
<input type="number">
```

## Checkbox
```html
<input type="checkbox">
```

## Submit Button
```html
<button type="submit">Submit</button>
```

## Full Form Example
```html
<form action="/submit" method="post">
    <input type="text" name="username">
    <button type="submit">Submit</button>
</form>
```

---

# CSS Notes

## Selectors
```css
h1 {
    color: red;
}

.classname {
    background-color: yellow;
}

#idname {
    font-size: 20px;
}
```

## Width and Height
```css
width: 100px;
height: 50px;
```

## Border
```css
border: 1px solid black;
```

## Border Radius
```css
border-radius: 10px;
```

## Display
```css
display: block;
display: inline;
display: flex;
```

## Positioning
```css
position: relative;
position: absolute;
```

---

# Flask Request Handling

## POST Request Example
```python
from flask import Flask
from flask import request

app = Flask(__name__)

@app.post("/submit")
def submit():
    username = request.form["username"]
    return username
```

## GET Parameters
```python
from flask import request

value = request.args.get("name")
```

## Redirect
```python
from flask import redirect

return redirect("/")
```

---

# Cookies

## Set Cookie
```python
from flask import make_response

response = make_response("Hello")
response.set_cookie("username", "Tom")

return response
```

## Read Cookie
```python
from flask import request

username = request.cookies.get("username")
```

---

# File Storage Example

## Save Data to File
```python
with open("users.txt", "a") as file:
    file.write(name + "
")
```

## Load Data from File
```python
with open("users.txt") as file:
    users = file.readlines()
```

---

# Useful String Methods

```python
s.isalpha()
s.isdigit()
s.islower()
s.isupper()
s.startswith("a")
s.endswith("z")
```

---

# Useful List Functions

```python
len(nums)
max(nums)
min(nums)
sum(nums)
```

---

# Useful Dictionary Functions

```python
len(d)
d.keys()
d.values()
d.items()
```

---

# Nested Data Structures

## List of Dictionaries
```python
students = [
    {"name": "Tom", "age": 18},
    {"name": "Amy", "age": 19}
]
```

## Dictionary of Lists
```python
d = {
    "fruit": ["apple", "banana"],
    "vegetables": ["carrot"]
}
```

---

# Searching Algorithms

## Linear Search
```python
found = False

for n in nums:
    if n == target:
        found = True
```

---

# Counting Frequency

```python
counts = {}

for item in items:
    if item not in counts:
        counts[item] = 0

    counts[item] += 1
```

---

# Sorting Example

```python
names.sort()
```

## Sort by Length
```python
names.sort(key=len)
```

---

# Reading CSV Style Data

```python
with open("data.txt") as file:
    for line in file:
        line = line.strip()
        parts = line.split(",")
```

---

# Common Patterns

## Accumulator Pattern
```python
total = 0

for n in nums:
    total += n
```

## Filtering Pattern
```python
result = []

for n in nums:
    if n % 2 == 0:
        result.append(n)
```

## Maximum Pattern
```python
largest = nums[0]

for n in nums:
    if n > largest:
        largest = n
```

---

# Common Mistakes

## Infinite Loop
```python
while True:
```

## Forgetting Return
```python
def add(a, b):
    return a + b
```

## Wrong Indentation
```python
if x > 0:
print(x)
```

---

# Complexity Notes

## O(n)
Single loop through data.

## O(n^2)
Nested loops.

---

# Exam Tips

## Before Coding
1. Read question carefully.
2. Identify input and output.
3. Write small steps.

## During Coding
1. Use meaningful variable names.
2. Test small parts.
3. Use print() for debugging.

## After Coding
1. Check indentation.
2. Check spelling.
3. Test edge cases.
4. Make sure return values are correct.

---

# Topics to Review

1. Functions
2. Loops
3. Strings
4. Lists
5. Dictionaries
6. File Reading and Writing
7. Flask
8. HTML
9. CSS
10. pyhtml
11. Cookies
12. Form Handling
13. Debugging
14. Data Structures
15. Searching and Counting

