Python Basics for Beginners
Python Basics for Beginners
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("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
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([Link](16))
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")
Example implementation:
python
Copy code
def show_menu():
print("4. Exit")
def add_task(tasks):
[Link](task)
print("Task added!")
def view_tasks(tasks):
if not tasks:
else:
print(f"{i}. {task}")
def remove_task(tasks):
view_tasks(tasks)
[Link](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
[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}
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)}
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:
○
[Link] with Text Files
content = [Link]()
print(content)
print(line, end="")
[Link]("Hello, World!")
with open("[Link]", "a") as file:
[Link]("\nAppended text.")
○
[Link] with CSV Files
reader = [Link](file)
print(row)
writer = [Link](file)
[Link](data)
○
[Link] Handling in File Operations
content = [Link]()
print(content)
except FileNotFoundError:
except IOError:
○
[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("3. Exit")
def add_grade(filename):
writer = [Link](file)
[Link]([name, grade])
print("Grade added!")
def view_grades(filename):
try:
reader = [Link](file)
except FileNotFoundError:
print("No grades found.")
def main():
filename = "[Link]"
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:
[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
[Link] = name
[Link] = age
def bark(self):
print(f"{[Link]} is barking!")
my_dog = Dog("Rex", 5)
[Link] = name
[Link] = age
def bark(self):
print(f"{[Link]} is barking!")
○
[Link] and Polymorphism
[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")
○
[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:
[Link] = author
self.is_available = True
def __str__(self):
class Member:
[Link] = name
self.borrowed_books = []
if book.is_available:
book.is_available = False
self.borrowed_books.append(book)
print(f"{[Link]} borrowed
{[Link]}")
else:
if book in self.borrowed_books:
book.is_available = True
self.borrowed_books.remove(book)
print(f"{[Link]} returned
{[Link]}")
else:
class Library:
def __init__(self):
[Link] = []
[Link] = []
[Link](book)
print(f"Added {[Link]}")
[Link](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:
[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.
○
[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 = {
}
df = [Link](data)
print(df)
○
[Link] Operations
Creating DataFrames
python
Copy code
data = {
df = [Link](data)
df = pd.read_csv("[Link]")
print(df["Name"])
# Filtering rows
Data Manipulation
python
Copy code
# Adding a column
# 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")
print([Link]())
total_sales = df["Sales"].sum()
average_sales = df["Sales"].mean()
# Sales by region
sales_by_region =
[Link]("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("[Link]", "w") as file:
[Link]("Hello, World!")
○
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.
python
Copy code
import json
class FinanceTracker:
def __init__(self):
[Link] = []
[Link] = []
[Link]({"amount": amount,
"category": category})
def get_total_expenses(self):
def get_total_incomes(self):
[Link](data, file)
print("Data saved.")
data = [Link](file)
[Link] = data["expenses"]
[Link] = 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()
[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.
○
[Link] Flask Application
app = Flask(__name__)
@[Link]("/")
def home():
if __name__ == "__main__":
[Link](debug=True)
def hello(name):
○
[Link] and Static Files
def home():
return render_template("[Link]")
# [Link]
<!doctype html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome to Flask!</h1>
</body>
</html>
@[Link]("/submit", methods=["POST"])
def submit():
name = [Link]["name"]
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():
def add_post():
if [Link] == "POST":
title = [Link]["title"]
content = [Link]["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>
<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 [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
[Link](data)
[Link]("Heatmap")
[Link]()
○
[Link] Plots
[Link]("Line Plot")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()
○
[Link]("Line Plot")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()
[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 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]("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()
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
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
return a + b
Using a Debugger
python
Copy code
import pdb; pdb.set_trace()
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
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:
Notes:
[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.