0% found this document useful (0 votes)
48 views70 pages

Course Material

Uploaded by

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

Course Material

Uploaded by

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

Week 1: Introduction to Python and Basic Syntax

Presentation:

Introduction to Python

History and Features of Python

Python vs Other Programming Languages

Setting Up Python Environment

Installing Python

Introduction to IDEs: Mu editor, Anaconda, Jupyter Notebooks, VS


Code

Writing and Running Your First Python Script

Basic Syntax

Variables and Data Types

Basic Operators (Arithmetic, Comparison, Logical)

Input and Output

Comments and Documentation

Project: Simple Calculator

Requirements

Walkthrough

Notes:

Introduction to Python

Python is an interpreted, high-level, general-purpose programming


language.

Emphasises code readability with its use of significant whitespace.


Supports multiple programming paradigms, including procedural,
object-oriented, and functional programming.

Setting Up Python Environment

Download and install Python from python.org.

Install Anaconda for a comprehensive environment or use VS


Code/Jupyter for lightweight development.

Example first script:


print("Hello, World!")

Basic Syntax

Variables and Data Types


python
Copy code
x = 10 # Integer

y = 10.5 # Float

name = "Alice" # String

Basic Operators
python
Copy code
# Arithmetic

result = x + y

# Comparison

is_equal = (x == y)

# Logical

is_true = (x > y) and (y < 15)


Input and Output
python
Copy code
user_input = input("Enter a number: ")

print("You entered:", user_input)

Comments and Documentation


python
Copy code
# This is a single-line comment

"""

This is a

multi-line comment

"""

def greet():

"""This function greets the user."""

print("Hello, User!")

Project: Simple Calculator

Create a program that can perform addition, subtraction,


multiplication, and division.

Example implementation:
python
Copy code
def add(x, y):

return x + y

def subtract(x, y):

return x - y

def multiply(x, y):

return x * y

def divide(x, y):

if y != 0:

return x / y

else:

return "Error! Division by zero."

print("Select operation:")

print("1.Add")

print("2.Subtract")

print("3.Multiply")

print("4.Divide")
choice = input("Enter choice(1/2/3/4): ")

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

if choice == '1':

print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':

print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':

print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':

print(num1, "/", num2, "=", divide(num1, num2))

else:

print("Invalid input")
Week 2: Control Structures

Presentation:

Conditional Statements

if, elif, else

Nested Conditions

Loops

for Loop

while Loop

Nested Loops

Loop Control Statements: break, continue

Project: Number Guessing Game

Requirements

Walkthrough

Notes:

Conditional Statements

if, elif, else


python
Copy code
age = 20

if age < 18:

print("Minor")

elif age >= 18 and age < 65:

print("Adult")

else:
print("Senior")

Nested Conditions
python
Copy code
num = 10

if num >= 0:

if num == 0:

print("Zero")

else:

print("Positive number")

else:

print("Negative number")

Loops

for Loop
python
Copy code
for i in range(5):

print(i)

while Loop
python
Copy code
count = 0
while count < 5:

print(count)

count += 1

Nested Loops
python
Copy code
for i in range(3):

for j in range(3):

print(i, j)

Loop Control Statements


python
Copy code
for i in range(10):

if i == 5:

break

print(i)

for i in range(10):

if i % 2 == 0:

continue

print(i)
Project: Number Guessing Game

Create a game where the computer randomly selects a number


and the user has to guess it within a certain number of attempts.

Example implementation:
python
Copy code
import random

def guess_number():

number_to_guess = random.randint(1, 100)

attempts = 0

max_attempts = 10

while attempts < max_attempts:

