Course Material
Course Material
Presentation:
Introduction to Python
Installing Python
Basic Syntax
Requirements
Walkthrough
Notes:
Introduction to Python
Basic Syntax
y = 10.5 # Float
Basic Operators
python
Copy code
# Arithmetic
result = x + y
# Comparison
is_equal = (x == y)
# Logical
"""
This is a
multi-line comment
"""
def greet():
print("Hello, User!")
Example implementation:
python
Copy code
def add(x, y):
return x + y
return x - y
return x * y
if y != 0:
return x / y
else:
print("Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
else:
print("Invalid input")
Week 2: Control Structures
Presentation:
Conditional Statements
Nested Conditions
Loops
for Loop
while Loop
Nested Loops
Requirements
Walkthrough
Notes:
Conditional Statements
print("Minor")
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)
if i == 5:
break
print(i)
for i in range(10):
if i % 2 == 0:
continue
print(i)
Project: Number Guessing Game
Example implementation:
python
Copy code
import random
def guess_number():
attempts = 0
max_attempts = 10
attempts += 1
print("Too low!")
print("Too high!")
else:
print(f"Congratulations! You've guessed
the number in {attempts} attempts.")
break
if attempts == max_attempts:
guess_number()
Presentation:
Functions
Scope of Variables
Modules
Importing Modules
Requirements
Walkthrough
Notes:
Functions
print(f"Hello, {name}!")
greet("Alice")
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()
global_var = 20
def my_function():
print(global_var)
my_function()
Modules
Importing Modules
python
Copy code
import math
print(math.sqrt(16))
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")
Example implementation:
python
Copy code
def show_menu():
print("4. Exit")
def add_task(tasks):
tasks.append(task)
print("Task added!")
def view_tasks(tasks):
if not tasks:
else:
print(f"{i}. {task}")
def remove_task(tasks):
view_tasks(tasks)
tasks.pop(task_num - 1)
print("Task removed!")
else:
tasks = []
while True:
show_menu()
if choice == '1':
add_task(tasks)
view_tasks(tasks)
remove_task(tasks)
print("Goodbye!")
break
else:
if __name__ == "__main__":
main()
Week 4: Data Structures
Presentation:
Lists
Creating Lists
Accessing Elements
List Comprehensions
Tuples
Creating Tuples
Accessing Elements
Tuple Methods
Sets
Creating Sets
Set Methods
Dictionaries
Creating Dictionaries
Accessing Values
Dictionary Comprehensions
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}
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)}
Example implementation:
python
Copy code
def show_menu():
print("5. Exit")
def add_contact(contacts):
contacts[name] = phone
print("Contact added!")
def view_contacts(contacts):
if not contacts:
else:
def remove_contact(contacts):
if name in contacts:
del contacts[name]
print("Contact removed!")
else:
def search_contact(contacts):
if name in contacts:
else:
print("Contact not found.")
def main():
contacts = {}
while True:
show_menu()
if choice == '1':
add_contact(contacts)
view_contacts(contacts)
remove_contact(contacts)
search_contact(contacts)
print("Goodbye!")
break
else:
main()
Presentation:
Notes:
○
2.Working with Text Files
content = file.read()
print(content)
print(line, end="")
file.write("Hello, World!")
with open("example.txt", "a") as file:
file.write("\nAppended text.")
○
3.Working with CSV Files
reader = csv.reader(file)
print(row)
writer = csv.writer(file)
writer.writerows(data)
○
4.Exception Handling in File Operations
content = file.read()
print(content)
except FileNotFoundError:
except IOError:
○
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("3. Exit")
def add_grade(filename):
writer = csv.writer(file)
writer.writerow([name, grade])
print("Grade added!")
def view_grades(filename):
try:
reader = csv.reader(file)
except FileNotFoundError:
print("No grades found.")
def main():
filename = "grades.csv"
while True:
show_menu()
if choice == '1':
add_grade(filename)
view_grades(filename)
print("Goodbye!")
break
else:
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
self.name = name
self.age = age
def bark(self):
print(f"{self.name} is barking!")
my_dog = Dog("Rex", 5)
self.name = name
self.age = age
def bark(self):
print(f"{self.name} is barking!")
○
4.Inheritance and Polymorphism
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")
○
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:
self.author = author
self.is_available = True
def __str__(self):
class Member:
self.name = name
self.borrowed_books = []
if book.is_available:
book.is_available = False
self.borrowed_books.append(book)
print(f"{self.name} borrowed
{book.title}")
else:
if book in self.borrowed_books:
book.is_available = True
self.borrowed_books.remove(book)
print(f"{self.name} returned
{book.title}")
else:
class Library:
def __init__(self):
self.books = []
self.members = []
self.books.append(book)
print(f"Added {book.title}")
self.members.append(member)
print(f"{book} - {status}")
def main():
library = Library()
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()
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.
○
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 = {
}
df = pd.DataFrame(data)
print(df)
○
3.DataFrame Operations
Creating DataFrames
python
Copy code
data = {
df = pd.DataFrame(data)
df = pd.read_csv("data.csv")
print(df["Name"])
# Filtering rows
Data Manipulation
python
Copy code
# Adding a column
# 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")
print(df.head())
total_sales = df["Sales"].sum()
average_sales = df["Sales"].mean()
# Sales by region
sales_by_region =
df.groupby("Region")["Sales"].sum()
print("Sales by Region:")
print(sales_by_region)
if __name__ == "__main__":
main()
Presentation:
Notes:
Decorators
python
Copy code
def my_decorator(func):
def wrapper():
func()
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Generators
python
Copy code
def my_generator():
for i in range(5):
yield i
print(value)
Context Managers
python
Copy code
with open("example.txt", "w") as file:
file.write("Hello, World!")
○
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.
python
Copy code
import json
class FinanceTracker:
def __init__(self):
self.expenses = []
self.incomes = []
self.expenses.append({"amount": amount,
"category": category})
def get_total_expenses(self):
def get_total_incomes(self):
json.dump(data, file)
print("Data saved.")
data = json.load(file)
self.expenses = data["expenses"]
self.incomes = data["incomes"]
print("Data loaded.")
def main():
tracker = FinanceTracker()
while True:
print("7. Exit")
if choice == '1':
tracker.add_expense(amount, category)
tracker.add_income(amount, source)
print(f"Total expenses:
{tracker.get_total_expenses()}")
print(f"Total incomes:
{tracker.get_total_incomes()}")
tracker.save_data(filename)
elif choice == '6':
tracker.load_data(filename)
print("Goodbye!")
break
else:
if __name__ == "__main__":
main()
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.
○
2.Basic Flask Application
app = Flask(__name__)
@app.route("/")
def home():
if __name__ == "__main__":
app.run(debug=True)
def hello(name):
○
3.Templates and Static Files
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>
@app.route("/submit", methods=["POST"])
def submit():
name = request.form["name"]
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():
def add_post():
if request.method == "POST":
title = request.form["title"]
content = request.form["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>
<ul>
<li>
</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>
<label for="content">Content</label>
<textarea name="content"
id="content"></textarea>
</form>
</body>
</html>
Presentation:
Notes:
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
sns.heatmap(data)
plt.title("Heatmap")
plt.show()
○
4.Customising Plots
plt.title("Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
○
plt.title("Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
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 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.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()
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
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
return a + b
Using a Debugger
python
Copy code
import pdb; pdb.set_trace()
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
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:
Notes:
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.