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

Python Basics for Beginners

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)
91 views70 pages

Python Basics for Beginners

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

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 [Link].

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("[Link]")

print("[Link]")

print("[Link]")

print("[Link]")
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 = [Link](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([Link](16))

Standard Library Modules


python
Copy code
import datetime

now = [Link]()

print(now)
Creating and Using Custom Modules
python
Copy code
# In a file named [Link]

def greet(name):

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

# In another file

import mymodule

[Link]("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: ")

[Link](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):

[Link](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
[Link]("orange")

[Link]("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([Link](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([Link](set2)) # Output: {1, 2, 3, 4, 5}

print([Link](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([Link]("Alice")) # Output: 123-4567

print([Link]()) # Output:
dict_keys(['Alice', 'Bob'])

print([Link]()) # 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 [Link]():

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:

[Link] to File Handling


○ Types of Files: Text and Binary
○ Opening and Closing Files
○ Reading and Writing to Files
[Link] with Text Files
○ Reading entire file content
○ Reading line by line
○ Writing and appending to files
[Link] with CSV Files
○ Reading from CSV files
○ Writing to CSV files
[Link] Handling in File Operations
○ Using try-except blocks
[Link]: Student Grades Management
○ Requirements
○ Walkthrough

Notes:

[Link] to File Handling


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

Opening and Closing Files


python
Copy code
file = open("[Link]", "r") # Open for reading

[Link]() # Close the file


[Link] with Text Files

Reading Entire File Content


python
Copy code
with open("[Link]", "r") as file:

content = [Link]()

print(content)

Reading Line by Line


python
Copy code
with open("[Link]", "r") as file:

for line in file:

print(line, end="")

Writing and Appending to Files


python
Copy code
with open("[Link]", "w") as file:

[Link]("Hello, World!")
with open("[Link]", "a") as file:

[Link]("\nAppended text.")


[Link] with CSV Files

Reading from CSV Files


python
Copy code
import csv

with open("[Link]", "r") as file:

reader = [Link](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("[Link]", "w", newline='') as file:

writer = [Link](file)
[Link](data)


[Link] Handling in File Operations

Using try-except Blocks


python
Copy code
try:

with open("[Link]", "r") as file:

content = [Link]()

print(content)

except FileNotFoundError:

print("File not found.")

except IOError:

print("An error occurred while reading the


file.")


[Link]: 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 = [Link](file)

[Link]([name, grade])

print("Grade added!")

def view_grades(filename):

try:

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

reader = [Link](file)

for row in reader:

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


{row[1]}")

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

def main():

filename = "[Link]"

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:

[Link] to OOP
○ Concepts: Classes and Objects
○ Benefits of OOP
[Link] Classes and Creating Objects
○ Defining a class
○ Creating instances (objects) of a class
[Link] and Methods
○ Instance attributes and methods
○ Class attributes and methods
[Link] and Polymorphism
○ Inheriting from a base class
○ Method overriding
[Link]: Library Management System
○ Requirements
○ Walkthrough

Notes:

[Link] 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.
[Link] Classes and Creating Objects

Defining a Class
python
Copy code
class Dog:
pass

Creating Instances
python
Copy code
my_dog = Dog()


[Link] and Methods

Instance Attributes and Methods


python
Copy code
class Dog:

def __init__(self, name, age):

[Link] = name

[Link] = age

def bark(self):

print(f"{[Link]} 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):

[Link] = name

[Link] = age

def bark(self):

print(f"{[Link]} is barking!")

print([Link]) # Output: Canis familiaris


[Link] and Polymorphism

Inheriting from a Base Class


python
Copy code
class Animal:

def __init__(self, name):

[Link] = 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!


[Link]: 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):


[Link] = title

[Link] = author

self.is_available = True

def __str__(self):

return f"{[Link]} by {[Link]}"

class Member:

def __init__(self, name):

[Link] = name

self.borrowed_books = []

def borrow_book(self, book):

if book.is_available:

book.is_available = False

self.borrowed_books.append(book)

print(f"{[Link]} borrowed
{[Link]}")

else:

print(f"Sorry, {[Link]} 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"{[Link]} returned
{[Link]}")

else:

print(f"{[Link]} does not have


{[Link]}")

class Library:

def __init__(self):

[Link] = []

[Link] = []

def add_book(self, book):

[Link](book)

print(f"Added {[Link]}")

def add_member(self, member):

[Link](member)

print(f"Added member {[Link]}")


def list_books(self):

for book in [Link]:

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:

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

Notes:
[Link] to Pandas
○ Pandas is a powerful data manipulation and
analysis library for Python.

Install Pandas using pip:


bash
Copy code
pip install pandas


[Link] Structures in Pandas

Series
python
Copy code
import pandas as pd

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

series = [Link](data)

print(series)

DataFrame
python
Copy code
data = {

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

"Age": [25, 30, 35]

}
df = [Link](data)

print(df)


[Link] Operations

Creating DataFrames
python
Copy code
data = {

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

"Age": [25, 30, 35]

df = [Link](data)

Reading and Writing DataFrames


python
Copy code
df.to_csv("[Link]", index=False)

df = pd.read_csv("[Link]")

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 = [Link]("Age", axis=1)

# Sorting

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


[Link]: 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([Link]())

# 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 =
[Link]("Region")["Sales"].sum()

print("Sales by Region:")

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

main()

Week 8: Advanced Topics and Final Project

Presentation:

[Link] Topics in Python


○ Decorators
○ Generators
○ Context Managers
○ Working with APIs
[Link] Project: Comprehensive Application
○ Requirements
○ Planning
○ Implementation

Notes:

[Link] 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("[Link]", "w") as file:

[Link]("Hello, World!")

Working with APIs


python
Copy code
import requests

response =
[Link]("[Link]

data = [Link]()

print(data)


[Link] 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):

[Link] = []

[Link] = []

def add_expense(self, amount, category):

[Link]({"amount": amount,
"category": category})

print(f"Added expense: {amount} in


{category}")

def add_income(self, amount, source):


[Link]({"amount": amount,
"source": source})

print(f"Added income: {amount} from


{source}")

def get_total_expenses(self):

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


[Link])

def get_total_incomes(self):

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


[Link])

def save_data(self, filename):

data = {"expenses": [Link], "incomes":


[Link]}

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

[Link](data, file)

print("Data saved.")

def load_data(self, filename):

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

data = [Link](file)
[Link] = data["expenses"]

[Link] = 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:

[Link] to Flask
○ What is Flask and its use cases
○ Setting up a Flask environment
[Link] Flask Application
○ Creating a simple Flask app
○ Routing and handling requests
[Link] and Static Files
○ Using Jinja2 templates
○ Serving static files (CSS, JS, images)
[Link] and User Input
○ Handling form data
○ Validating user input
[Link]: Simple Blog Application
○ Requirements
○ Walkthrough

Notes:

[Link] to Flask
○ Flask is a lightweight web framework for
Python.

Install Flask using pip:


bash
Copy code
pip install flask


[Link] Flask Application

Creating a Simple Flask App


python
Copy code
from flask import Flask

app = Flask(__name__)

@[Link]("/")

def home():

return "Hello, Flask!"

if __name__ == "__main__":

[Link](debug=True)

Routing and Handling Requests


python
Copy code
@[Link]("/hello/<name>")

def hello(name):

return f"Hello, {name}!"


[Link] and Static Files

Using Jinja2 Templates


python
Copy code
from flask import render_template
@[Link]("/")

def home():

return render_template("[Link]")

# [Link]

<!doctype html>

<html>

<head>

<title>Home</title>

</head>

<body>

<h1>Welcome to Flask!</h1>

</body>

</html>

Serving Static Files


html
Copy code
<!-- [Link] -->

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


filename='[Link]') }}">

[Link] and User Input

Handling Form Data


python
Copy code
from flask import request

@[Link]("/submit", methods=["POST"])

def submit():

name = [Link]["name"]

return f"Hello, {name}!"

Validating User Input


python
Copy code
from wtforms import Form, StringField, validators

class MyForm(Form):

name = StringField('Name',
[[Link]()])


[Link]: 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 = []

@[Link]("/")

def home():

return render_template("[Link]", posts=posts)

@[Link]("/add", methods=["GET", "POST"])

def add_post():

if [Link] == "POST":

title = [Link]["title"]

content = [Link]["content"]

[Link]({"title": title, "content":


content})

return redirect(url_for("home"))

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

[Link](debug=True)

# [Link]

<!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>{{ [Link] }}</h2>

<p>{{ [Link] }}</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:

[Link] to Data Visualization


○ Importance of data visualisation
○ Overview of Matplotlib and Seaborn
[Link] Plots with Matplotlib
○ Line plots
○ Bar charts
○ Scatter plots
[Link] Plots with Seaborn
○ Distribution plots
○ Box plots
○ Heatmaps
[Link] Plots
○ Adding titles and labels
○ Changing colours and styles
○ Saving plots to files
[Link]: Data Visualization Dashboard
○ Requirements
○ Walkthrough

Notes:

[Link] 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.
[Link] Plots with Matplotlib

Line Plots
python
Copy code
import [Link] as plt

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

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

[Link](x, y)

[Link]("Line Plot")

[Link]("X-axis")

[Link]("Y-axis")

[Link]()

Bar Charts
python
Copy code
[Link](x, y)

[Link]("Bar Chart")

[Link]("X-axis")

[Link]("Y-axis")
[Link]()

Scatter Plots
python
Copy code
[Link](x, y)

[Link]("Scatter Plot")

[Link]("X-axis")

[Link]("Y-axis")

[Link]()


[Link] Plots with Seaborn

Distribution Plots
python
Copy code
import seaborn as sns

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

[Link](data)

[Link]("Distribution Plot")

[Link]()

Box Plots
python
Copy code
[Link](data=data)

[Link]("Box Plot")

[Link]()

Heatmaps
python
Copy code
import numpy as np

data = [Link](10, 12)

[Link](data)

[Link]("Heatmap")

[Link]()


[Link] Plots

Adding Titles and Labels


python
Copy code
[Link](x, y)

[Link]("Line Plot")

[Link]("X-axis")

[Link]("Y-axis")

[Link]()

Changing Colors and Styles


python
Copy code
[Link](x, y, color="red", linestyle="--")

[Link]("Line Plot")

[Link]("X-axis")

[Link]("Y-axis")

[Link]()

Saving Plots to Files


python
Copy code
[Link](x, y)

[Link]("Line Plot")

[Link]("X-axis")

[Link]("Y-axis")

[Link]("line_plot.png")


[Link]: Data Visualization Dashboard
○ Create a dashboard that visualises a dataset
using various plots.

Example implementation:
python
Copy code
import [Link] as plt

import seaborn as sns

import pandas as pd

def load_data(filename):

return pd.read_csv(filename)

def plot_data(df):

[Link](figsize=(10, 6))

# Line Plot

[Link](2, 2, 1)

[Link](df["Date"], df["Sales"])

[Link]("Sales Over Time")

[Link]("Date")

[Link]("Sales")

# Bar Chart

[Link](2, 2, 2)

[Link](df["Product"], df["Quantity"])
[Link]("Product Sales")

[Link]("Product")

[Link]("Quantity")

# Scatter Plot

[Link](2, 2, 3)

[Link](df["Quantity"], df["Sales"])

[Link]("Sales vs Quantity")

[Link]("Quantity")

[Link]("Sales")

# Heatmap

[Link](2, 2, 4)

corr = [Link]()

[Link](corr, annot=True)

[Link]("Correlation Heatmap")

plt.tight_layout()

[Link]()

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

df = load_data(filename)

plot_data(df)

if __name__ == "__main__":

main()

Week 11: Testing and Debugging

Presentation:

[Link] to Testing
○ Importance of testing
○ Types of testing (unit tests, integration
tests)
[Link] unittest Framework
○ Writing and running tests
○ Assertions
[Link]-Driven Development (TDD)
○ Principles of TDD
○ Writing tests before code
[Link] Techniques
○ Using print statements
○ Using a debugger (e.g., pdb)
[Link]: Testing a Python Application
○ Requirements
○ Walkthrough

Notes:
[Link] 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).
[Link] unittest Framework

Writing and Running Tests


python
Copy code
import unittest

def add(a, b):

return a + b

class TestMath([Link]):

def test_add(self):

[Link](add(1, 2), 3)

[Link](add(-1, 1), 0)

if __name__ == "__main__":

[Link]()

Assertions
python
Copy code
[Link](condition)

[Link](condition)

[Link](a, b)

[Link](a, b)


[Link]-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([Link]):

def test_is_even(self):

[Link](is_even(2))

[Link](is_even(3))

if __name__ == "__main__":
[Link]()


[Link] 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)


[Link]: 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([Link]):

def setUp(self):

[Link] = FinanceTracker()

def test_add_expense(self):

[Link].add_expense(100, "Food")

[Link]([Link].get_total_expenses(),
100)

def test_add_income(self):

[Link].add_income(500, "Salary")

[Link]([Link].get_total_incomes(),
500)

if __name__ == "__main__":

[Link]()


Week 12: Final Project Completion and Review

Presentation:

[Link] of Key Concepts


○ Summarise key topics covered throughout the
course
[Link] Project Guidelines
○ Requirements
○ Expectations
[Link] Skills
○ How to present your project effectively
○ Preparing a project presentation
[Link] Showcase
○ Students present their projects
○ Feedback and discussion

Notes:

[Link] of Key Concepts


○ Briefly revisit each major topic: basic
syntax, data structures, OOP, file handling,
libraries, web development, data
visualisation, and testing.
[Link] Project Guidelines
○ Ensure the project demonstrates an
understanding of the concepts learned.
○ Focus on clean, efficient, and
well-documented code.
[Link] 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.
[Link] 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

[Link]
○ Introduce yourself and your project.
[Link] Overview
○ Describe the project idea and its purpose.
○ Highlight key features and functionality.
[Link]
○ Show a live demo or walkthrough of your
project.
[Link]
○ 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