guess = int(input("Guess the number (between


1 and 100): "))

attempts += 1

if guess < number_to_guess:

print("Too low!")

elif guess > number_to_guess:

print("Too high!")

else:
print(f"Congratulations! You've guessed
the number in {attempts} attempts.")

break

if attempts == max_attempts:

print(f"Sorry, you've reached the maximum


attempts. The number was {number_to_guess}.")

guess_number()

Week 3: Functions and Modules

Presentation:

Functions

Defining and Calling Functions

Function Parameters and Return Values

Scope of Variables

Modules

Importing Modules

Standard Library Modules

Creating and Using Custom Modules

Project: Basic To-Do List Application

Requirements

Walkthrough
Notes:

Functions

Defining and Calling Functions


python
Copy code
def greet(name):

print(f"Hello, {name}!")

greet("Alice")

Function Parameters and Return Values


python
Copy code
def add(a, b):

return a + b

result = add(5, 3)

print(result)

Scope of Variables
python
Copy code
def my_function():

local_var = 10

print(local_var)
my_function()

# print(local_var) # This will raise an error

global_var = 20

def my_function():

print(global_var)

my_function()

Modules

Importing Modules
python
Copy code
import math

print(math.sqrt(16))

Standard Library Modules


python
Copy code
import datetime

now = datetime.datetime.now()

print(now)
Creating and Using Custom Modules
python
Copy code
# In a file named mymodule.py

def greet(name):

print(f"Hello, {name}!")

# In another file

import mymodule

mymodule.greet("Alice")

Project: Basic To-Do List Application

Create a simple console-based to-do list application that allows


users to add, remove, and view tasks.

Example implementation:
python
Copy code
def show_menu():

print("1. Add task")

print("2. View tasks")

print("3. Remove task")

print("4. Exit")
def add_task(tasks):

task = input("Enter a task: ")

tasks.append(task)

print("Task added!")

def view_tasks(tasks):

if not tasks:

print("No tasks to show.")

else:

for i, task in enumerate(tasks, start=1):

print(f"{i}. {task}")

def remove_task(tasks):

view_tasks(tasks)

task_num = int(input("Enter the task number to


remove: "))

if 0 < task_num <= len(tasks):

tasks.pop(task_num - 1)

print("Task removed!")

else:

print("Invalid task number.")


def main():

tasks = []

while True:

show_menu()

choice = input("Enter your choice: ")

if choice == '1':

add_task(tasks)

elif choice == '2':

view_tasks(tasks)

elif choice == '3':

remove_task(tasks)

elif choice == '4':

print("Goodbye!")

break

else:

print("Invalid choice. Please try


again.")

if __name__ == "__main__":

main()
Week 4: Data Structures

Presentation:

Lists

Creating Lists

Accessing Elements

List Methods (append, remove, etc.)

List Comprehensions

Tuples

Creating Tuples

Accessing Elements

Tuple Methods

Sets

Creating Sets

Set Operations (union, intersection, etc.)

Set Methods

Dictionaries

Creating Dictionaries

Accessing Values

Dictionary Methods (get, keys, values, etc.)

Dictionary Comprehensions

Project: Contact Book

Requirements
Walkthrough

Notes:

Lists

Creating Lists
python
Copy code
fruits = ["apple", "banana", "cherry"]

Accessing Elements
python
Copy code
print(fruits[0]) # Output: apple

List Methods
python
Copy code
fruits.append("orange")

fruits.remove("banana")

List Comprehensions
python
Copy code
numbers = [x for x in range(10)]

Tuples

Creating Tuples
python
Copy code
coordinates = (10, 20)

Accessing Elements
python
Copy code
print(coordinates[0]) # Output: 10

Tuple Methods
python
Copy code
print(coordinates.count(10)) # Output: 1

Sets

Creating Sets
python
Copy code
unique_numbers = {1, 2, 3, 4}

Set Operations
python
Copy code
set1 = {1, 2, 3}

set2 = {3, 4, 5}

print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}

print(set1.intersection(set2)) # Output: {3}


Set Methods
python
Copy code
unique_numbers.add(5)

unique_numbers.remove(3)

Dictionaries

Creating Dictionaries
python
Copy code
phonebook = {"Alice": "123-4567", "Bob": "234-5678"}

Accessing Values
python
Copy code
print(phonebook["Alice"]) # Output: 123-4567

Dictionary Methods
python
Copy code
print(phonebook.get("Alice")) # Output: 123-4567

print(phonebook.keys()) # Output:
dict_keys(['Alice', 'Bob'])

print(phonebook.values()) # Output:
dict_values(['123-4567', '234-5678'])

Dictionary Comprehensions
python
Copy code
squares = {x: x*x for x in range(6)}

Project: Contact Book

Create a program to manage contacts using dictionaries. The user


can add, delete, and search for contacts.

Example implementation:
python
Copy code
def show_menu():

print("1. Add contact")

print("2. View contacts")

print("3. Remove contact")

print("4. Search contact")

print("5. Exit")

def add_contact(contacts):

name = input("Enter contact name: ")

phone = input("Enter contact phone: ")

contacts[name] = phone

print("Contact added!")

def view_contacts(contacts):
if not contacts:

print("No contacts to show.")

else:

for name, phone in contacts.items():

print(f"Name: {name}, Phone: {phone}")

def remove_contact(contacts):

name = input("Enter the contact name to remove:


")

if name in contacts:

del contacts[name]

print("Contact removed!")

else:

print("Contact not found.")

def search_contact(contacts):

name = input("Enter the contact name to search:


")

if name in contacts:

print(f"Name: {name}, Phone:


{contacts[name]}")

else:
print("Contact not found.")

def main():

contacts = {}

while True:

show_menu()

choice = input("Enter your choice: ")

if choice == '1':

add_contact(contacts)

elif choice == '2':

view_contacts(contacts)

elif choice == '3':

remove_contact(contacts)

elif choice == '4':

search_contact(contacts)

elif choice == '5':

print("Goodbye!")

break

else:

print("Invalid choice. Please try


again.")
if __name__ == "__main__":

main()

Week 5: File Handling

Presentation:

1.Introduction to File Handling


○ Types of Files: Text and Binary
○ Opening and Closing Files
○ Reading and Writing to Files
2.Working with Text Files
○ Reading entire file content
○ Reading line by line
○ Writing and appending to files
3.Working with CSV Files
○ Reading from CSV files
○ Writing to CSV files
4.Exception Handling in File Operations
○ Using try-except blocks
5.Project: Student Grades Management
○ Requirements
○ Walkthrough

Notes:

1.Introduction to File Handling


○ Python provides built-in functions to open,
read, write, and close files.

Opening and Closing Files


python
Copy code
file = open("example.txt", "r") # Open for reading

file.close() # Close the file


2.Working with Text Files

Reading Entire File Content


python
Copy code
with open("example.txt", "r") as file:

content = file.read()

print(content)

Reading Line by Line


python
Copy code
with open("example.txt", "r") as file:

for line in file:

print(line, end="")

Writing and Appending to Files


python
Copy code
with open("example.txt", "w") as file:

file.write("Hello, World!")
with open("example.txt", "a") as file:

file.write("\nAppended text.")


3.Working with CSV Files

Reading from CSV Files


python
Copy code
import csv

with open("data.csv", "r") as file:

reader = csv.reader(file)

for row in reader:

print(row)

Writing to CSV Files


python
Copy code
import csv

data = [["Name", "Age"], ["Alice", 24], ["Bob", 30]]

with open("data.csv", "w", newline='') as file:

writer = csv.writer(file)
writer.writerows(data)


4.Exception Handling in File Operations

Using try-except Blocks


python
Copy code
try:

with open("example.txt", "r") as file:

content = file.read()

print(content)

except FileNotFoundError:

print("File not found.")

except IOError:

print("An error occurred while reading the


file.")


5.Project: Student Grades Management
○ Create a program to manage student grades,
allowing the user to input grades, save them
to a file, and read them back for analysis.

Example implementation:
python
Copy code
import csv
def show_menu():

print("1. Add grade")

print("2. View grades")

print("3. Exit")

def add_grade(filename):

name = input("Enter student name: ")

grade = input("Enter grade: ")

with open(filename, "a", newline='') as file:

writer = csv.writer(file)

writer.writerow([name, grade])

print("Grade added!")

def view_grades(filename):

try:

with open(filename, "r") as file:

reader = csv.reader(file)

for row in reader:

print(f"Name: {row[0]}, Grade:


{row[1]}")

except FileNotFoundError:
print("No grades found.")

def main():

filename = "grades.csv"

while True:

show_menu()

choice = input("Enter your choice: ")

if choice == '1':

add_grade(filename)

elif choice == '2':

view_grades(filename)

elif choice == '3':

print("Goodbye!")

break

else:

print("Invalid choice. Please try


again.")

if __name__ == "__main__":

main()


Week 6: Object-Oriented Programming (OOP)

Presentation:

1.Introduction to OOP
○ Concepts: Classes and Objects
○ Benefits of OOP
2.Defining Classes and Creating Objects
○ Defining a class
○ Creating instances (objects) of a class
3.Attributes and Methods
○ Instance attributes and methods
○ Class attributes and methods
4.Inheritance and Polymorphism
○ Inheriting from a base class
○ Method overriding
5.Project: Library Management System
○ Requirements
○ Walkthrough

Notes:

1.Introduction to OOP
○ OOP is a programming paradigm based on the
concept of objects, which can contain data
and code.
○ Benefits include code reuse, scalability, and
ease of maintenance.
2.Defining Classes and Creating Objects

Defining a Class
python
Copy code
class Dog:
pass

Creating Instances
python
Copy code
my_dog = Dog()


3.Attributes and Methods

Instance Attributes and Methods


python
Copy code
class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

print(f"{self.name} is barking!")

my_dog = Dog("Rex", 5)

my_dog.bark() # Output: Rex is barking!

Class Attributes and Methods


python
Copy code
class Dog:

species = "Canis familiaris" # Class attribute

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

print(f"{self.name} is barking!")

print(Dog.species) # Output: Canis familiaris


4.Inheritance and Polymorphism

Inheriting from a Base Class


python
Copy code
class Animal:

def __init__(self, name):

self.name = name

def speak(self):

pass
class Dog(Animal):

def speak(self):

return "Woof!"

class Cat(Animal):

def speak(self):

return "Meow!"

my_dog = Dog("Rex")

my_cat = Cat("Whiskers")

print(my_dog.speak()) # Output: Woof!

print(my_cat.speak()) # Output: Meow!


5.Project: Library Management System
○ Build a simple library management system
using OOP concepts to manage books, members,
and book loans.

Example implementation:
python
Copy code
class Book:

def __init__(self, title, author):


self.title = title

self.author = author

self.is_available = True

def __str__(self):

return f"{self.title} by {self.author}"

class Member:

def __init__(self, name):

self.name = name

self.borrowed_books = []

def borrow_book(self, book):

if book.is_available:

book.is_available = False

self.borrowed_books.append(book)

print(f"{self.name} borrowed
{book.title}")

else:

print(f"Sorry, {book.title} is not


available.")
def return_book(self, book):

if book in self.borrowed_books:

book.is_available = True

self.borrowed_books.remove(book)

print(f"{self.name} returned
{book.title}")

else:

print(f"{self.name} does not have


{book.title}")

class Library:

def __init__(self):

self.books = []

self.members = []

def add_book(self, book):

self.books.append(book)

print(f"Added {book.title}")

def add_member(self, member):

self.members.append(member)

print(f"Added member {member.name}")


def list_books(self):

for book in self.books:

status = "Available" if book.is_available


else "Not Available"

print(f"{book} - {status}")

def main():

library = Library()

book1 = Book("1984", "George Orwell")

book2 = Book("To Kill a Mockingbird", "Harper


Lee")

library.add_book(book1)

library.add_book(book2)

member1 = Member("Alice")

member2 = Member("Bob")

library.add_member(member1)

library.add_member(member2)

library.list_books()
member1.borrow_book(book1)

library.list_books()

member1.return_book(book1)

library.list_books()

if __name__ == "__main__":

main()

Week 7: Intermediate Data Handling with Pandas

Presentation:

1.Introduction to Pandas
○ What is Pandas and its importance
○ Installing Pandas
2.Data Structures in Pandas
○ Series
○ DataFrame
3.DataFrame Operations
○ Creating DataFrames
○ Reading and Writing DataFrames (CSV, Excel)
○ Data Selection and Filtering
○ Data Manipulation (adding/removing columns,
sorting, etc.)
4.Project: Sales Data Analysis
○ Requirements
○ Walkthrough

Notes:
1.Introduction to Pandas
○ Pandas is a powerful data manipulation and
analysis library for Python.

Install Pandas using pip:


bash
Copy code
pip install pandas


2.Data Structures in Pandas

Series
python
Copy code
import pandas as pd

data = [1, 2, 3, 4, 5]

series = pd.Series(data)

print(series)

DataFrame
python
Copy code
data = {

"Name": ["Alice", "Bob", "Charlie"],

"Age": [25, 30, 35]

}
df = pd.DataFrame(data)

print(df)


3.DataFrame Operations

Creating DataFrames
python
Copy code
data = {

"Name": ["Alice", "Bob", "Charlie"],

"Age": [25, 30, 35]

df = pd.DataFrame(data)

Reading and Writing DataFrames


python
Copy code
df.to_csv("data.csv", index=False)

df = pd.read_csv("data.csv")

Data Selection and Filtering


python
Copy code
# Selecting columns

print(df["Name"])
# Filtering rows

print(df[df["Age"] > 25])

Data Manipulation
python
Copy code
# Adding a column

df["Salary"] = [50000, 60000, 70000]

# Removing a column

df = df.drop("Age", axis=1)

# Sorting

df = df.sort_values(by="Salary", ascending=False)


4.Project: Sales Data Analysis
○ Analyze a dataset containing sales data to
extract insights such as total sales, average
sales, and sales by region.

Example implementation:
python
Copy code
import pandas as pd

def main():
# Load the dataset

df = pd.read_csv("sales_data.csv")

# Display first few rows

print("First few rows of the dataset:")

print(df.head())

# Calculate total sales

total_sales = df["Sales"].sum()

print(f"Total Sales: {total_sales}")

# Calculate average sales

average_sales = df["Sales"].mean()

print(f"Average Sales: {average_sales}")

# Sales by region

sales_by_region =
df.groupby("Region")["Sales"].sum()

print("Sales by Region:")

print(sales_by_region)
if __name__ == "__main__":

main()

Week 8: Advanced Topics and Final Project

Presentation:

1.Advanced Topics in Python


○ Decorators
○ Generators
○ Context Managers
○ Working with APIs
2.Final Project: Comprehensive Application
○ Requirements
○ Planning
○ Implementation

Notes:

1.Advanced Topics in Python

Decorators
python
Copy code
def my_decorator(func):

def wrapper():

print("Something is happening before the


function is called.")

func()

print("Something is happening after the


function is called.")
return wrapper

@my_decorator

def say_hello():

print("Hello!")

say_hello()

Generators
python
Copy code
def my_generator():

for i in range(5):

yield i

for value in my_generator():

print(value)

Context Managers
python
Copy code
with open("example.txt", "w") as file:

file.write("Hello, World!")

Working with APIs


python
Copy code
import requests

response =
requests.get("https://api.example.com/data")

data = response.json()

print(data)


2.Final Project: Comprehensive Application
○ Design and implement a comprehensive
application that combines various concepts
learned throughout the course. This could be
a web application, data analysis tool, or a
game.
○ Example project outline:
■ Project Idea: Personal Finance Tracker
■ Features:
■ User authentication
■ Expense tracking
■ Income tracking
■ Data visualization
■ Implementation:
■ Week 1: Setup project structure and
basic authentication.
■ Week 2: Implement expense and income
tracking features.
■ Week 3: Add data visualisation using
libraries like Matplotlib or
Seaborn.
■ Week 4: Finalise and test the
application, adding any additional
features or improvements.

Example Final Project Implementation: Personal


Finance Tracker

python

Copy code

import json

class FinanceTracker:

def __init__(self):

self.expenses = []

self.incomes = []

def add_expense(self, amount, category):

self.expenses.append({"amount": amount,
"category": category})

print(f"Added expense: {amount} in


{category}")

def add_income(self, amount, source):


self.incomes.append({"amount": amount,
"source": source})

print(f"Added income: {amount} from


{source}")

def get_total_expenses(self):

return sum(expense["amount"] for expense in


self.expenses)

def get_total_incomes(self):

return sum(income["amount"] for income in


self.incomes)

def save_data(self, filename):

data = {"expenses": self.expenses, "incomes":


self.incomes}

with open(filename, "w") as file:

json.dump(data, file)

print("Data saved.")

def load_data(self, filename):

with open(filename, "r") as file:

data = json.load(file)
self.expenses = data["expenses"]

self.incomes = data["incomes"]

print("Data loaded.")

def main():

tracker = FinanceTracker()

while True:

print("1. Add expense")

print("2. Add income")

print("3. View total expenses")

print("4. View total incomes")

print("5. Save data")

print("6. Load data")

print("7. Exit")

choice = input("Enter your choice: ")

if choice == '1':

amount = float(input("Enter expense


amount: "))
category = input("Enter expense category:
")

tracker.add_expense(amount, category)

elif choice == '2':

amount = float(input("Enter income


amount: "))

source = input("Enter income source: ")

tracker.add_income(amount, source)

elif choice == '3':

print(f"Total expenses:
{tracker.get_total_expenses()}")

elif choice == '4':

print(f"Total incomes:
{tracker.get_total_incomes()}")

elif choice == '5':

filename = input("Enter filename to save


data: ")

tracker.save_data(filename)
elif choice == '6':

filename = input("Enter filename to load


data: ")

tracker.load_data(filename)

elif choice == '7':

print("Goodbye!")

break

else:

print("Invalid choice. Please try


again.")

if __name__ == "__main__":

main()

This curriculum provides a comprehensive introduction


to Python, covering basic to advanced topics with
hands-on projects for each week to reinforce
learning. Each week's project is designed to be
practical and applicable, helping students build a
solid foundation and progressively advance their
skills.

Week 9: Web Development with Flask


Presentation:

1.Introduction to Flask
○ What is Flask and its use cases
○ Setting up a Flask environment
2.Basic Flask Application
○ Creating a simple Flask app
○ Routing and handling requests
3.Templates and Static Files
○ Using Jinja2 templates
○ Serving static files (CSS, JS, images)
4.Forms and User Input
○ Handling form data
○ Validating user input
5.Project: Simple Blog Application
○ Requirements
○ Walkthrough

Notes:

1.Introduction to Flask
○ Flask is a lightweight web framework for
Python.

Install Flask using pip:


bash
Copy code
pip install flask


2.Basic Flask Application

Creating a Simple Flask App


python
Copy code
from flask import Flask

app = Flask(__name__)

@app.route("/")

def home():

return "Hello, Flask!"

if __name__ == "__main__":

app.run(debug=True)

Routing and Handling Requests


python
Copy code
@app.route("/hello/<name>")

def hello(name):

return f"Hello, {name}!"


3.Templates and Static Files

Using Jinja2 Templates


python
Copy code
from flask import render_template
@app.route("/")

def home():

return render_template("index.html")

# index.html

<!doctype html>

<html>

<head>

<title>Home</title>

</head>

<body>

<h1>Welcome to Flask!</h1>

</body>

</html>

Serving Static Files


html
Copy code
<!-- index.html -->

<link rel="stylesheet" href="{{ url_for('static',


filename='style.css') }}">

4.Forms and User Input

Handling Form Data


python
Copy code
from flask import request

@app.route("/submit", methods=["POST"])

def submit():

name = request.form["name"]

return f"Hello, {name}!"

Validating User Input


python
Copy code
from wtforms import Form, StringField, validators

class MyForm(Form):

name = StringField('Name',
[validators.InputRequired()])


5.Project: Simple Blog Application
○ Build a simple blog application where users
can create and view blog posts.
Example implementation:
python
Copy code
from flask import Flask, render_template, request,
redirect, url_for

app = Flask(__name__)

posts = []

@app.route("/")

def home():

return render_template("index.html", posts=posts)

@app.route("/add", methods=["GET", "POST"])

def add_post():

if request.method == "POST":

title = request.form["title"]

content = request.form["content"]

posts.append({"title": title, "content":


content})

return redirect(url_for("home"))

return render_template("add_post.html")
if __name__ == "__main__":

app.run(debug=True)

# index.html

<!doctype html>

<html>

<head>

<title>Blog</title>

</head>

<body>

<h1>My Blog</h1>

<a href="{{ url_for('add_post') }}">Add


Post</a>

<ul>

{% for post in posts %}

<li>

<h2>{{ post.title }}</h2>

<p>{{ post.content }}</p>

</li>

{% endfor %}
</ul>

</body>

</html>

# add_post.html

<!doctype html>

<html>

<head>

<title>Add Post</title>

</head>

<body>

<h1>Add Post</h1>

<form method="POST">

<label for="title">Title</label>

<input type="text" name="title"


id="title">

<label for="content">Content</label>

<textarea name="content"
id="content"></textarea>

<button type="submit">Add Post</button>

</form>

</body>
</html>

Week 10: Data Visualization with Matplotlib and


Seaborn

Presentation:

1.Introduction to Data Visualization


○ Importance of data visualisation
○ Overview of Matplotlib and Seaborn
2.Basic Plots with Matplotlib
○ Line plots
○ Bar charts
○ Scatter plots
3.Advanced Plots with Seaborn
○ Distribution plots
○ Box plots
○ Heatmaps
4.Customising Plots
○ Adding titles and labels
○ Changing colours and styles
○ Saving plots to files
5.Project: Data Visualization Dashboard
○ Requirements
○ Walkthrough

Notes:

1.Introduction to Data Visualization


○ Data visualisation helps to communicate
information clearly and effectively.
○ Matplotlib is a basic plotting library, while
Seaborn provides a high-level interface for
drawing attractive statistical graphics.
2.Basic Plots with Matplotlib

Line Plots
python
Copy code
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [2, 3, 5, 7, 11]

plt.plot(x, y)

plt.title("Line Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.show()

Bar Charts
python
Copy code
plt.bar(x, y)

plt.title("Bar Chart")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")
plt.show()

Scatter Plots
python
Copy code
plt.scatter(x, y)

plt.title("Scatter Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.show()


3.Advanced Plots with Seaborn

Distribution Plots
python
Copy code
import seaborn as sns

data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

sns.distplot(data)

plt.title("Distribution Plot")

plt.show()

Box Plots
python
Copy code
sns.boxplot(data=data)

plt.title("Box Plot")

plt.show()

Heatmaps
python
Copy code
import numpy as np

data = np.random.rand(10, 12)

sns.heatmap(data)

plt.title("Heatmap")

plt.show()


4.Customising Plots

Adding Titles and Labels


python
Copy code
plt.plot(x, y)

plt.title("Line Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.show()

Changing Colors and Styles


python
Copy code
plt.plot(x, y, color="red", linestyle="--")

plt.title("Line Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.show()

Saving Plots to Files


python
Copy code
plt.plot(x, y)

plt.title("Line Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.savefig("line_plot.png")


5.Project: Data Visualization Dashboard
○ Create a dashboard that visualises a dataset
using various plots.

Example implementation:
python
Copy code
import matplotlib.pyplot as plt

import seaborn as sns

import pandas as pd

def load_data(filename):

return pd.read_csv(filename)

def plot_data(df):

plt.figure(figsize=(10, 6))

# Line Plot

plt.subplot(2, 2, 1)

plt.plot(df["Date"], df["Sales"])

plt.title("Sales Over Time")

plt.xlabel("Date")

plt.ylabel("Sales")

# Bar Chart

plt.subplot(2, 2, 2)

plt.bar(df["Product"], df["Quantity"])
plt.title("Product Sales")

plt.xlabel("Product")

plt.ylabel("Quantity")

# Scatter Plot

plt.subplot(2, 2, 3)

plt.scatter(df["Quantity"], df["Sales"])

plt.title("Sales vs Quantity")

plt.xlabel("Quantity")

plt.ylabel("Sales")

# Heatmap

plt.subplot(2, 2, 4)

corr = df.corr()

sns.heatmap(corr, annot=True)

plt.title("Correlation Heatmap")

plt.tight_layout()

plt.show()

def main():
filename = "sales_data.csv"

df = load_data(filename)

plot_data(df)

if __name__ == "__main__":

main()

Week 11: Testing and Debugging

Presentation:

1.Introduction to Testing
○ Importance of testing
○ Types of testing (unit tests, integration
tests)
2.Using unittest Framework
○ Writing and running tests
○ Assertions
3.Test-Driven Development (TDD)
○ Principles of TDD
○ Writing tests before code
4.Debugging Techniques
○ Using print statements
○ Using a debugger (e.g., pdb)
5.Project: Testing a Python Application
○ Requirements
○ Walkthrough

Notes:
1.Introduction to Testing
○ Testing ensures code reliability and
correctness.
○ Types of testing include unit tests (testing
individual components) and integration tests
(testing combined parts of a system).
2.Using unittest Framework

Writing and Running Tests


python
Copy code
import unittest

def add(a, b):

return a + b

class TestMath(unittest.TestCase):

def test_add(self):

self.assertEqual(add(1, 2), 3)

self.assertEqual(add(-1, 1), 0)

if __name__ == "__main__":

unittest.main()

Assertions
python
Copy code
self.assertTrue(condition)

self.assertFalse(condition)

self.assertEqual(a, b)

self.assertNotEqual(a, b)


3.Test-Driven Development (TDD)
○ Principles of TDD
■ Write tests before writing the code.
■ Refactor code to pass tests.

Example:
python
Copy code
import unittest

def is_even(n):

return n % 2 == 0

class TestMath(unittest.TestCase):

def test_is_even(self):

self.assertTrue(is_even(2))

self.assertFalse(is_even(3))

if __name__ == "__main__":
unittest.main()


4.Debugging Techniques

Using Print Statements


python
Copy code
def add(a, b):

print(f"a: {a}, b: {b}")

return a + b

Using a Debugger
python
Copy code
import pdb; pdb.set_trace()

def add(a, b):

return a + b

add(1, 2)


5.Project: Testing a Python Application
○ Write tests for a previously developed
project to ensure its functionality.

Example implementation:
python
Copy code
import unittest

from finance_tracker import FinanceTracker

class TestFinanceTracker(unittest.TestCase):

def setUp(self):

self.tracker = FinanceTracker()

def test_add_expense(self):

self.tracker.add_expense(100, "Food")

self.assertEqual(self.tracker.get_total_expenses(),
100)

def test_add_income(self):

self.tracker.add_income(500, "Salary")

self.assertEqual(self.tracker.get_total_incomes(),
500)

if __name__ == "__main__":

unittest.main()


Week 12: Final Project Completion and Review

Presentation:

1.Review of Key Concepts


○ Summarise key topics covered throughout the
course
2.Final Project Guidelines
○ Requirements
○ Expectations
3.Presentation Skills
○ How to present your project effectively
○ Preparing a project presentation
4.Project Showcase
○ Students present their projects
○ Feedback and discussion

Notes:

1.Review of Key Concepts


○ Briefly revisit each major topic: basic
syntax, data structures, OOP, file handling,
libraries, web development, data
visualisation, and testing.
2.Final Project Guidelines
○ Ensure the project demonstrates an
understanding of the concepts learned.
○ Focus on clean, efficient, and
well-documented code.
3.Presentation Skills
○ Presenting Effectively
■ Structure your presentation:
introduction, project overview, demo,
and conclusion.
■ Practise clear and concise
communication.
○ Preparing a Project Presentation
■ Use slides to highlight key points.
■ Include code snippets and screenshots.
■ Be prepared to answer questions.
4.Project Showcase
○ Student Presentations
■ Each student presents their final
project.
○ Feedback and Discussion
■ Constructive feedback from peers and
instructors.
■ Discussion of challenges faced and
lessons learned.

Example Final Project Presentation Outline

1.Introduction
○ Introduce yourself and your project.
2.Project Overview
○ Describe the project idea and its purpose.
○ Highlight key features and functionality.
3.Demo
○ Show a live demo or walkthrough of your
project.
4.Conclusion
○ Summarize your experience and what you
learned.
○ Discuss any future improvements or features.
5.Q&A
○ Invite questions from the audience and
provide answers.

You might also like