0% found this document useful (0 votes)
54 views121 pages

Learn Python Through App Development

This document outlines a project-based approach to learning Python through the development of real-world applications. It includes various projects such as a personal expense tracker, web scraper, and a GUI notepad app, emphasizing hands-on learning and practical skills. The book aims to build confidence in coding by guiding readers through the creation of functional applications while teaching essential programming concepts.

Uploaded by

kbcedu35
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)
54 views121 pages

Learn Python Through App Development

This document outlines a project-based approach to learning Python through the development of real-world applications. It includes various projects such as a personal expense tracker, web scraper, and a GUI notepad app, emphasizing hands-on learning and practical skills. The book aims to build confidence in coding by guiding readers through the creation of functional applications while teaching essential programming concepts.

Uploaded by

kbcedu35
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

Python App Development Projects

Learn Python Fast by Building Real-World


Applications
By

STEM School
This Page Left Intentionally Blank

Contents

Chapter 1
Why Learn Python by Building Apps?
Chapter 3
Building a GUI with Tkinter – Desktop Notepad App
Chapter 4
Data Management App – Personal Expense Tracker
Chapter 5
Web Scraper and Dashboard – News & Weather App
Chapter 6
REST APIs – Currency Converter Web App (Flask)
Chapter 7
Authentication and User Management
Chapter 8
Automating Tasks – Email Reminder Bot
Chapter 9
Interactive Command Line Tool
Chapter 10
Realtime Chat App
Chapter 1
Working with Files – File Organizer Utility
Chapter 12
Data Visualization – COVID-19 Tracker Dashboard
Chapter 13
Game Development with Pygame – 2D Snake Game
Chapter 15
Deploying Your Python App
Chapter 16
Capstone Project – Personal Productivity Suite
Appendices
Appendix A
Python Syntax Quick Reference
Appendix D
Project Ideas for Future Learning
Chapter 1

Why Learn Python by Building Apps?

Learning to code can often feel abstract and overwhelming—especially


when you're starting with syntax rules, data types, and theoretical concepts.
But what if you could learn Python by actually doing something meaningful
from day one? That’s the essence of project-based learning. Instead of
memorizing dry lists of commands and functions, you’ll jump straight into
building real-world applications—apps you can use, apps you can improve,
and apps that can solve problems around you.
This book is built around the philosophy that the best way to learn a
programming language is by building physical or digital products with it.
This hands-on approach not only accelerates learning but also makes the
process far more engaging and relevant. You’ll see immediate results, learn
how various components of Python come together, and—most importantly
—gain confidence as a creator.
Python The Perfect Language for Makers
Python is one of the most beginner-friendly programming languages in the
world. Its clean and readable syntax means that you can often write more
functionality in fewer lines of code compared to languages like Java or
C++. But don’t mistake simplicity for weakness—Python is extremely
powerful and is used by major companies like Google, Netflix, and NASA.
Python's strength lies in its flexibility. It supports multiple programming
paradigms—object-oriented, functional, and procedural. It has a rich
ecosystem of libraries and frameworks that can help you do everything
from building web apps to scraping websites, creating games, automating
repetitive tasks, and even programming hardware like Raspberry Pi.
What You’ll Learn By Building
Here’s what sets this book apart rather than teaching Python as a set of
disconnected concepts, we’ll teach it through the lens of creating something
tangible. You’ll gradually move from basic tools to more advanced projects.
Each project is designed not just to demonstrate a feature of Python but to
solve a real-world problem. In the process, you’ll develop a wide array of
valuable skills.
Take a look at the variety of apps you’ll build as you progress through the
book
App Type Project Example Skills Learned
Desktop A file organizer that File I/O, OS module, exception
Tools sorts files by type handling
Web A personal blog Routing, HTML templating, REST
Applicationsengine using Flask APIs
A Twitter bot that
Automation APIs, JSON parsing, time scheduling,
posts scheduled
Bots automation techniques
updates
A weather app
Data-Driven Working with APIs, data visualization,
using real-time API
Apps error handling
data
App Type Project Example Skills Learned
GUI A to-do list app Graphical interfaces, event handling,
Applications using Tkinter object-oriented design
Working with external libraries like
Scripting & A PDF merger and
PyPDF2, understanding modular
Utilities splitter
architecture
Game
A simple arcade- Game loops, sprite handling, collision
Developmen
style game detection, basic physics
t
Each of these projects will help you master different elements of Python.
You’ll become fluent in the language by solving real problems, which is far
more effective than rote memorization.
What is Project-Based Learning?
Project-based learning (PBL) is an instructional methodology that
encourages learning through hands-on projects. Rather than simply learning
about concepts in isolation, PBL immerses learners in practical challenges.
You’re not just learning the syntax of a programming language; you’re
understanding how to use it as a tool.
Here’s how project-based learning benefits you
Engagement Building something tangible keeps you motivated.
Retention You remember things better when you apply them immediately.
Contextual Understanding Instead of abstract lessons, you learn why
something is important.
Problem Solving You get better at debugging, critical thinking, and
developing creative solutions.
Portfolio Building You’ll finish with a set of working applications you can
showcase to potential employers or collaborators.
We also take this one step further by aligning each project with a mini-
capstone challenge, encouraging you to modify or enhance the base
application with custom features. This lets you apply creativity, deepen
your learning, and make each project your own.
Understanding the Build-Measure-Learn Cycle
One of the most powerful ways to grow your coding ability is to adopt the
Build-Measure-Learn loop, a concept borrowed from lean startup
methodology. Here’s how it works in the context of this book
Build Start with a goal. Write the code to create a functional version of your
app.
Measure Use the app. Does it behave as expected? What are its limitations?
Gather feedback.
Learn Based on your observations, refactor or improve the app. Add
features. Fix bugs. Optimize performance.
This loop not only reinforces Python concepts but also mimics real-world
software development. You’ll learn how to write minimum viable products
(MVPs), deal with bugs and edge cases, optimize code, and document your
process.
Hands-On Projects, Step-by-Step
Each chapter in this book walks you through a complete app development
project. These are not just tutorials; they are guided builds that explain
every line of code, every choice, and every potential extension. For
example, when building the file organizer app, you’ll learn
How to access directories and files using Python’s os and shutil
modules.
How to filter files by extension and move them automatically.
How to handle user input and invalid paths.
How to turn a script into a GUI using Tkinter .

How to package your script into a standalone executable.

This step-by-step approach is key to mastering the skills necessary to


develop apps on your own. By the end of each chapter, you won’t just have
a working app—you’ll have the confidence and knowledge to extend it or
build something similar from scratch.
Building Skill by Skill
Python isn't just about writing code; it’s about thinking logically, solving
problems, and understanding how systems interact. With each app you
build, you’ll strengthen multiple skill areas.
Here’s a table showing how your skill set will evolve
Project Python Concepts Mastered Secondary Skills Gained
File handling, conditional File system navigation, OS
File Organizer
logic integration
Tkinter, class-based UI design, state
GUI To-Do List
programming management
Flask Blog Flask, templating, routing, Front-end/back-end
Engine RESTful APIs interaction
Twitter HTTP requests, JSON,
Social media APIs, OAuth
Automation Bot authentication
Weather API integration, JSON,
Data visualization
Forecast App exception handling
Game with Loops, events, timers, Game mechanics, sprite
Pygame functions animation
Third-party libraries, modular Document handling, file
PDF Tool
code security
This book isn’t about memorizing commands—it’s about transformation.
You’re not just becoming someone who knows Python; you’re becoming
someone who builds with Python. Whether your goal is to automate boring
tasks, create your own tools, start a business, or land a job in tech, the
journey begins here—with your hands on the keyboard, building one app at
a time.
In the next chapter, we’ll set up your development environment so you're
ready to dive into your first Python-powered creation a smart file organizer.
Let’s get building.
Chapter 2
Getting Started – Setup, Tools, and Your First App

Before you can dive into the rich world of Python programming and start
creating applications, you must prepare your development environment.
This chapter guides you through setting up Python, installing an editor
(Visual Studio Code or PyCharm), and creating your first real-world
application a Command-Line Interface (CLI) To-Do List App.
This simple app may look small, but it provides the perfect starting point to
explore essential Python concepts such as syntax, variables, data types,
conditional logic, loops, functions, and file input/output. You won’t just
read about these topics—you’ll experience them in a real, working project.
Installing Python The Foundation of All Apps
Python is the programming language we will use throughout this book. It is
open-source, runs on all operating systems, and has a huge ecosystem of
tools and libraries that will power your apps.
To install Python, head over to the official website at https
//[Link]/downloads/ and download the latest version for your
operating system. During the installation process, make sure to check the
box that says “Add Python to PATH.” This step is critical because it
allows you to run Python from any terminal window.
Once installed, you can verify the installation by opening a terminal or
command prompt and typing
python --version
You should see something like
Python 3.11.3

If you get an error, it likely means Python was not added to your system’s
PATH. In that case, re-run the installer and ensure that checkbox is selected.
Choosing and Setting Up Your Code Editor
Coding is best done in a proper environment. While you can technically
write Python code in any text editor, using a dedicated Integrated
Development Environment (IDE) dramatically improves productivity. Two
excellent options are Visual Studio Code (VS Code) and PyCharm.
Visual Studio Code (Recommended for Beginners)
VS Code is lightweight, fast, and highly customizable. It supports Python
via extensions and has excellent integration with Git and terminal
commands.
1. Download VS Code from https //[Link]/.
2. Once installed, open it and install the Python extension (search for
“Python” in the Extensions tab and install the one from Microsoft).
3. Open a terminal within VS Code by selecting Terminal > New
Terminal.
4. Create a new folder for your project
mkdir todo_app
cd todo_app

5. Create a new file called [Link] . This will be the main script for
your To-Do app.

PyCharm (Recommended for Full-Scale Projects)


If you prefer an all-in-one solution with more features like intelligent code
completion, project navigation, and powerful debugging, PyCharm is an
excellent choice. You can download the Community Edition from https
//[Link]/pycharm/.
Once you’ve installed it
1. Start a new project.
2. Create a new Python file in the src or root directory and name it
[Link] .

3. You’re ready to start coding!

Understanding Your First Project Structure


Even a simple app needs some structure. Let’s understand how your To-Do
CLI app project is organized. At this point, the structure is simple

[Link] is the main script that contains your Python code.


is a simple text file where we’ll store the user’s to-do items
[Link]
persistently.
This file-based data handling mimics how real-world applications often use
databases or APIs to store and retrieve information. Starting with file I/O
builds a solid foundation before we move on to more complex data
handling techniques.
Let’s Build Your First CLI To-Do App
Now that your environment is set up, let’s get hands-on and start building.
Open your [Link] file and begin typing along.
Step 1 Creating the Menu System
The first thing we want is a basic menu that lets the user choose an action.
def display_menu()
print("\n--- To-Do List ---")
print("1. View Tasks")
print("2. Add Task")
print("3. Remove Task")
print("4. Exit")
This function doesn’t do anything yet, but it teaches the use of functions, a
reusable block of code. You’ll call this function later every time you want to
show the menu.
Step 2 Storing Tasks in a File
To keep things simple, we will use a text file called [Link] . Each task will
be stored on a new line.
def load_tasks()
try
with open("[Link]", "r") as file
tasks = [Link]()
return [[Link]() for task in tasks]
except FileNotFoundError
return []
Here, we learn file handling, lists, and exception management. The try-
except block prevents the program from crashing if the file doesn’t exist. It
also teaches the habit of writing resilient code.
Step 3 Adding and Viewing Tasks
def add_task(task)
with open("[Link]", "a") as file
[Link](task + "\n")

def view_tasks()
tasks = load_tasks()
if not tasks
print("No tasks found.")
else
for index, task in enumerate(tasks, start=1)
print(f"{index}. {task}")
Now you’re working with functions, lists, conditionals, and string
manipulation.
Step 4 Removing a Task
def remove_task(task_number)
tasks = load_tasks()
if 0 < task_number <= len(tasks)
[Link](task_number - 1)
with open("[Link]", "w") as file
for task in tasks
[Link](task + "\n")
else
print("Invalid task number.")
This introduces list operations like pop() and shows how to overwrite files,
teaching data persistence techniques that mimic CRUD operations used in
databases.
Step 5 Putting It All Together
Finally, let’s create the main logic loop that allows the user to interact with
your app
while True
display_menu()
choice = input("Choose an option (1-4) ")

if choice == "1"
view_tasks()
elif choice == "2"
task = input("Enter the task ")
add_task(task)
elif choice == "3"
view_tasks()
try
task_num = int(input("Enter the task number to remove "))
remove_task(task_num)
except ValueError
print("Please enter a valid number.")
elif choice == "4"
print("Exiting the app. Goodbye!")
break
else
print("Invalid choice. Please select from 1 to 4.")
You have now created a fully functional CLI application. This loop allows
the user to keep interacting with the app until they choose to exit. It uses
control flow, input handling, and data validation.
Diagram App Flow
Let’s visualize how your CLI app works with this flow diagram
This kind of structured thinking is the same mental framework used by
software engineers and application developers. It trains you to break
complex systems into manageable steps.
Key Concepts and Skills Gained
Concept Explanation
Variables Storing user input and task data.
Functions Creating reusable blocks of logic.
Conditionals Controlling the flow of the application with if and else .
File I/O Reading from and writing to a text file to persist user data.
Lists and
Managing multiple items and looping through tasks.
Loops
User Input Using input() to allow dynamic interaction.
Error Writing try-except blocks to make your program resilient to
Handling user errors.
What’s Next?
With this first project, you've taken your first real step into the world of
Python programming. You now understand how to set up a project, use
basic syntax, build logic with functions and conditionals, and save data
between sessions. This foundational knowledge will serve you well in all
future projects.
In the next chapter, we’ll elevate this concept by turning this simple CLI
app into a GUI To-Do App using Tkinter, introducing the world of
graphical user interfaces and event-driven programming.
So take a moment to test your app, try adding 10 tasks, remove a few, and
check if it handles everything smoothly. Maybe challenge yourself can you
add a feature to mark a task as “done”? Can you sort tasks alphabetically?
This is how builders evolve into developers.
Let’s keep building.
Chapter 3

Building a GUI with Tkinter – Desktop Notepad App

In this chapter, we are moving beyond the command line and stepping into
the world of graphical user interfaces, or GUIs. Graphical interfaces are
what you see in everyday software—windows with buttons, text boxes,
menus, and other visual elements you interact with using your mouse or
keyboard. Building GUI applications introduces you to event-driven
programming, where the flow of the program depends on user actions, such
as clicking a button or selecting text.
Python comes bundled with a powerful yet simple GUI toolkit called
Tkinter. Tkinter is lightweight, easy to learn, and fully integrated with
Python, making it a perfect starting point for creating desktop applications.
In this chapter, we will build a fully functional Notepad application,
similar to what you use on your computer for taking notes. This Notepad
will include features like saving and opening files, basic font formatting,
menus, and a user-friendly interface—all using pure Python and Tkinter.
This hands-on project will teach you about window layouts, widgets (the
building blocks of GUIs), event handling (how programs respond to user
inputs), and file dialogs. By the end of this chapter, you'll have created a
tool you can use daily, and you’ll understand how to design your own
desktop applications with confidence.
What is Tkinter and Why Use It?
Tkinter is the standard GUI package included with Python. It’s essentially a
thin object-oriented layer on top of the Tk GUI toolkit. Because it comes
with Python, there's no need to install it separately, and it works on all
major platforms like Windows, macOS, and Linux. Tkinter offers all the
essential components you need to build applications, such as buttons,
menus, labels, entry fields, and text boxes.
While there are more modern GUI frameworks like PyQt or Kivy, they are
either not free for commercial use or more complex to set up. Tkinter is
excellent for learning GUI design and prototyping apps quickly.
The Structure of a GUI Application
Before we jump into coding, let’s explore what makes up a GUI app. A
typical application involves several components that are structured in a
certain way
Each component here is a widget the Root Window is the main container,
the Menu Bar contains commands like "Open," "Save," and "Exit," and the
Text Widget is where the user writes notes.
Starting the Notepad App Basic Window Setup
To begin, you need to import Tkinter and initialize the main application
window
import tkinter as tk
from tkinter import filedialog, messagebox, font

root = [Link]()
[Link]("Python Notepad")
[Link]("800x600")

Here, we create the main application window, give it a title, and set its
dimensions. Every Tkinter app begins with creating an instance of the Tk
class, which represents the main window.
Adding a Text Widget The Core of the Notepad
The heart of a Notepad app is the text area where users type their notes. In
Tkinter, this is handled using the Text widget
text_area = [Link](root, wrap="word", undo=True)
text_area.pack(expand=1, fill="both")
The Text widget supports multi-line input, unlike the Entry widget (which is
for single-line input). We also enable word wrapping and undo support. The
pack() method arranges the widget to fill all available space in the window.
Adding a Menu Bar with File Operations
To make your app feel like a true desktop application, we need a menu bar.
Menus in Tkinter are created using the Menu widget and linked to the main
window.
Let’s create basic menu commands New, Open, Save, and Exit.
menu_bar = [Link](root)

file_menu = [Link](menu_bar, tearoff=0)


file_menu.add_command(label="New", command=lambda text_area.delete(1.0, [Link]))
file_menu.add_command(label="Open", command=lambda open_file())
file_menu.add_command(label="Save", command=lambda save_file())
file_menu.add_separator()
file_menu.add_command(label="Exit", command=[Link])

menu_bar.add_cascade(label="File", menu=file_menu)
[Link](menu=menu_bar)
Each menu item uses add_command() to link a label with an action. The
command parameter binds each item to a function. For example, selecting
"New" will delete all text in the editor using text_area.delete() .
Now let’s define the file functions
def open_file()
file_path = [Link](defaultextension=".txt",
filetypes=[("Text Documents", "*.txt"), ("All Files", "*.*")])
if file_path
text_area.delete(1.0, [Link])
with open(file_path, "r") as file
text_area.insert([Link], [Link]())

def save_file()
file_path = [Link](defaultextension=".txt",
filetypes=[("Text Documents", "*.txt"), ("All Files",
"*.*")])
if file_path
with open(file_path, "w") as file
[Link](text_area.get(1.0, [Link]))
This introduces file dialogs, a critical GUI concept that allows users to
choose files using the operating system’s standard file picker. You also learn
how to interact with text inside the Text widget.
Adding Font Formatting Features
Now, let’s make the app feel a bit more powerful by adding options to
change fonts and sizes. We first set a default font
default_font = [Link](family="Helvetica", size=12)
text_area.configure(font=default_font)

To allow the user to change font size, add a new menu item under a Format
menu
format_menu = [Link](menu_bar, tearoff=0)
menu_bar.add_cascade(label="Format", menu=format_menu)

def set_font_size(size)
default_font.configure(size=size)

for size in [10, 12, 14, 16, 18, 20, 24]


format_menu.add_command(label=f"Font Size {size}", command=lambda s=size
set_font_size(s))
This loop dynamically creates menu entries for each font size, and clicking
them updates the font in real time. You’ve now built a real-time settings
system into your app.
Diagram Component Architecture of the Notepad App
Let’s break down the structure of our GUI application
This kind of architecture becomes the blueprint for more advanced apps
you’ll build later. Knowing how to organize windows, menus, and widgets
is a vital GUI skill.
Event Handling and Interaction
One of the powerful concepts in GUI programming is event handling.
Every button click, key press, or mouse event is considered an event.
Tkinter uses the command parameter or the bind() method to associate events
with functions.
For example, to bind the keyboard shortcut Ctrl+S to save the file
[Link]("<Control-s>", lambda event save_file())
This improves usability and teaches how to handle user input outside of
simple clicks.
Final Touch Running the App
At the end of your script, add the main loop to start the GUI
[Link]()
This line starts the event loop and waits for the user to interact with your
app. It keeps the window open until the user closes it.
Summary of Skills Gained
Concept Explanation
Tkinter Basics Creating windows, widgets, and event loops.
Handling user input with a scrollable, editable text
Text Widget
box.
Menu Creation Adding file and formatting options using Menu .
File I/O with Reading and writing files with standard open/save
Dialogs dialogs.
Font Management Changing text appearance using the font module.
Event Handling Responding to user actions like clicks or key presses.
Challenge Enhance Your Notepad App
Try adding more features to solidify your skills
Add a "Dark Mode" toggle.
Implement a "Find and Replace" feature.
Track unsaved changes and prompt the user before exiting.

These enhancements will deepen your understanding of widgets, state


management, and user interaction.
What's Next?
Now that you’ve built your first full-fledged GUI app, you're well-prepared
to take on more sophisticated projects. In the next chapter, we’ll take this
knowledge into a different direction and build a Weather App using APIs,
which will teach you how to interact with online data and parse JSON,
bringing your apps into the real world.
Let’s continue this journey—your desktop app development toolkit is just
beginning to take shape.
Chapter 4

Data Management App – Personal Expense Tracker

In this chapter, we will explore one of the most practical and in-demand
applications of Python—managing structured data through databases.
Specifically, you will build a Personal Expense Tracker a data-driven
application that allows users to record, store, and review their financial
expenses. This project is not only a useful tool you can use every day but
also a real-world example of how Python interfaces with databases to create
powerful applications.
This chapter will guide you through the core concepts of data management
in applications, from understanding databases to executing SQL commands
through Python’s built-in sqlite3 module. You will learn how to store data
persistently, structure it using tables, and retrieve it efficiently using
queries. This application lays the foundation for many advanced apps, from
customer management systems to inventory software and even full-scale
accounting tools.
Introduction to Databases and sqlite3

Before jumping into development, it’s crucial to understand what databases


are and why we use them.
A database is a structured collection of data that can be easily accessed,
managed, and updated. Unlike variables in memory, data in a database is
stored persistently, meaning it remains available even after the program
ends. This persistence is vital for applications that rely on saving user input
over long periods.
SQLite is a lightweight, embedded SQL database engine that comes
bundled with Python. It does not require a separate server process and saves
data in a local file on your system. This makes SQLite an ideal choice for
desktop applications or small-scale systems like our Expense Tracker.
We will use sqlite3 , a Python module that allows you to execute SQL
commands—such as creating tables, inserting data, and retrieving results—
directly from your Python script.
Design of the Expense Tracker App
Let’s first outline what our application will do. The Personal Expense
Tracker will allow users to
1. Add a new expense entry with details such as date, amount,
category, and description.
2. View all saved expense entries in a structured format.
3. Filter expenses by date or category.
4. Persist the data in an SQLite database.

The data structure for each expense entry looks like this
Data
Column Description
Type
id INTEGER Unique identifier for each record
Date of the expense (YYYY-MM-
date TEXT
DD)
amount REAL Expense amount
category TEXT Type of expense (e.g., Food, Travel)
Data
Column Description
Type
descriptio
TEXT Additional notes
n
Let’s visualize the architecture

Step-by-Step Development
Let us now build the app step by step using Python’s sqlite3 and Tkinter for
a basic interface.
Step 1 Setting Up the Database
To start, we need to create the database and the table structure. Here's how
we do it in Python
import sqlite3
def create_database()
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
amount REAL NOT NULL,
category TEXT NOT NULL,
description TEXT
)
""")
[Link]()
[Link]()

create_database()
This function connects to (or creates) a database named [Link] , defines
a table expenses , and ensures that the table is only created if it doesn’t
already exist.
Step 2 Inserting New Expenses
We will create a function to insert a new record into the database. This
function will be called whenever a user adds a new expense
def add_expense(date, amount, category, description)
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("""
INSERT INTO expenses (date, amount, category, description)
VALUES (?, ?, ?, ?)
""", (date, amount, category, description))
[Link]()
[Link]()
Here, ? placeholders are used to prevent SQL injection and promote
security—a good programming practice.
Step 3 Retrieving and Displaying Data
To display all expenses, we can define the following function
def view_expenses()
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT * FROM expenses ORDER BY date DESC")
rows = [Link]()
[Link]()
return rows
This function returns all records, sorted with the most recent date first.
You can also add filters
def filter_expenses_by_category(category)
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT * FROM expenses WHERE category = ?", (category,))
rows = [Link]()
[Link]()
return rows

Step 4 Building a Basic Tkinter Interface


Here’s a basic GUI using Tkinter to input and display expense records
import tkinter as tk
from tkinter import ttk

root = [Link]()
[Link]("Personal Expense Tracker")
[Link]("600x400")

# Input fields
[Link](root, text="Date (YYYY-MM-DD)").grid(row=0, column=0)
date_entry = [Link](root)
date_entry.grid(row=0, column=1)

[Link](root, text="Amount").grid(row=1, column=0)


amount_entry = [Link](root)
amount_entry.grid(row=1, column=1)

[Link](root, text="Category").grid(row=2, column=0)


category_entry = [Link](root)
category_entry.grid(row=2, column=1)

[Link](root, text="Description").grid(row=3, column=0)


desc_entry = [Link](root)
desc_entry.grid(row=3, column=1)

# Add Button
def submit_expense()
add_expense(date_entry.get(), float(amount_entry.get()), category_entry.get(), desc_entry.get())
update_table()

[Link](root, text="Add Expense", command=submit_expense).grid(row=4, column=0,


columnspan=2)
# Table View
tree = [Link](root, columns=("Date", "Amount", "Category", "Description"),
show="headings")
[Link]("Date", text="Date")
[Link]("Amount", text="Amount")
[Link]("Category", text="Category")
[Link]("Description", text="Description")
[Link](row=5, column=0, columnspan=2)

def update_table()
for i in tree.get_children()
[Link](i)
for row in view_expenses()
[Link]("", "end", values=row[1 ]) # Skip ID

update_table()
[Link]()

Summary of Skills Gained


Concept What You Learned and Built
How to create, read, update, and delete records using
SQLite Integration
Python and SQL.
Table Design Structuring data into useful, queryable formats.
Querying and
Creating custom queries for sorting and filtering data.
Filtering
Security Practices Using parameterized queries to prevent SQL injection.
GUI + Database
Linking a visual interface with back-end data storage.
Combo
Event-Driven How button clicks trigger data operations and refresh
Execution the UI.
Challenge Projects to Deepen Your Skills
To further sharpen your skills and prepare for larger applications, try
implementing these features on your own
Add a "Monthly Report" summary that shows total expenses per
category.
Include pie chart visualization using matplotlib to visualize spending
habits.
Create CSV export functionality to back up your database or use it
in spreadsheet software.
Add user authentication to make the tracker multi-user.

You’ve now built a complete data-driven desktop application that combines


the power of persistent data storage with a user-friendly interface. You
learned how to structure data effectively, manipulate it through SQL
queries, and present it dynamically through a graphical interface.
In the next chapter, we will take this even further by connecting Python to
the internet and interacting with external services and APIs. You’ll build a
Weather Forecasting App that fetches real-time data from the web,
allowing you to merge local app logic with global data feeds. Your journey
in Python application development is picking up speed—let’s keep going.
Chapter 5

Web Scraper and Dashboard – News & Weather App

In this chapter, we transition from working solely with local data to


interacting with the vast and ever-changing world of the internet. You will
build a dynamic and visually rich News & Weather App—a desktop
application that fetches real-time data from online sources, processes it, and
presents it in a user-friendly graphical interface.
This project introduces several new concepts web scraping, HTML
parsing, data visualization, API usage, and error handling. Each of these
skills is essential for building modern applications that rely on live data or
automate tasks that typically require manual web browsing.
The News & Weather App will serve two core functions. First, it will use
web scraping to retrieve news headlines from a major news website.
Second, it will use an API to fetch real-time weather information based on
the user’s input location. Finally, this data will be displayed in a clean,
interactive GUI using Tkinter , and weather trends will be visualized using
matplotlib .

Overview of the Project


Tools and Libraries Required
To complete this project, ensure that you have the following Python
libraries installed. These can be installed using pip if they are not already
available in your environment.
pip install requests beautifulsoup4 matplotlib
We will also use Tkinter , which comes pre-installed with Python, to build
the graphical interface.
Step 1 Fetching Weather Data Using an API
We will use the OpenWeatherMap API, which provides reliable and free
weather data. First, you need to create a free account at https
//[Link]/ and generate your API key.
Once you have the key, the base URL to get weather data for a city is
http //[Link]/data/2.5/weather?q={city_name}&appid={API_key}&units=metric
Here is a function in Python to fetch and parse the weather data
import requests

def get_weather(city)
API_KEY = "your_api_key_here"
URL = f"http //[Link]/data/2.5/weather?q={city}&appid=
{API_KEY}&units=metric"

try
response = [Link](URL)
data = [Link]()

if [Link]("cod") != 200
return {"error" [Link]("message", "Unknown error occurred")}

weather = {
"city" data["name"],
"temperature" data["main"]["temp"],
"humidity" data["main"]["humidity"],
"description" data["weather"][0]["description"].capitalize()
}
return weather

except [Link] as e
return {"error" str(e)}
This function sends a request to the weather API, handles the response, and
formats the data into a clean dictionary. It also checks for errors, such as
invalid city names or network issues.
Step 2 Scraping News Headlines Using BeautifulSoup
To fetch the latest headlines, we can scrape a website like BBC News or
any site with a clean HTML structure. We’ll use BeautifulSoup to parse the
HTML.
from bs4 import BeautifulSoup

def get_news()
URL = "https //[Link]/news"
try
response = [Link](URL)
soup = BeautifulSoup([Link], "[Link]")
headlines = []

for item in [Link]("h3") # This selector may need to be updated depending on the site's
layout
title = item.get_text().strip()
if title and len(headlines) < 5
[Link](title)

return headlines

except [Link] as e
return ["Error fetching news " + str(e)]

This function retrieves the HTML content of the news site and uses CSS
selectors to pull out the headlines. We limit the result to 5 for simplicity.
Step 3 Creating the GUI Interface with Tkinter
Now, let’s build the GUI to display this information. We will include
Entry box for city name input.
Labels for weather info.
A listbox or text area for news headlines.
A matplotlib plot embedded in the GUI.
import tkinter as tk
from tkinter import messagebox
from [Link] import Figure
from [Link].backend_tkagg import FigureCanvasTkAgg

root = [Link]()
[Link]("News & Weather App")
[Link]("800x600")

city_var = [Link]()

[Link](root, text="Enter City ", font=("Arial", 14)).pack()


city_entry = [Link](root, textvariable=city_var, font=("Arial", 14))
city_entry.pack()

weather_label = [Link](root, text="", font=("Arial", 12))


weather_label.pack()

news_box = [Link](root, height=10, wrap="word")


news_box.pack()

def update_app()
city = city_var.get()
weather = get_weather(city)

if "error" in weather
[Link]("Error", weather["error"])
return

weather_info = f"City {weather['city']}\nTemperature {weather['temperature']}°C\n" \


f"Humidity {weather['humidity']}%\nDescription {weather['description']}"
weather_label.config(text=weather_info)

news_headlines = get_news()
news_box.delete("1.0", [Link])
for headline in news_headlines
news_box.insert([Link], "• " + headline + "\n")

[Link](root, text="Update", command=update_app).pack()


This code provides a user-friendly way to trigger the fetching of weather
and news data. All results are dynamically inserted into the interface.
Step 4 Adding Weather Trend Graphs Using Matplotlib
Let’s assume you also want to visualize temperature over the next 5 days.
The OpenWeatherMap API offers a 5-day forecast endpoint. Let’s use it to
show trends.
def get_forecast(city)
API_KEY = "your_api_key_here"
URL = f"http //[Link]/data/2.5/forecast?q={city}&appid=
{API_KEY}&units=metric"

try
response = [Link](URL)
data = [Link]()
if [Link]("cod") != "200"
return {"error" [Link]("message", "Unknown error")}

forecast = {}
for entry in data["list"]
date = entry["dt_txt"].split(" ")[0]
temp = entry["main"]["temp"]
if date not in forecast
forecast[date] = []
forecast[date].append(temp)

# Average daily temps


avg_forecast = {date sum(temps)/len(temps) for date, temps in [Link]()}
return avg_forecast

except [Link] as e
return {"error" str(e)}
Now let’s visualize it in the GUI
def plot_forecast(city)
forecast = get_forecast(city)
if "error" in forecast
[Link]("Error", forecast["error"])
return

fig = Figure(figsize=(5, 3), dpi=100)


ax = fig.add_subplot(111)
dates = list([Link]())[ 5]
temps = [forecast[date] for date in dates]
[Link](dates, temps, marker='o')
ax.set_title("5-Day Temperature Forecast")
ax.set_ylabel("Temperature (°C)")
ax.set_xlabel("Date")

canvas = FigureCanvasTkAgg(fig, master=root)


[Link]()
canvas.get_tk_widget().pack()
[Link](root, text="Show Forecast", command=lambda plot_forecast(city_var.get())).pack()
This function embeds a temperature trend chart directly into your
application, making the dashboard not only informative but also visually
appealing.
Summary of Skills Acquired
Skill Application in the Project
Extracting news headlines using HTML parsing with
Web Scraping
BeautifulSoup
Accessing real-time weather and forecast data with
API Interaction
error handling
GUI
Creating an interactive desktop interface using Tkinter
Development
Data
Displaying charts and trends with matplotlib
Visualization
Managing network errors, API limits, and incorrect
Error Handling
inputs
Integration of Combining multiple data streams into one cohesive user
Sources experience
Practice Projects for Readers
To reinforce your learning and take this project further, try these extensions
Add search filters or categories to the news feed.
Display weather icons using PIL and the weather condition code
from the API.
Schedule auto-refreshing of the data every hour using after() in
Tkinter.
Allow the user to choose from multiple news sources and
languages.

This chapter equips you with the ability to reach beyond your local machine
and harness data from the internet. You’ve combined the power of web
scraping, APIs, error handling, and visualization to build a real-world
dashboard that is both practical and extensible. With these skills, you can
now create anything from stock market trackers to travel planners and even
automation bots that digest and summarize online content.
In the next chapter, we will explore automation and bots, allowing your
Python apps to perform background tasks—scraping, reporting, sending
emails, and interacting with online services autonomously. Let’s keep
building.
Chapter 6

REST APIs – Currency Converter Web App (Flask)

In the previous chapters, we explored how Python could be used to build


desktop applications and perform tasks like scraping data, visualizing
information, and interacting with APIs. In this chapter, we venture into a
powerful domain of modern application development web development
using Flask. Our goal is to design and build a fully functional Currency
Converter Web App using Python’s Flask web framework.
The project is designed to teach the fundamentals of REST APIs, HTTP
methods (GET and POST), routing, template rendering using Jinja2, and
how to dynamically present content to users based on their input. By the
end of this chapter, you will understand how to build a lightweight web
server, interact with external APIs to retrieve live data, and present that data
cleanly on a web interface.
This hands-on project-based approach ensures that you are not just learning
Flask syntax—you are building a complete web product that can be
hosted and accessed via a browser.
Why Flask and Not Something Else?
Flask is often referred to as a “micro-framework”. Unlike full-stack
frameworks such as Django, Flask does not come bundled with form
validation tools, admin panels, or authentication systems by default.
However, this minimalism is what makes Flask highly appealing for
beginners and professionals alike. It provides complete control over the
application structure and allows you to add components only when you
need them.
When a user visits a web page, their browser sends a request (usually a
GET request). Flask handles this request through routes, fetches data (from
a database or external API), and uses templates to render the HTML
response dynamically.
Step-by-Step Project Currency Converter Web App
Let’s build a complete Currency Converter that allows the user to input an
amount, choose a source and target currency, and see the converted result
using live exchange rates.
Step 1 Install Flask and Required Libraries
Before we begin coding, make sure Flask is installed in your Python
environment. You can do this with pip
pip install flask requests
We’ll also use the requests library to call an external REST API that
provides real-time currency exchange rates.
Step 2 Project Structure and Files
We will structure our Flask app as shown below
[Link] The main application script
This folder contains HTML templates rendered by
templates/
Flask using Jinja2
static/ Contains CSS or JavaScript files

This modular structure is scalable and easy to maintain.


Step 3 Flask Application Code ( [Link] )
Let us now create our main Flask app. Below is the annotated code
from flask import Flask, render_template, request
import requests

app = Flask(__name__)

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


def index()
result = None
error = None
currencies = ["USD", "EUR", "GBP", "INR", "JPY", "AUD", "CAD"]

if [Link] == "POST"
amount = [Link]("amount")
from_currency = [Link]("from_currency")
to_currency = [Link]("to_currency")

if not amount or not from_currency or not to_currency


error = "All fields are required!"
else
try
url = f"https //[Link]/v4/latest/{from_currency}"
response = [Link](url)
data = [Link]()

if "rates" in data
rate = data["rates"].get(to_currency)
if rate
result = float(amount) * rate
else
error = "Invalid target currency selected."
else
error = "Failed to fetch rates. Try again later."

except Exception as e
error = str(e)

return render_template("[Link]", result=result, error=error, currencies=currencies)


In this script
The root route ( / ) accepts both GET and POST requests.
If it's a GET request, it renders the form.
If it's a POST request, it processes the input, makes an API call,
calculates the conversion, and displays the result.

Step 4 HTML Templates and Jinja2 Templating Engine


[Link] will serve as our main form
<!DOCTYPE html>
<html>
<head>
<title>Currency Converter</title>
<link rel="stylesheet" href="{{ url_for('static', filename='[Link]') }}">
</head>
<body>
<h1>Currency Converter</h1>
<form method="POST">
<label>Amount </label>
<input type="text" name="amount" required><br><br>

<label>From </label>
<select name="from_currency">
{% for currency in currencies %}
<option value="{{ currency }}">{{ currency }}</option>
{% endfor %}
</select><br><br>
<label>To </label>
<select name="to_currency">
{% for currency in currencies %}
<option value="{{ currency }}">{{ currency }}</option>
{% endfor %}
</select><br><br>

<input type="submit" value="Convert">


</form>

{% if result %}
<h2>Converted Amount {{ result | round(2) }}</h2>
{% endif %}

{% if error %}
<p style="color red;">{{ error }}</p>
{% endif %}
</body>
</html>

This template uses Jinja2 syntax to loop over currency options and
conditionally display the result or error message.
Step 5 Adding Style with CSS ( static/[Link] )
body {
font-family Arial, sans-serif;
padding 40px;
background-color #f4f4f4;
text-align center;
}

form {
background-color white;
padding 30px;
margin auto;
width 400px;
box-shadow 0 0 10px rgba(0,0,0,0.1);
}
This adds a professional appearance to the form, giving your web app a
polished look.
Understanding the Key Concepts Through This Project
Let’s look at the various Flask concepts you’ve practiced in this hands-on
project and what skills you’ve built
Concept Explanation and Implementation
Handled with @[Link]() decorators to define GET/POST
Routing
endpoints
HTML files dynamically rendered using Jinja2, allowing for
Templates
variable interpolation
HTTP GET shows the form, POST processes the input and displays
Methods results
REST APIs Integrated a third-party exchange rate API using requests
Error Managed API failures and invalid user inputs gracefully with
Handling feedback in the UI
Dynamic Displayed results based on live data fetched and user
Content selections
Form Extracted input data using [Link]() and processed the
Handling data
Suggested Enhancements for Readers to Try
To further practice and expand your understanding of Flask and REST
APIs, you can try the following enhancements
Add More Currencies Modify the app to fetch a full list of currencies
dynamically from the API.
Currency Graphs Integrate matplotlib or a JavaScript charting library like
[Link] to show historical trends.
User Authentication Allow users to log in and save their conversion
history.
Internationalization Add multilingual support using Flask-Babel.
Deploy to the Web Host the app on platforms like Heroku or
PythonAnywhere for public access.
You’ve now built a fully functional web app using Flask, REST APIs, and
HTML/CSS. More importantly, you’ve understood how a client (browser)
interacts with a server (Flask) and how dynamic data can be pulled and
rendered in real-time. This project provides a strong foundation to build
anything from e-commerce platforms to dashboards, microservices, or
even mobile backend servers.
In the next chapter, we will build on this knowledge by introducing
automation and bot development, allowing your Python apps to interact
with the web autonomously—scheduling tasks, sending messages, scraping
data at intervals, and more. Let’s keep going and take your Python skillset
to a whole new level.
Chapter 7

Authentication and User Management – Flask Login App

In this chapter, we focus on one of the most crucial aspects of modern web
applications authentication and user management. After building a
functional currency converter in the last chapter, it is time to extend your
Flask app with the ability to manage users. Authentication is the process of
verifying a user's identity, while authorization deals with determining their
access rights after login.
We will guide you through creating a secure login and registration system
using Flask, incorporating bcrypt for password hashing, sessions for login
persistence, and an SQLite database for storing user credentials. You will
learn how to build a real-world authentication system from scratch, gaining
a deep understanding of core security practices.
Why Authentication Matters in Web Development
Authentication is the gatekeeper of any multi-user application. Whether it's
a social media platform, an online shop, or a data dashboard, secure user
access ensures
Privacy Only the user can access their data.
Security Prevents unauthorized access or tampering.
User Tracking Enables personalized services and saved progress.
Even small-scale apps can benefit from authentication. In this hands-on
project, you’ll add these features to a Flask app, ensuring you understand
how to apply them in various contexts.
Setting Up the Project Structure
Let’s define the structure of our user management app. We will keep it
modular and clean, as this is essential for scalability and maintainability

[Link] Main application launcher and routes.


[Link] Handles registration, login, and logout logic.
[Link] Initializes and manages the SQLite database.
[Link] Manages data models for users.
templates/ Contains the HTML pages rendered through Jinja2.
static/ Holds styling files (CSS).
[Link] Local SQLite database storing user credentials.
Step-by-Step Project Building the Login App
We will divide this process into foundational blocks database setup, user
registration, password hashing, login/logout functionality, and session
handling.
1. Initializing the Database ( [Link] )
We’ll use sqlite3 to store our user data. Here’s how we create a simple user
table.
import sqlite3

def init_db()
conn = [Link]('[Link]')
cursor = [Link]()
[Link]('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
''')
[Link]()
[Link]()
This function creates a users table where each entry stores a unique
username and a hashed password.
2. Creating the User Model ( [Link] )
To keep the logic modular, we define a set of database access functions
import sqlite3

def add_user(username, password)


conn = [Link]('[Link]')
cursor = [Link]()
try
[Link]('INSERT INTO users (username, password) VALUES (?, ?)', (username,
password))
[Link]()
return True
except
return False
finally
[Link]()
def get_user(username)
conn = [Link]('[Link]')
cursor = [Link]()
[Link]('SELECT * FROM users WHERE username = ?', (username,))
user = [Link]()
[Link]()
return user
These functions allow us to register a new user and retrieve an existing one
during login.
3. User Registration and Password Hashing ( [Link] )
Security is key. Passwords should never be stored in plain text. We use
bcrypt to hash passwords before saving them to the database.

Install bcrypt if you haven't already


pip install bcrypt
Now let’s add the registration logic
from flask import render_template, request, redirect, session, flash
import bcrypt
from models import add_user, get_user

def register_user()
if [Link] == 'POST'
username = [Link]['username']
password = [Link]['password'].encode('utf-8')
hashed = [Link](password, [Link]())

if add_user(username, hashed)
flash("Registration successful. Please log in.")
return redirect('/login')
else
flash("Username already exists.")
return redirect('/register')
return render_template('[Link]')
Here, passwords are hashed using [Link]() before being saved. This
prevents attackers from reading passwords even if the database is
compromised.
4. Login Logic and Session Handling
We now implement login functionality that checks credentials and starts a
session
def login_user()
if [Link] == 'POST'
username = [Link]['username']
password = [Link]['password'].encode('utf-8')
user = get_user(username)

if user and [Link](password, user[2])


session['user'] = username
return redirect('/dashboard')
else
flash("Invalid credentials.")
return redirect('/login')
return render_template('[Link]')
We use Flask's session object to store the logged-in user's data across
different routes. This creates a persistent login state until the user logs out.
To support sessions, don’t forget to set a secret key in [Link]
app.secret_key = "your_secret_key"

5. Logout Function
Logging out is as simple as clearing the session
def logout_user()
[Link]('user', None)
flash("You have been logged out.")
return redirect('/login')

6. Tying It All Together in [Link]

Now we bring in everything and define the main routing


from flask import Flask, session, redirect, render_template
from auth import register_user, login_user, logout_user
from database import init_db

app = Flask(__name__)
app.secret_key = 'your_secret_key'

init_db()

@[Link]('/register', methods=['GET', 'POST'])


def register()
return register_user()

@[Link]('/login', methods=['GET', 'POST'])


def login()
return login_user()
@[Link]('/logout')
def logout()
return logout_user()

@[Link]('/dashboard')
def dashboard()
if 'user' in session
return render_template('[Link]', user=session['user'])
return redirect('/login')

if __name__ == '__main__'
[Link](debug=True)

HTML Templates
Here's a simplified version of the [Link] template
<!DOCTYPE html>
<html>
<head><title>Register</title></head>
<body>
<h1>Register</h1>
<form method="POST">
<input type="text" name="username" placeholder="Username" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>
<input type="submit" value="Register">
</form>
<p><a href="/login">Already have an account? Log in</a></p>
</body>
</html>
The [Link] is nearly identical, with adjusted heading and action.
Visual Flow of the Application
Here's a diagram summarizing the flow
Table Security Best Practices for Authentication
Practice Explanation
Password Hashing Always hash passwords with bcrypt before storing.
bcrypt automatically salts passwords, making hash
Use Salt
lookup infeasible.
Avoid Plaintext
Never store raw passwords in any form.
Storage
Validate Form Sanitize all user inputs to avoid injection or scripting
Inputs attacks.
Use HTTPS Deploy behind HTTPS to encrypt credentials in transit.
Implement timeouts or logout options to reduce session
Session Expiry
hijacking risk.
Secret Keys Keep your app.secret_key secure and random.
Summary and What You’ve Built
By completing this chapter, you now understand the fundamentals of secure
authentication systems in Flask. You've built
A user registration and login system
Password hashing with bcrypt

Persistent login sessions using Flask's session object


SQLite-based user database integration
Basic HTML templates with user feedback and navigation

This lays the groundwork for any future applications that require secure,
multi-user support—whether it's a dashboard, a blog, or a productivity tool.
In the next chapter, we will extend these skills to build automated tools
using schedulers and background tasks, giving you insight into running
scripts at regular intervals or automating workflows for users of your app.
Keep going—you’re becoming a full-stack Python developer one project at
a time.
Chapter 8

Automating Tasks – Email Reminder Bot

In this chapter, we take a significant leap into the world of automation by


building a complete desktop app that functions as an Email Reminder Bot.
The goal of this project is to automate daily or weekly task reminders by
sending out emails at scheduled times. This hands-on application is
designed to help you master time-based automation, understand the
SMTP protocol for sending emails, format professional email content, and
implement event logging for traceability.
By the end of this chapter, you will have created a useful productivity tool
that can automate the act of sending task-based reminders to a list of users.
In doing so, you'll gain a concrete understanding of task scheduling,
background services, string formatting, email protocols, and Python
modules like smtplib , email , and schedule .
Overview of the Project
Let’s begin by understanding the flow of the Email Reminder Bot. The
workflow starts with a structured CSV file containing tasks and their
scheduled reminder times. Python reads this file, formats email content
accordingly, and then uses smtplib to send the reminders automatically.
Structuring the Project
To keep everything modular and professional, the project should be
organized as follows

[Link] The entry point that launches and runs the scheduler.
[Link] Manages all email operations and formatting.
[Link] Reads tasks and schedules them.
[Link] Handles logging for successful and failed email events.
[Link] The data file that contains scheduled tasks and emails.
[Link] Stores email server credentials and settings.
logs/reminder_log.txt Logs all automation events.

Creating the Task File


We'll begin by preparing a CSV file named [Link] . Here's how it should be
structured
Task Tim
Task Description Email Date
ID e
Project deadline user1@[Link] 2025-04- 08
1
reminder m 12 00
2025-04- 09
2 Team meeting notice team@[Link]
12 30
Task Tim
Task Description Email Date
ID e
2025-04- 16
3 Doctor's appointment me@[Link]
12 00
Each row represents a scheduled reminder with a specific timestamp. This
format ensures clarity and machine-readability.
Writing the Scheduler ( [Link] )
We use the schedule library for time-based automation. First, install it using
pip install schedule
Here is the basic code that loads the tasks and schedules them
import csv
import schedule
import time
from datetime import datetime
from mailer import send_email
from logger import log_event

def load_tasks()
with open('[Link]', newline='') as csvfile
reader = [Link](csvfile)
for row in reader
schedule_time = f"{row['Date']} {row['Time']}"
schedule_task(row['Task Description'], row['Email'], schedule_time)

def schedule_task(description, email, schedule_time)


def job()
subject = "Scheduled Reminder"
body = f"This is a reminder for {description}"
if send_email(email, subject, body)
log_event(f"Success Sent '{description}' to {email}")
else
log_event(f"Failed Could not send '{description}' to {email}")

# Calculate delay using datetime for actual deployment


date_time = [Link](schedule_time, "%Y-%m-%d %H %M")
now = [Link]()
delay_seconds = (date_time - now).total_seconds()

if delay_seconds > 0
[Link](delay_seconds).[Link](job)
This script dynamically schedules jobs from the CSV file and executes the
job() function when the specified time is reached.

Writing the Email Sender ( [Link] )


We use smtplib and [Link] to send formatted emails.
import smtplib
from [Link] import MIMEText
from config import SMTP_SERVER, SMTP_PORT, EMAIL_ADDRESS, EMAIL_PASSWORD

def send_email(to_address, subject, body)


try
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = EMAIL_ADDRESS
msg['To'] = to_address

with [Link](SMTP_SERVER, SMTP_PORT) as server


[Link]()
[Link](EMAIL_ADDRESS, EMAIL_PASSWORD)
[Link](EMAIL_ADDRESS, to_address, msg.as_string())
return True
except Exception as e
print(f"Error {e}")
return False

To run this, define your credentials in [Link] like this


SMTP_SERVER = '[Link]'
SMTP_PORT = 587
EMAIL_ADDRESS = 'your-email@[Link]'
EMAIL_PASSWORD = 'your-app-password'
If you're using Gmail, remember to enable "App Passwords" or use OAuth.
Creating a Logger ( [Link] )
Logging is essential for keeping a history of events. Here’s a minimal
logger module
from datetime import datetime

def log_event(message)
with open('logs/reminder_log.txt', 'a') as f
timestamp = [Link]().strftime('%Y-%m-%d %H %M %S')
[Link](f"{timestamp} - {message}\n")
This ensures every action is recorded with a timestamp.
Launching the Bot ( [Link] )
The main script ties everything together
import time
from scheduler import load_tasks

print("Initializing Email Reminder Bot...")


load_tasks()

while True
schedule.run_pending()
[Link](1)
Once this script is running, it continuously checks for tasks and sends
reminders at the correct times.
Diagram Module Interactions
Here’s how the modules interact at runtime
Each module performs a clearly defined role, emulating production-level
design patterns.
Sample Output in Log File
The reminder_log.txt file will look something like this after successful
execution
2025-04-12 08 00 00 - Success Sent 'Project deadline reminder' to user1@[Link]
2025-04-12 09 30 01 - Success Sent 'Team meeting notice' to team@[Link]
This becomes extremely helpful when debugging or confirming email
delivery.
Table Python Modules and Their Purpose
Module Purpose
smtplib Establish SMTP connections to send email
schedule Schedule tasks to run at a specific time
[Link]
e Format emails with headers and body
csv Read structured task information from a file
datetime Calculate time differences and format timestamps
Manage file system paths and environment
os
settings
Challenges to Build Skills Further
Once your base application is complete, consider adding these
enhancements
Support for recurring tasks (daily/weekly).
GUI interface using Tkinter for non-technical users.
Attachment support in emails.
Integrate a database (SQLite) instead of a CSV file.
Add a web dashboard with Flask to view task status.

In this chapter, you've built an Email Reminder Bot capable of reading


scheduled tasks from a CSV file, formatting them as emails, and sending
them at the right time using SMTP. You've worked with scheduling
automation, email formatting, and proper logging—all essential for real-
world desktop or backend services.
This project is not only useful in itself, but it also lays the foundation for
developing more complex automation tools, such as daily reports,
personalized email digests, or even AI-enhanced bots.
In the next chapter, we will take your backend skills to the web frontend by
building a React + Flask hybrid application, combining the best of both
worlds Python’s logic and JavaScript’s interactivity. You're well on your
way to becoming a well-rounded Python developer.
Chapter 9

Interactive Command Line Tool – Password Manager

In the digital age, managing multiple passwords has become a crucial task
for both individuals and businesses. With rising security threats, it is
essential to store passwords safely using encryption and to retrieve them
efficiently without compromising privacy. In this chapter, we will build a
fully functional and secure command-line password manager. This tool
will allow users to store, retrieve, and manage passwords locally with
encrypted storage.
This hands-on project focuses on core Python techniques, including
command-line interaction, secure password input, data encryption,
password generation, and secure file handling. By working through this
project, readers will develop a clear understanding of how secure
command-line applications are designed and built from scratch.
Project Objectives
The purpose of this project is to teach you how to build a local password
manager that operates entirely from the terminal. The features of the tool
include
Storing passwords securely using AES encryption.
Accepting passwords using getpass to hide typed characters.
Reading and writing data from an encrypted local file.
Command-line interaction with argparse for parsing user inputs.
Generating strong passwords automatically.
Displaying only decrypted passwords when explicitly requested.

Project Structure
We will begin by organizing the password manager project into logical
components
[Link] the main logic and command-line argument
parsing.
[Link] is responsible for all encryption and decryption
functions.
password_gen.py provides a secure password generator.
[Link] is an encrypted file storing password data.
[Link] contains the master key used for encryption/decryption.

Creating the Encryption Key


To securely store and retrieve passwords, we use the cryptography library’s
Fernet module which provides symmetric encryption based on AES. Install
the module first using
pip install cryptography
Then, generate an encryption key that will be used throughout the
application
# [Link]
from [Link] import Fernet

def generate_key()
key = Fernet.generate_key()
with open('[Link]', 'wb') as key_file
key_file.write(key)

def load_key()
with open('[Link]', 'rb') as key_file
return key_file.read()
Call generate_key() only once to create your vault key. This key must be
stored securely and never shared, as it is the only way to access the
encrypted database.
Encrypting and Decrypting Passwords
We now define the encryption and decryption functions, which use the
Fernet object for secure operations
# [Link] continued
def encrypt_data(data)
key = load_key()
f = Fernet(key)
return [Link]([Link]())
def decrypt_data(token)
key = load_key()
f = Fernet(key)
return [Link](token).decode()
These functions will convert plaintext into encrypted text and vice versa,
ensuring passwords are never stored unencrypted.
Building the Password Generator
A good password manager should offer the ability to generate strong
random passwords. This module uses secrets and string for secure password
generation
# password_gen.py
import string
import secrets

def generate_password(length=16)
characters = string.ascii_letters + [Link] + [Link]
return ''.join([Link](characters) for _ in range(length))
This will create a random and secure password of the desired length using a
cryptographically strong random generator.
Securely Getting Input from the User
To avoid displaying sensitive data on screen when users input passwords,
we use Python’s getpass module
import getpass

master_password = [Link]("Enter your master password ")


This method prevents passwords from being visible in the terminal as they
are typed.
Creating the Encrypted Database
We store all password data in a JSON file that is encrypted before writing
and decrypted upon reading. Here is a function to write and retrieve data
from this database
import json
from encryption import encrypt_data, decrypt_data

def save_entry(service, username, password)


try
with open('[Link]', 'rb') as db
encrypted_data = [Link]()
decrypted_data = decrypt_data(encrypted_data)
entries = [Link](decrypted_data)
except FileNotFoundError
entries = {}

entries[service] = {'username' username, 'password' password}


encrypted_data = encrypt_data([Link](entries))
with open('[Link]', 'wb') as db
[Link](encrypted_data)

def get_entry(service)
try
with open('[Link]', 'rb') as db
encrypted_data = [Link]()
decrypted_data = decrypt_data(encrypted_data)
entries = [Link](decrypted_data)
return [Link](service, None)
except Exception
return None

Command Line Interface with argparse

The main script uses the argparse module to parse commands from the user
# [Link]
import argparse
from password_gen import generate_password
from encryption import generate_key
from manager import save_entry, get_entry

parser = [Link](description='Command-Line Password Manager')


parser.add_argument('--setup', action='store_true', help='Initialize encryption key')
parser.add_argument('--add', nargs=3, metavar=('SERVICE', 'USERNAME', 'PASSWORD'),
help='Add new password')
parser.add_argument('--get', metavar='SERVICE', help='Retrieve password')
parser.add_argument('--gen', type=int, metavar='LENGTH', help='Generate a random password')

args = parser.parse_args()

if [Link]
generate_key()
print("Vault key generated and stored in [Link].")

service, username, password = [Link]


save_entry(service, username, password)
print(f"Password for {service} saved successfully.")

elif [Link]
entry = get_entry([Link])
if entry
print(f"Service {[Link]}\nUsername {entry['username']}\nPassword {entry['password']}")
else
print("No entry found.")

elif [Link]
password = generate_password([Link])
print(f"Generated Password {password}")
This CLI allows users to run the following commands
python [Link] --setup – Initializes the encryption system.
python [Link] --add Gmail myemail@[Link] MySecurePass123! – Stores
login.
python [Link] --get Gmail – Retrieves the stored password.
python [Link] --gen 24 – Generates a secure password of 24 characters.

Example Output
Let’s say the user runs the command
python [Link] --add Netflix user@[Link] 98f$Tg&lK2
The data stored in [Link] will look like this (encrypted form)
gAAAAABf3lJ3gqJ8zM9Fq1ZbgJ7zAeM9n4O...
Then, calling
python [Link] --get Netflix

Will output
Service Netflix
Username user@[Link]
Password 98f$Tg&lK2

Table – Modules and Their Functionality


Module Purpose
argparse Command-line argument parsing
getpass Securely get user input without echo
cryptograph
y Encrypt and decrypt stored data
Module Purpose
secrets
Generate cryptographically secure
passwords
json Store structured data in file
os File management and key handling
Security Considerations
Storing passwords, even encrypted, requires following best practices
Never store the encryption key ( [Link] ) in public repositories.
Always use getpass for secure inputs.
Avoid printing passwords in logs or errors.
Use Fernet symmetric encryption, which automatically handles
salt and initialization vector.
Ensure your [Link] and [Link] are in .gitignore if using
version control.

Skill Extensions
To extend your learning, consider adding the following features
Password expiration reminders.
Backup and restore mechanism.
Login authentication with master password.
QR code password sharing.
Integration with clipboard managers.
Desktop GUI using Tkinter or web app using Flask.

You’ve now created a complete, secure, and efficient command-line


password manager in Python. This project equipped you with skills in
cryptography, secure file handling, command-line interfaces, and data
encryption techniques. This kind of application can be easily scaled,
modified, and used in real-world scenarios. By building this tool, you have
taken a step closer to mastering secure software development, and you're
now fully prepared to explore the integration of backend security with GUI
or web frontends in upcoming chapters.
Chapter 10

Realtime Chat App – Using Sockets


Hands-On Guide to Building a Multi-Client Terminal Chat
Application in Python

In this chapter, you will learn to build a fully functional real-time chat
application using Python’s built-in socket module, accompanied by
threading for handling multiple connections simultaneously. The purpose of
this project is to introduce the foundational principles of network
communication, client-server architecture, and concurrent
programming using threads—all necessary concepts for any kind of real-
time application, from messaging systems and multiplayer games to
collaborative tools and more.
What makes this chapter particularly important is that it provides readers
with the opportunity to build a real-world networked product while
demystifying how online communication really works. You’ll not only
create the product itself but develop an in-depth understanding of the
internals—how devices talk to each other, how messages are transmitted,
and how concurrency works at the socket level.
Understanding Networking in Python
Before jumping into code, it’s vital to understand how computers
communicate over a network. Every time two machines exchange data, they
do so through sockets, which are endpoints in a two-way communication
channel. In this project, one program will act as the server, listening for
connections from multiple clients, and each client will be able to send and
receive messages.
The two core roles are
Server Waits for incoming connections, handles message broadcasting, and
keeps track of active users.
Client Connects to the server, sends user input as messages, and receives
broadcasts from the server.
We will use TCP (Transmission Control Protocol) sockets to ensure
reliable communication. TCP guarantees that all packets will arrive, in
order, and without corruption, which is essential for a chat system.
All clients connect to the same server. Whenever one client sends a
message, the server receives it and broadcasts it to all other connected
clients. The server will use threading to handle each client independently
and in parallel, ensuring real-time communication without delays or
blocking.
The Tools and Techniques Used
In this chapter, we’ll use the following Python modules
socket To create TCP/IP sockets for communication.
threading To run client sessions concurrently on the server.
sysand select For handling command-line output and non-blocking
I/O.
datetime To log messages with timestamps (optional enhancement).

We’ll build two primary scripts


1. – Handles incoming client connections and broadcasts
[Link]
messages.
2. – Connects to the server and allows user input/output for
[Link]
chatting.
Step-by-Step Building the Server
Let’s begin by coding the server. The server will
Bind to a specific IP address and port.
Accept incoming client connections.
Receive messages and rebroadcast them.
Use threading to allow multiple clients to chat at once.
# [Link]

import socket
import threading

# Server setup
HOST = '[Link]' # Localhost
PORT = 55555

# Create a socket object (IPv4, TCP)


server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link]((HOST, PORT))
[Link]()

clients = []
nicknames = []

# Broadcast messages to all clients


def broadcast(message)
for client in clients
[Link](message)

# Handle communication with each client


def handle_client(client)
while True
try
message = [Link](1024)
broadcast(message)
except
index = [Link](client)
[Link](client)
[Link]()
nickname = nicknames[index]
broadcast(f'{nickname} left the chat!'.encode('utf-8'))
[Link](nickname)
break

# Accept new clients


def receive_connections()
print("Server is running and listening...")
while True
client, address = [Link]()
print(f"Connected with {str(address)}")

[Link]('NICK'.encode('utf-8'))
nickname = [Link](1024).decode('utf-8')
[Link](nickname)
[Link](client)

print(f"Nickname of the client is {nickname}")


broadcast(f"{nickname} joined the chat!".encode('utf-8'))
[Link]('Connected to the server!'.encode('utf-8'))

thread = [Link](target=handle_client, args=(client,))


[Link]()

receive_connections()

This code initiates a basic multi-client chat server that listens on port 55555
and assigns each client a nickname. Every new client is given its own
thread for communication so that the server can serve multiple users
concurrently.
Building the Chat Client
The client will
Connect to the server using the same IP and port.
Allow the user to input a nickname.
Send and receive messages continuously in a threaded loop.
# [Link]

import socket
import threading

# Ask for nickname


nickname = input("Choose your nickname ")

client = [Link](socket.AF_INET, socket.SOCK_STREAM)


[Link](('[Link]', 55555))

# Handle receiving messages from the server


def receive()
while True
try
message = [Link](1024).decode('utf-8')
if message == 'NICK'
[Link]([Link]('utf-8'))
else
print(message)
except
print("An error occurred! Disconnecting...")
[Link]()
break

# Handle sending messages to the server


def write()
while True
message = f'{nickname} {input("")}'
[Link]([Link]('utf-8'))

receive_thread = [Link](target=receive)
receive_thread.start()

write_thread = [Link](target=write)
write_thread.start()

The [Link] script creates a clean two-way communication flow. The


receiving thread listens for messages from the server and prints them to the
screen, while the writing thread captures user input and sends it to the
server.
Enhancements to the Application
Once the core functionality is complete, you can build on this foundation by
adding advanced features such as
Timestamping each message using datetime .

Logging chat history to a file.


Allowing private messages with commands like /whisper .

Creating a GUI using Tkinter or PyQt.


Supporting emojis or markdown-style formatting.
Encrypting messages using symmetric encryption like Fernet.

Network Architecture Table


Component Role Technology Used
Server Manages clients, broadcasts socket , threading
Component Role Technology Used
Client Sends/receives messages socket , threading
Communicatio IPv4 , TCP port
Full-duplex over TCP
n 55555
Basic, unencrypted
Security Optional cryptography
(extendable)
Scaling Handles multiple clients Python threads
This real-time chat application is more than just a toy project. It models the
architecture used in multiplayer games, messaging platforms, collaboration
tools, and remote command centers. The key benefit of socket
programming is its low-level control over the network, offering you insight
into how the internet works under the hood.
The project gives you practical experience in
Network protocols.
Concurrent programming.
Real-time data flow.
Writing scalable backend services.

You are encouraged to go beyond this example by experimenting with


message logging, user authentication, offline message caching, or even
turning this into a Flask-powered web application.
In the next chapter, we will build on this networking knowledge to create a
file transfer application, further exploring the possibilities of socket-based
Python development while integrating it with file I/O and progress tracking
systems.
Chapter 11

Working with Files – File Organizer Utility

In this chapter, we will create a File Organizer Utility, a simple yet


incredibly useful tool that automatically sorts files in the Downloads folder
(or any directory you choose) into organized subfolders based on their file
types. The utility will demonstrate practical file management concepts,
including file handling, automation, and organizing files by type, date, or
other criteria. By building this tool, you will not only have a useful script
for your everyday computing tasks but will also learn key aspects of Python
programming related to file systems, paths, and automation.
Why Build a File Organizer?
A lot of times, files you download from the internet or receive in emails end
up in the Downloads folder, resulting in a cluttered mess of various file
types. While it’s easy to find files manually, it can become increasingly
difficult as your files accumulate over time. A file organizer tool like the
one we’ll build in this chapter can save you time by automatically
categorizing files into subfolders based on their file extensions, such as
Images, Documents, Audio, Video, etc.
The File Organizer Utility will take the following steps
1. Scan the specified folder (like Downloads ).

2. Identify the file types based on file extensions (e.g., .jpg , .txt ,
.pdf ).

3. Create folders based on the types of files found.


4. Move files into the corresponding folders.

The core concepts we’ll explore in this chapter include


File I/O (Input/Output) Reading, writing, and moving files.
Path manipulation Using os , pathlib , and shutil to navigate the file system
and manipulate files.
Automation Scheduling the file organization task to run periodically,
ensuring that your downloads folder stays organized automatically.
Getting Started with File Handling in Python
Python provides several built-in libraries to handle file operations. The key
ones we will use in this chapter are
os This module provides functions for interacting with the operating
system, such as navigating directories, renaming files, and checking file
existence.
shutil This module offers high-level file operations, such as copying and
moving files.
pathlib A modern approach to dealing with file system paths. It simplifies
path manipulations and is more intuitive than older methods using [Link] .
Let’s break down how each of these libraries can help us
The os module allows us to get a list of files in a directory and check
whether files exist or not. We will use it to list the files in the specified
folder (like Downloads ) and create new folders for organizing files.
The shutil module provides a convenient way to move files into their
respective directories. This will help us move files to the correct folder.
pathlib allows us to manipulate paths in an object-oriented manner, making
it easier to manage and manipulate directories and file paths.
Creating the File Organizer
Let’s begin by writing a Python script that organizes files by their extension
(e.g., .txt , .jpg , .mp4 , etc.). The basic steps we’ll take are
Scan the target directory List all files present.
Identify file types Based on file extensions.
Create new folders For different file types, if they don’t already exist.
Move files To their appropriate folders.
Here’s the basic implementation of the File Organizer
import os
import shutil
from pathlib import Path

# Define file categories based on file extensions


file_types = {
'Images' ['.jpg', '.jpeg', '.png', '.gif'],
'Documents' ['.pdf', '.txt', '.docx', '.xlsx'],
'Audio' ['.mp3', '.wav', '.flac'],
'Videos' ['.mp4', '.avi', '.mkv'],
'Archives' ['.zip', '.rar', '.tar'],
}

# The folder to organize (can be set to any directory you want)


downloads_folder = Path('C /Users/YourUsername/Downloads')

# Create folders if they don't exist


def create_folders()
for category in file_types
category_path = downloads_folder / category
if not category_path.exists()
category_path.mkdir()
print(f"Created folder {category_path}")

# Sort files into folders


def organize_files()
for file in downloads_folder.iterdir()
if file.is_file() # Only process files (skip subdirectories)
file_extension = [Link]() # Get the file extension and make it lowercase
moved = False

for category, extensions in file_types.items()


if file_extension in extensions
target_folder = downloads_folder / category
[Link](str(file), target_folder / [Link])
print(f"Moved {[Link]} to {category}/")
moved = True
break

if not moved
print(f"File {[Link]} does not match any category.")

if __name__ == "__main__"
create_folders()
organize_files()

Step-by-Step Breakdown
Setting Up File Types We begin by defining a dictionary called file_types to
categorize the types of files we expect. For example, all files with .jpg ,
.jpeg , .png , or .gif extensions will be categorized under the 'Images' folder.
Similarly, files with .pdf , .txt , .docx will go into the 'Documents' folder.
Creating Folders The function create_folders checks if the folders for each
category exist. If a folder doesn’t exist, it creates one using the mkdir
method. This ensures that all necessary subdirectories are available before
we start moving files.
Organizing Files The function organize_files scans the files in the target
directory ( downloads_folder ). For each file, it checks its extension and moves
the file to the corresponding folder based on its type. We use [Link]() to
move the file to the correct subdirectory. If a file doesn’t match any of the
predefined categories, it will be skipped with a notification.
Working with Pathlib
Using Pathlib allows us to work with paths in an object-oriented way. We
use the following features of Pathlib in the code
This creates a Path object for a directory. It’s much
Path('directory')
more readable and intuitive than using raw strings.
This method returns an iterator of all files and
.iterdir()
subdirectories in the directory. It helps us list the files in the target
folder.
.suffixThis returns the file extension, which is used to determine the
file type and categorize it accordingly.
.mkdir() This method creates a new directory if it does not exist.

Additional Features and Enhancements


The File Organizer utility we’ve built so far works for a basic file
organization task. However, you can extend this script with several
enhancements to make it even more useful.
Handling Nested Directories You could modify the script to handle files
located in nested subdirectories by using [Link]() or pathlib ’s rglob() method.
This would allow the utility to traverse subdirectories and organize all files,
not just those in the top level of the directory.
Automating File Sorting You can automate the file organization task by
scheduling it to run periodically using libraries like schedule or by setting it
up as a cron job (on Linux/macOS) or using Task Scheduler (on Windows).
This way, the organizer will run at regular intervals (e.g., once a day) and
keep the Downloads folder organized without any manual intervention.
Handling Unknown File Types Files that don’t match any of the
categories in the file_types dictionary could be moved to a "Miscellaneous"
folder. This would help keep your directory organized even if new or
unusual file types are encountered.
Logging You could add logging to the script to keep a record of all the files
that have been moved and any issues encountered. The Python logging
module would be ideal for this purpose.
Automating the Process with Task Scheduler
To automate the running of your file organizer, you can set up a task in
Task Scheduler on Windows. This will allow your utility to run at a
specific time or interval, making sure that your Downloads folder is always
organized without you having to run the script manually.
1. Open Task Scheduler from the Start menu.
2. Click Create Task in the right-hand panel.
3. In the General tab, give your task a name (e.g., "File Organizer").
4. In the Triggers tab, create a trigger to run the task at specific
intervals (e.g., every day at 6 00 PM).
5. In the Actions tab, set the action to start the Python executable and
add the path to your Python script.
6. Click OK to save the task.

Now, your file organizer will run automatically at the set time, keeping your
Downloads folder neat and tidy!
In this chapter, we built a simple yet practical File Organizer utility using
Python’s os , shutil , and pathlib modules. We explored essential concepts of
file handling and automation, learned to classify and move files based on
their extensions, and discussed ways to automate this task for regular use.
This project not only teaches you fundamental programming concepts but
also gives you a tool you can use daily to maintain an organized digital
workspace. By extending the functionality of this utility, you can create
even more advanced file management tools, which will enhance your
automation skills and serve as a foundation for more complex projects. In
the next chapter, we’ll dive deeper into file I/O and look at creating an
advanced File Backup System to protect your important files, so stay
tuned!
Chapter 12

Data Visualization – COVID-19 Tracker Dashboard

In this chapter, we will walk through the process of creating a COVID-19


Tracker Dashboard using real-time data sourced from a public API. Our
goal is to provide you with a hands-on learning experience by guiding you
step-by-step through building a fully functional dashboard that fetches,
processes, and visualizes COVID-19 statistics. The project will showcase
how to interact with web APIs, parse JSON data, and use powerful Python
libraries like Plotly or matplotlib to create interactive charts and graphs.
Data visualization is a crucial aspect of programming because it helps
transform raw data into meaningful insights. As we go through this project,
you'll learn how to work with real-world data, interact with APIs, and
present the data in a visually appealing and informative way. You’ll also
gain familiarity with important programming concepts such as JSON
parsing, API requests, interactive charts, and dashboard creation.
Getting Started with Data Visualization
Before diving into the specifics of the COVID-19 Tracker Dashboard, let’s
first understand why data visualization is so important. In many industries,
large datasets are collected and analyzed. However, understanding the key
insights from these data sets can be difficult without proper visual
representation. By visualizing the data, we make it easier to spot trends,
relationships, and outliers, enabling better decision-making.
In the case of the COVID-19 pandemic, real-time statistics such as case
counts, deaths, and recoveries are crucial in understanding the current
state of the outbreak and its potential impact on health systems. Building a
dashboard that dynamically updates with the latest information can provide
valuable insights to the public, policymakers, and healthcare professionals.
In this chapter, we will achieve the following
Fetch real-time COVID-19 data using an API.
Parse JSON data from the API.
Create dynamic visualizations such as bar charts, line graphs, and
pie charts.
Build an interactive dashboard to display the visualizations.

Step 1 Fetching Data from an API


To begin, we need to find a reliable API that provides real-time data on
COVID-19 statistics. Fortunately, there are several public APIs available
for free. One such API is COVID-19 API (https //[Link]/),
which provides up-to-date information on COVID-19 cases, deaths,
recoveries, and more.
The first step is to interact with this API and fetch the data. To do this, we
will use the requests library in Python, which allows us to send HTTP
requests and handle responses. Let’s start by installing the necessary
libraries
pip install requests plotly matplotlib
Now, let’s write some Python code to fetch the data
import requests

# URL for the COVID-19 data API


url = 'https //[Link]/summary'

# Send a GET request to the API


response = [Link](url)

# Check if the request was successful


if response.status_code == 200
# Parse the JSON data from the response
data = [Link]()
print(data)
else
print("Failed to retrieve data")
Here, we are sending a GET request to the API’s /summary endpoint, which
provides the most recent COVID-19 statistics globally as well as by
country. If the request is successful (status code 200), we will parse the
response using the .json() method, which converts the API’s response into a
Python dictionary.
Step 2 Parsing JSON Data
The data we receive from the API is in JSON format, which stands for
JavaScript Object Notation. It is a lightweight data interchange format that
is easy for humans to read and write, and easy for machines to parse and
generate. JSON data is structured in key-value pairs, much like a dictionary
in Python.
For example, the response data from the API might look like this
{
"Global" {
"NewConfirmed" 20000,
"TotalConfirmed" 5000000,
"NewDeaths" 1000,
"TotalDeaths" 300000,
"NewRecovered" 15000,
"TotalRecovered" 4700000
},
"Countries" [
{
"Country" "United States of America",
"TotalConfirmed" 1000000,
"TotalDeaths" 25000,
"TotalRecovered" 800000
},
{
"Country" "India",
"TotalConfirmed" 800000,
"TotalDeaths" 15000,
"TotalRecovered" 700000
}
// More countries...
]
}
This JSON data contains a global summary of COVID-19 statistics as well
as detailed information for individual countries. We will parse this data to
extract the relevant statistics for visualization. Let’s focus on the Global
data first and extract key information such as TotalConfirmed,
TotalDeaths, and TotalRecovered.
global_data = data['Global']
total_confirmed = global_data['TotalConfirmed']
total_deaths = global_data['TotalDeaths']
total_recovered = global_data['TotalRecovered']

print(f"Total Confirmed {total_confirmed}")


print(f"Total Deaths {total_deaths}")
print(f"Total Recovered {total_recovered}")
This will output the global statistics, which we can now use in our
visualizations.
Step 3 Data Visualization with Plotly
Now that we have the data, let’s move on to visualizing it. Plotly is an
excellent Python library for creating interactive graphs and dashboards. It is
especially useful for building interactive visualizations that can be
embedded in web applications or desktop applications.
Let’s start by creating a simple bar chart that displays the total confirmed,
deaths, and recovered cases globally. First, we need to import Plotly and set
up the figure
import plotly.graph_objects as go

# Create a bar chart


fig = [Link](data=[
[Link](name='Confirmed', x=['Global'], y=[total_confirmed]),
[Link](name='Deaths', x=['Global'], y=[total_deaths]),
[Link](name='Recovered', x=['Global'], y=[total_recovered])
])

# Update layout to add title and labels


fig.update_layout(
title='Global COVID-19 Statistics',
xaxis_title='Category',
yaxis_title='Count'
)

# Show the figure


[Link]()
In the above code
We use [Link] to create a new figure object, which holds the data
for our plot.
[Link] used to create bar charts for the three categories
Confirmed, Deaths, and Recovered.
update_layout is used to customize the chart’s appearance, including
the title and axis labels.

This will produce an interactive bar chart where users can hover over bars
to see detailed information.
Step 4 Adding More Visualizations and Interactivity
To make the dashboard more insightful, we can add additional
visualizations like line charts or pie charts to track the trends in COVID-19
cases over time or show the distribution of cases across countries.
For instance, to create a pie chart showing the distribution of Total
Confirmed cases across different countries, you could extract data for
multiple countries and visualize it like this
# Extract data for a few countries
countries = ['United States of America', 'India', 'Brazil', 'Russia', 'Turkey']
total_cases = [1000000, 800000, 500000, 400000, 300000]

# Create a pie chart


fig = [Link](data=[[Link](labels=countries, values=total_cases)])

# Update layout
fig.update_layout(title='COVID-19 Total Confirmed Cases by Country')
# Show the figure
[Link]()
This code creates an interactive pie chart that displays the proportion of
total confirmed cases in different countries.
Step 5 Building a Real-Time Dashboard
Now that we have the visualizations ready, let’s combine them into a real-
time dashboard. To build a complete dashboard, we can use Dash, a
Python framework built on top of Plotly that allows us to create web-based
interactive dashboards. With Dash, we can combine different visualizations
into one dashboard and even add interactivity like dropdowns, sliders, and
buttons.
First, install Dash
pip install dash

Here’s a simple Dash app that combines the charts and updates them with
real-time data from the COVID-19 API
import dash
from dash import dcc, html
import plotly.graph_objects as go

app = [Link](__name__)

# Define the layout


[Link] = [Link]([
html.H1('COVID-19 Tracker Dashboard'),

# Bar chart
[Link](
id='global-covid-bar-chart',
figure=[Link](data=[
[Link](name='Confirmed', x=['Global'], y=[total_confirmed]),
[Link](name='Deaths', x=['Global'], y=[total_deaths]),
[Link](name='Recovered', x=['Global'], y=[total_recovered])
])
),

# Pie chart
[Link](
id='country-pie-chart',
figure=[Link](data=[[Link](labels=countries, values=total_cases)])
),
])
# Run the app
if __name__ == '__main__'
app.run_server(debug=True)
This basic Dash app creates a simple dashboard with a bar chart and pie
chart, displaying global COVID-19 data and cases by country. It
automatically updates whenever new data is fetched from the API.
In this chapter, we created a real-time COVID-19 Tracker Dashboard that
fetches live data from a public API, processes it, and displays it using
interactive data visualizations. We used Python’s powerful libraries like
Plotly and Dash to create rich visualizations and build an interactive
dashboard. You learned how to parse JSON data, interact with APIs, and
visualize data using both static and dynamic charts.
As you progress, you can extend this project by adding more features, such
as filtering by country, displaying historical trends, or adding more types of
visualizations like scatter plots or heatmaps. This project not only helps you
learn data visualization but also teaches you how to work with real-time
data and APIs, which are invaluable skills for any developer.
Chapter 13

Game Development with Pygame – 2D Snake Game

Game development is a captivating and rewarding way to learn


programming, as it combines creativity with technical skills. In this chapter,
we will dive into the world of 2D game development using Pygame, a
popular library for creating simple games in Python. Our project will be a
classic Snake game, a well-known game where the player controls a snake
that grows longer with each food item it eats, while trying to avoid running
into walls or itself.
Throughout this chapter, you will learn several fundamental game
development concepts, such as the game loop, collision detection, sprite
management, and handling user input using keyboard controls. These
concepts form the foundation of any game, from simple 2D games to
complex 3D games, and will give you the tools needed to start building
your own games.
By the end of this chapter, you will have created a fully functioning Snake
game where the player can control the snake’s movement, eat food, and
grow longer. You'll also understand how to implement basic game
mechanics and principles, and you will be able to extend the game or create
your own games from scratch.

Setting Up Pygame
Before we begin building the game, we need to set up Pygame. Pygame is a
library that allows you to easily work with graphics, sound, and other game-
related features in Python. To install Pygame, run the following command
in your terminal
pip install pygame

Once you have Pygame installed, we can start coding the Snake game.
Step 1 Game Initialization and Setup
The first thing we need to do is set up our game environment. This includes
initializing Pygame, creating the game window, and defining some
important game settings, such as the screen size, colors, and clock.
We will begin by importing the necessary libraries and initializing Pygame.
We will also define some basic constants for the game, such as the window
dimensions and the color scheme.
import pygame
import time
import random

# Initialize Pygame
[Link]()

# Set up the display window


width = 600
height = 400
screen = [Link].set_mode((width, height))
[Link].set_caption('Snake Game')

# Define colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

# Set up the clock to control the frame rate


clock = [Link]()
snake_block = 10
snake_speed = 15
In the above code
[Link].set_mode() sets the screen size to 600x400 pixels.
[Link].set_caption() sets the title of the game window.
helps control the game's frame rate, ensuring the game
[Link]()
runs at a consistent speed.
defines the size of the snake's body, and
snake_block snake_speed controls the
snake’s movement speed.
Step 2 Defining the Snake
Now that we have set up the basic game environment, we need to define the
snake and its movement. The snake will be a collection of blocks, and it
will grow in length each time it eats food.
To start, let’s write a function to draw the snake on the screen. We will
represent the snake as a list of coordinates, with each coordinate
representing a segment of the snake’s body. When the snake moves, we will
update the positions of these segments.
def our_snake(snake_block, snake_list)
for x in snake_list
[Link](screen, green, [x[0], x[1], snake_block, snake_block])

In this function
takes the snake_block size and a list of
our_snake() snake_list (the
coordinates of each segment).
We loop through the snake_list and draw a rectangle for each
segment using [Link]() . This is how the snake is displayed
on the screen.

Step 3 Handling User Input


Next, we need to handle user input so that the player can control the snake’s
movement using the keyboard. The snake will move in one of four
directions up, down, left, or right. We will use the [Link]() method
to capture keyboard events and update the direction of the snake
accordingly.
def gameLoop()
game_over = False
game_close = False

# Initial position of the snake


x1 = width / 2
y1 = height / 2

x1_change = 0
y1_change = 0

# Create a list to hold the snake’s body


snake_List = []
Length_of_snake = 1

# Food position
foodx = round([Link](0, width - snake_block) / 10.0) * 10.0
foody = round([Link](0, height - snake_block) / 10.0) * 10.0

while not game_over

while game_close
[Link](blue)
message = "You Lost! Press Q-Quit or C-Play Again"
display_message(message, red)
[Link]()

# Check for player input after game over


for event in [Link]()
if [Link] == [Link]
if [Link] == pygame.K_q
game_over = True
game_close = False
if [Link] == pygame.K_c
gameLoop()

for event in [Link]()


if [Link] == [Link]
game_over = True
if [Link] == [Link]
if [Link] == pygame.K_LEFT
x1_change = -snake_block
y1_change = 0
elif [Link] == pygame.K_RIGHT
x1_change = snake_block
y1_change = 0
elif [Link] == pygame.K_UP
y1_change = -snake_block
x1_change = 0
elif [Link] == pygame.K_DOWN
y1_change = snake_block
x1_change = 0

# Check if the snake hits the wall


if x1 >= width or x1 < 0 or y1 >= height or y1 < 0
game_close = True
x1 += x1_change
y1 += y1_change
[Link](blue)

# Draw the food


[Link](screen, red, [foodx, foody, snake_block, snake_block])

# Update the snake’s body


snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake
del snake_List[0]

# Check for collision with the snake’s own body


for x in snake_List[ -1]
if x == snake_Head
game_close = True

# Draw the snake


our_snake(snake_block, snake_List)

# Update the screen


[Link]()

# Check if the snake eats food


if x1 == foodx and y1 == foody
foodx = round([Link](0, width - snake_block) / 10.0) * 10.0
foody = round([Link](0, height - snake_block) / 10.0) * 10.0
Length_of_snake += 1

# Control the game’s frame rate


[Link](snake_speed)

[Link]()
quit()
In the gameLoop() function
We handle user input to move the snake in four directions up,
down, left, and right.
The game continues running until the snake collides with the walls
or itself.
The snake eats food and grows longer.
If the snake hits the wall or itself, the game ends, and the player
can choose to either quit or restart the game.

Step 4 Displaying Messages


To display messages (such as "Game Over" or instructions), we can create a
display_message() function
def display_message(msg, color)
font_style = [Link]("bahnschrift", 25)
mesg = font_style.render(msg, True, color)
[Link](mesg, [width / 6, height / 3])
This function takes a message and a color, renders the message using a
specific font, and then blits (draws) it onto the screen at a specified location.
Step 5 Running the Game
Finally, we call the gameLoop() function to start the game
gameLoop()
This initiates the main game loop, allowing the player to control the snake
and play the game.
In this chapter, you’ve learned how to create a simple 2D Snake Game
using Pygame. We covered key concepts such as game loops, user input
handling, collision detection, and sprite management. These are
fundamental building blocks of game development and provide a solid
foundation for creating more complex games in the future.
You can enhance the game further by adding features such as
Scoring system
Levels with increasing difficulty
Sounds and music
Different game modes

By experimenting with these concepts and expanding on this project, you


will continue developing your game development skills, and soon you’ll be
able to build even more advanced games on your own!

Chapter 14
Machine Learning Mini App – Image Classifier

Machine learning is a powerful tool used to build intelligent applications


that can recognize patterns and make predictions. One of the most common
uses of machine learning is image classification, where a model is trained
to recognize and categorize images into predefined classes. In this chapter,
we will guide you through building a simple image classifier using scikit-
learn or TensorFlow Lite and integrate it into a Graphical User Interface
(GUI) application.
By the end of this chapter, you will not only have created an image
classification model but also learned how to incorporate this model into a
working desktop application. Along the way, you will learn the
fundamentals of machine learning, how to preprocess image data, train a
model, and use this model for predictions. The knowledge gained here will
serve as a stepping stone for developing more advanced machine learning
applications in the future.
Understanding Machine Learning Basics
Before jumping into the implementation, it is important to understand the
core principles behind machine learning, especially in the context of image
classification.
Machine learning works by allowing computers to learn from data. This
process involves training a model using labeled examples so that it can
generalize to new, unseen data. For image classification, we use a type of
machine learning called supervised learning. In supervised learning, the
algorithm learns from input-output pairs. The input is typically an image,
and the output is the corresponding label or category for that image.
To classify an image, the model looks for patterns or features in the image
that distinguish one class from another. In our case, we will train a model to
classify images of different objects (e.g., cats, dogs, or any other set of
classes) based on the features present in the images.
Step 1 Setting Up the Environment
To build the image classifier, you need to install the necessary libraries. We
will be using scikit-learn or TensorFlow Lite, depending on your
preference. For this example, we will demonstrate the process using scikit-
learn, as it is simpler and lighter to get started with.
To install the required libraries, use the following commands
pip install scikit-learn matplotlib numpy opencv-python

scikit-learn is the machine learning library we’ll use to build our classifier.
matplotlib will help us visualize images.
numpy is used for numerical operations.
opencv-python is used for image processing.
Step 2 Preparing the Dataset
For image classification, you will need a labeled dataset. A dataset typically
consists of images stored in folders, where each folder corresponds to a
class label. Each image in a folder belongs to the class represented by that
folder's name.
For simplicity, let's consider a dataset of images categorized into two
classes "cats" and "dogs." You can use publicly available datasets, such as
Kaggle’s Cats vs Dogs dataset, or create your own by organizing the
images in the following structure
dataset/
cats/
[Link]
[Link]
...
dogs/
[Link]
[Link]
...
Once the dataset is organized, we can start processing the images and
converting them into a format suitable for training the model.
Step 3 Preprocessing the Data
Images come in various sizes and formats, and before we can train a
machine learning model, we need to preprocess the images. This involves
resizing the images to a consistent size, converting them into numerical data
(pixel values), and normalizing the values.
To preprocess the images, we will use OpenCV to read and resize them.
Here’s an example of how to load and preprocess images
import cv2
import os
import numpy as np

# Function to load and preprocess images


def load_data(dataset_dir, img_size=(64, 64))
images = []
labels = []
class_labels = {'cats' 0, 'dogs' 1}

for label in class_labels


folder_path = [Link](dataset_dir, label)
for img_name in [Link](folder_path)
img_path = [Link](folder_path, img_name)
img = [Link](img_path)
img = [Link](img, img_size) # Resize to consistent size
img = [Link]("float32") / 255.0 # Normalize pixel values
[Link](img)
[Link](class_labels[label])

return [Link](images), [Link](labels)

# Load the dataset


images, labels = load_data("dataset")
In this code
[Link]() is used to read an image from the file system.
[Link]() resizes the image to a consistent size (in this case, 64x64
pixels).
Normalization scales the pixel values from the range of 0-255 to a
range of 0-1, which helps the model learn more effectively.

Step 4 Training the Model


Now that the images are preprocessed, it’s time to train a machine learning
model. We will use scikit-learn’s Support Vector Machine (SVM)
classifier, which works well for simple classification tasks.
To train the model, we will split the dataset into a training set and a test
set. The training set will be used to teach the model, while the test set will
be used to evaluate its performance.
from sklearn.model_selection import train_test_split
from [Link] import SVC
from [Link] import accuracy_score

# Split data into training and test sets


X_train, X_test, y_train, y_test = train_test_split(images, labels, test_size=0.2, random_state=42)

# Flatten the images from 3D to 2D (64x64x3 to 12288)


X_train = X_train.reshape(X_train.shape[0], -1)
X_test = X_test.reshape(X_test.shape[0], -1)

# Train a Support Vector Machine (SVM) classifier


model = SVC(kernel='linear')
[Link](X_train, y_train)

# Make predictions on the test set


y_pred = [Link](X_test)
# Evaluate the model’s accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Model accuracy {accuracy * 100 .2f}%")
In this code
train_test_split() divides the dataset into training and testing sets.
[Link]() trains the model using the training data.
makes predictions on the test set, and
[Link]() accuracy_score()
calculates how well the model performed.
Step 5 Integrating the Model into a GUI
Now that we have trained the image classifier, we can integrate it into a
GUI application using Tkinter. The GUI will allow users to upload an
image, classify it using the trained model, and display the result.
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk

# Function to classify the uploaded image


def classify_image()
file_path = [Link](title="Select an Image")
if file_path
img = [Link](file_path)
img = [Link](img, (64, 64)) # Resize to match training image size
img = [Link]("float32") / 255.0
img = [Link](1, -1) # Flatten the image
prediction = [Link](img)
result_label.config(text="Prediction " + ("Cat" if prediction == 0 else "Dog"))

# Set up the GUI


root = [Link]()
[Link]("Image Classifier")

# Create a button to select an image


select_button = [Link](root, text="Select Image", command=classify_image)
select_button.pack()

# Label to display the prediction


result_label = [Link](root, text="Prediction None")
result_label.pack()

# Run the GUI


[Link]()
In this GUI
[Link]() opens a file dialog to select an image.
loads the selected image, and we preprocess it to match the
[Link]()
format expected by the model.
The prediction result (either "Cat" or "Dog") is displayed on the GUI.
In this chapter, you have learned how to build a simple image classifier
using scikit-learn and integrate it into a GUI application. You now
understand the basic principles of machine learning for image
classification, including data preprocessing, model training, and making
predictions. Additionally, you have gained experience in combining
machine learning models with graphical user interfaces, which is an
essential skill for building interactive and user-friendly applications.
As you continue your journey into machine learning, you can explore more
advanced techniques and models, such as deep learning with TensorFlow
or Keras, to improve the accuracy and capabilities of your image
classifiers. By experimenting with different datasets and algorithms, you
can create sophisticated image classification systems for a wide range of
applications.
Chapter 15

Deploying Your Python App

After putting in the hard work of building your Python applications—


whether they are desktop apps or web apps—the next step is to make these
apps accessible to users. Deploying your Python application properly is
critical for ensuring its usability, accessibility, and scalability. Whether you
are building a desktop application that users will download and run on
their own machines, or a web application hosted on a server and accessible
through a browser, this chapter will walk you through the process of
deploying your Python app.
This chapter will cover packaging and deploying Python applications using
two primary methods PyInstaller for desktop applications and Heroku or
Render for Flask web applications. In addition, we will delve into the
concepts of virtual environments, managing project dependencies, and
introducing you to basic Continuous Integration and Continuous
Deployment (CI/CD) pipelines, which are crucial for modern application
development and deployment workflows.
By the end of this chapter, you will have the knowledge to package your
application for distribution, deploy it to the cloud, and manage your
development environment and dependencies effectively. You will also gain
an understanding of the basic concepts behind CI/CD, which will be useful
when you scale your projects in the future.
Setting Up a Virtual Environment
Before diving into deployment, it is essential to understand virtual
environments and their role in managing dependencies. A virtual
environment is an isolated environment that allows you to manage
dependencies for a project separately from your global Python installation.
This is especially helpful when you’re working on multiple projects that
require different versions of Python or external libraries.
To set up a virtual environment, follow these steps
Install virtualenv

If you haven’t already installed virtualenv , you can do so by running the


following command
pip install virtualenv

Create a Virtual Environment


Navigate to the root directory of your project, and create a new virtual
environment by running
virtualenv venv

This command creates a new directory called venv , where the isolated
Python environment will reside.
Activate the Virtual Environment
On macOS or Linux, activate the virtual environment using
source venv/bin/activate
On Windows, use
.\venv\Scripts\activate

Install Dependencies
Once the virtual environment is activated, you can install the required
dependencies for your project using
pip install <dependency>
After installing all the required libraries, it’s a good practice to save them in
a [Link] file so that other developers can easily replicate the
environment.
pip freeze > [Link]
This generates a list of installed packages, which can later be installed by
running
pip install -r [Link]

Packaging Desktop Apps with PyInstaller


If your Python application is a desktop app, you will want to package it into
a standalone executable so that users can run it on their machines without
needing to install Python or any dependencies. PyInstaller is a tool that
makes this process easy by bundling your Python code into a single
executable file.
Here’s how to package your Python desktop application with PyInstaller
Install PyInstaller
To begin, you need to install PyInstaller. You can do this by running
pip install pyinstaller
Package the Application
After installing PyInstaller, you can create the executable by running the
following command in your terminal
pyinstaller --onefile your_script.py

The --onefile flag ensures that PyInstaller generates a single executable file.
Replace your_script.py with the name of the Python script that you want to
convert into an executable.
PyInstaller will analyze your Python script, bundle all dependencies, and
create a dist directory containing the executable. You can now distribute
this file to others, and they will be able to run the app without needing to
install Python or any libraries.
Customizing the Executable
PyInstaller also allows you to customize the output of the executable. For
example, you can set the application icon, specify the version of the
executable, and bundle additional files or resources. To include an icon, use
the --icon flag
pyinstaller --onefile --icon=[Link] your_script.py

Distributing the Application


After generating the executable, you can share it with users by uploading it
to your website, hosting it on a file-sharing platform, or distributing it
through other means. The executable can be run on the same operating
system for which it was packaged (e.g., Windows, macOS, or Linux).
Deploying a Flask Web App to the Cloud
If your project is a web application built with Flask, you will need to
deploy it to a server so that users can access it through a web browser.
Platforms like Heroku and Render make deploying Flask applications
incredibly easy. In this section, we will show you how to deploy your Flask
app using Heroku.
Install Heroku CLI
To deploy your Flask app to Heroku, you need to install the Heroku
Command Line Interface (CLI). You can download the Heroku CLI from
the official website Heroku CLI.
Prepare Your Flask App for Deployment
Before deploying, you need to make sure your Flask app is properly
configured. The essential files for deployment are
This file tells Heroku how to run your app. It should contain the
Procfile
following line
web python [Link]

This file contains all the dependencies required for your app.
[Link]
You can generate it by running
pip freeze > [Link]
[Link] This file specifies the version of Python your app uses. For
example
Deploying to Heroku
To deploy your app to Heroku, follow these steps
Initialize a Git repository if you haven’t already
git init

Add your files and commit the changes


git add .
git commit -m "Initial commit"
Create a new Heroku app
heroku create
Deploy the app
git push heroku master
Open the app in your browser
heroku open
Your Flask app will now be live on Heroku, and users can access it by
visiting the URL provided by Heroku.
Setting Up Continuous Integration
In modern software development, CI/CD plays a vital role in automating
the process of testing and deploying applications. CI/CD involves
automatically testing and deploying your code changes as soon as you push
them to a version control system (like GitHub). This ensures that your code
is always tested and deployed without manual intervention.
Integrating GitHub with Heroku
Heroku provides a seamless way to integrate with GitHub, allowing you to
automatically deploy your app every time you push changes to your GitHub
repository.
In your Heroku app dashboard, navigate to the "Deploy" tab.
Connect your GitHub account, select the repository, and enable
automatic deployments for the master branch.
Every time you push changes to your GitHub repository,
Heroku will automatically rebuild and redeploy your app.

Setting Up GitHub Actions


For more advanced CI/CD workflows, you can set up GitHub Actions to
automate testing and deployment. GitHub Actions is a continuous
integration tool that allows you to define workflows using YAML files. For
example, you can create a workflow that runs tests on every pull request
and deploys the app when changes are merged into the master branch.
Example .github/workflows/[Link]
name Deploy to Heroku

on
push
branches
- master

jobs
deploy
runs-on ubuntu-latest
steps
- name Checkout code
uses actions/checkout@v2

- name Set up Python


uses actions/setup-python@v2
with
python-version '3.8'

- name Install dependencies


run |
pip install -r [Link]

- name Deploy to Heroku


env
HEROKU_API_KEY ${{ secrets.HEROKU_API_KEY }}
run |
git remote add heroku https //[Link]/${{ secrets.HEROKU_APP_NAME }}.git
git push heroku master
This configuration ensures that your app is tested and deployed
automatically, providing a smooth, hands-off development experience.
In this chapter, you learned how to deploy your Python applications,
whether they are desktop apps or web apps. You explored PyInstaller for
packaging desktop applications and Heroku for deploying Flask web
applications. We also discussed the importance of virtual environments for
dependency management and introduced you to the basics of CI/CD for
automating the deployment process.
With the knowledge gained in this chapter, you are now ready to deploy
your Python applications and make them accessible to users. Additionally,
by implementing CI/CD pipelines, you will ensure that your applications
are always up-to-date, thoroughly tested, and ready for production
deployment.
By deploying and automating the deployment of your projects, you will
enhance your skill set and bring your applications to a new level of
accessibility and reliability.
Chapter 16

Capstone Project – Personal Productivity Suite

After working through individual Python projects in previous chapters, it's


time to bring everything together and apply your newfound knowledge to
create a comprehensive, fully functional productivity suite. This chapter
will guide you through the process of building a Personal Productivity
Suite, a multi-featured application that includes essential productivity tools
for managing tasks, notes, daily weather and news updates, and email/file
automation. The objective of this project is not only to showcase the
application of concepts from previous chapters, but also to teach you how to
structure a complex Python app into modular components, manage user
data, and deploy the final product.
In this capstone project, we will leverage concepts from GUI design,
databases, automation, and web scraping. By the end of this chapter, you
will have created a fully functioning productivity suite, and you will have
gained hands-on experience with packaging and deploying a Python
application. This project will serve as an excellent portfolio piece,
demonstrating your ability to solve real-world problems with Python.
Building the Personal Productivity Suite
The Personal Productivity Suite will be composed of several core modules
Task Manager with Deadline Reminders
Notes with Cloud Sync
Daily Weather/News Dashboard
File and Email Automation
Each of these features will be developed as a separate module, and then we
will integrate them to form a cohesive suite. Let's go step by step.
Task Manager with Deadline Reminders
The task manager will allow users to add, update, and delete tasks with
specific deadlines. The application will notify users of upcoming deadlines,
which can be sent as reminders via email or displayed as pop-up
notifications.
Step 1 Designing the Task Manager
We will store the task data in a SQLite database. The table will have the
following columns
Task ID (primary key, auto-increment)
Task Name (text)
Description (text)
Deadline (date and time)
Status (open, completed)
Priority (low, medium, high)

Here is the SQL query to create the database


CREATE TABLE tasks (
task_id INTEGER PRIMARY KEY AUTOINCREMENT,
task_name TEXT NOT NULL,
description TEXT,
deadline DATETIME NOT NULL,
status TEXT NOT NULL,
priority TEXT
);
We will use Python's SQLite3 library to interact with this database. The
task manager will provide the following functionalities
Add a new task
Update task details
Delete tasks
List all tasks with deadlines
Send deadline reminders via email or desktop notifications

Step 2 Task Manager Implementation


Start by creating a Python class that will interact with the database. The
class will define methods for adding, updating, and retrieving tasks.
import sqlite3

class TaskManager
def __init__(self, db_name="[Link]")
[Link] = [Link](db_name)
[Link] = [Link]()
self.create_table()

def create_table(self)
query = '''CREATE TABLE IF NOT EXISTS tasks (
task_id INTEGER PRIMARY KEY AUTOINCREMENT,
task_name TEXT NOT NULL,
description TEXT,
deadline DATETIME NOT NULL,
status TEXT NOT NULL,
priority TEXT
)'''
[Link](query)
[Link]()

def add_task(self, task_name, description, deadline, priority="medium")


query = '''INSERT INTO tasks (task_name, description, deadline, status, priority)
VALUES (?, ?, ?, "open", ?)'''
[Link](query, (task_name, description, deadline, priority))
[Link]()

def get_tasks(self)
query = '''SELECT * FROM tasks'''
[Link](query)
return [Link]()

def update_task(self, task_id, task_name=None, description=None, deadline=None, status=None,


priority=None)
query = '''UPDATE tasks SET task_name=?, description=?, deadline=?, status=?, priority=?
WHERE task_id=?'''
[Link](query, (task_name, description, deadline, status, priority, task_id))
[Link]()

def delete_task(self, task_id)


query = '''DELETE FROM tasks WHERE task_id=?'''
[Link](query, (task_id,))
[Link]()
This basic task manager class allows you to interact with the tasks database.
You can now add, update, retrieve, and delete tasks as needed.
Step 3 Implementing Reminders
To implement reminders, we can use Python's smtplib to send emails or the
plyer library to show notifications on the user's desktop. We will compare
the current time with the task deadlines and notify the user accordingly.
You can use the schedule library to schedule the reminder task at regular
intervals to check for upcoming deadlines and send notifications.
import smtplib
from datetime import datetime
from plyer import notification
import schedule
import time

def send_email_reminder(task_name, deadline)


# Code to send email reminder
pass

def check_deadlines()
current_time = [Link]()
tasks = task_manager.get_tasks()
for task in tasks
task_id, task_name, _, deadline, status, _ = task
if status == "open" and [Link](deadline, "%Y-%m-%d %H %M %S") <=
current_time
send_email_reminder(task_name, deadline)
[Link](title="Task Reminder", message=f"Deadline for task '{task_name}' has
passed.")

# Schedule the deadline checker to run every minute


[Link](1).[Link](check_deadlines)

while True
schedule.run_pending()
[Link](1)
This function will check the tasks every minute and send reminders for
those whose deadlines have passed.
2. Notes with Cloud Sync
Next, we will build a Notes module where users can add, edit, and delete
notes. These notes will be synced to the cloud using an API like Google
Firebase or a simple REST API. We will create a Firebase project, set up
an API key, and use Firebase’s Python SDK to upload and retrieve notes
from the cloud.
Step 1 Setting up Firebase
Start by setting up Firebase in your project. Install the Firebase Admin SDK
pip install firebase-admin
Next, initialize the Firebase app with the credentials provided by the
Firebase console.
import firebase_admin
from firebase_admin import credentials, firestore

cred = [Link]("path_to_your_firebase_credentials.json")
firebase_admin.initialize_app(cred)

db = [Link]()
notes_ref = [Link]("notes")

Step 2 Implementing Cloud Sync


Now we can define functions to add, retrieve, update, and delete notes in
Firebase
class NotesManager
def __init__(self, db)
[Link] = db

def add_note(self, note_title, note_content)


note_ref = [Link]("notes").add({
"title" note_title,
"content" note_content
})
return note_ref.id

def get_notes(self)
return [Link]("notes").stream()

def update_note(self, note_id, note_title, note_content)


[Link]("notes").document(note_id).update({
"title" note_title,
"content" note_content
})

def delete_note(self, note_id)


[Link]("notes").document(note_id).delete()
This class allows you to interact with the Firebase database to manage
notes.
3. Daily Weather/News Dashboard
For the weather and news dashboard, we will build a simple GUI that
shows the latest weather updates and news headlines. We will use APIs
such as the OpenWeatherMap API for weather and NewsAPI for news.
Step 1 Weather and News API Integration
First, sign up for free API keys from OpenWeatherMap and NewsAPI.
Then, use the requests library to fetch the latest weather and news data.
import requests

def get_weather(city)
api_key = "your_openweathermap_api_key"
url = f"http //[Link]/data/2.5/weather?q={city}&appid=
{api_key}&units=metric"
response = [Link](url)
data = [Link]()
return data['weather'][0]['description'], data['main']['temp']

def get_news()
api_key = "your_newsapi_key"
url = f"https //[Link]/v2/top-headlines?country=us&apiKey={api_key}"
response = [Link](url)
data = [Link]()
return data['articles']

Step 2 Building the GUI Dashboard


Use Tkinter to create the GUI for displaying the weather and news.
import tkinter as tk

class Dashboard([Link])
def __init__(self)
super().__init__()
[Link]("Productivity Suite Dashboard")
[Link]("400x400")

self.weather_label = [Link](self, text="Weather Info ")


self.weather_label.pack()

self.news_label = [Link](self, text="News Headlines ")


self.news_label.pack()

def update_weather(self, weather_desc, temp)


self.weather_label.config(text=f"Weather {weather_desc}, Temp {temp}°C")

def update_news(self, news)


news_text = "\n".join([article['title'] for article in news])
self.news_label.config(text=f"News \n{news_text}")
This GUI will display the weather and the latest news when the data is
fetched from the APIs.
4. File and Email Automation
The final feature involves automating file organization and email reminders.
Use Python’s os, shutil, and smtplib to implement file organization and
email sending.
The file organizer will sort files into folders based on file types (e.g.,
documents, images, videos), while the email automation will remind users
of their scheduled tasks and deadlines.
Final Integration and Deployment
Once all the modules are created, integrate them into one app. Use Tkinter
for the user interface and organize the app structure into several Python files
for better maintainability. Then, follow the previous chapters' instructions to
package the app using PyInstaller or deploy a Flask-based web version
to Heroku or Render.
With this capstone project, you have created a fully functional personal
productivity suite that incorporates essential tools such as task management,
notes synchronization, weather and news tracking, and email/file
automation. By breaking down each component into manageable tasks and
using the knowledge you've accumulated throughout the book, you've
learned how to build modular, scalable applications. This project serves as
an excellent showcase of your Python skills and will provide valuable
experience in building and deploying real-world applications.
Appendices

Appendix A

Python Syntax Quick Reference

In this appendix, we provide a concise reference to the most commonly


used Python syntax and constructs that will help you as you navigate your
way through projects and tasks. This reference serves as a quick guide to
help you recall important syntax, functions, and structures when working
with Python.
1. Variables and Data Types
In Python, variables are dynamically typed, meaning you don’t have to
declare the type of variable explicitly. The following examples illustrate the
most commonly used data types
x = 10 # Integer
name = "John" # String
pi = 3.14159 # Float
is_active = True # Boolean
Python also supports lists, dictionaries, sets, and tuples. Here are examples
# List
fruits = ["apple", "banana", "cherry"]

# Tuple (immutable)
coordinates = (10, 20)

# Dictionary (key-value pairs)


person = {"name" "Alice", "age" 25}

# Set (unique items)


unique_numbers = {1, 2, 3, 3}

2. Control Flow Statements


If-Else Statements
x = 10
if x > 5
print("Greater than 5")
else
print("Less than or equal to 5")

For Loop
for i in range(5)
print(i)
While Loop
i=0
while i < 5
print(i)
i += 1

Break and Continue


for i in range(5)
if i == 3
continue # Skip iteration
if i == 4
break # Exit loop
print(i)

3. Functions
Functions allow you to reuse code and simplify complex programs.
def greet(name)
return f"Hello, {name}!"

result = greet("Alice")
print(result)

4. Exception Handling
Python uses try and except blocks to catch and handle exceptions.
try
x = 10 / 0 # Division by zero
except ZeroDivisionError
print("You cannot divide by zero!")

5. Classes and Objects


Python is an object-oriented programming language. Here’s how you define
and use classes
class Car
def __init__(self, make, model)
[Link] = make
[Link] = model

def display_info(self)
print(f"Car Make {[Link]}, Model {[Link]}")

car1 = Car("Toyota", "Corolla")


car1.display_info()

Appendix B

Common Errors and Debugging Tips


In Python development, encountering errors is a normal part of the learning
process. Below are some common Python errors and tips for debugging
them.
1. SyntaxError Unexpected EOF while parsing
This error occurs when Python expects more code but reaches the end of the
file. Common causes include missing closing parentheses or quotes. Always
double-check if all parentheses, brackets, and quotes are properly closed.
2. TypeError 'str' object is not callable
This error often arises when you accidentally overwrite a built-in Python
function or method name with a string variable. For instance
str = "Hello"
print(str("World")) # TypeError 'str' object is not callable

Solution Avoid using built-in function names as variable names.


3. KeyError
A KeyError happens when you try to access a dictionary key that does not
exist.
my_dict = {"name" "Alice"}
print(my_dict["age"]) # KeyError
Solution Use get() to safely access dictionary keys.
print(my_dict.get("age", "Not Available")) # Returns "Not Available"

4. Debugging Tips
Use print() statements to display variables and the program's flow
at various points in the code.
For complex projects, consider using a debugger. Python’s built-in
debugger ( pdb ) allows you to step through the code and inspect
variables.
Use IDEs like PyCharm or Visual Studio Code, which provide
interactive debuggers to set breakpoints, step through code, and
inspect variables.
import pdb; pdb.set_trace() # Adds a breakpoint in your code

5. Common Logical Errors


Logical errors often go unnoticed because the program runs without
crashing, but the results are incorrect. Make sure you verify your algorithms
and test with edge cases.
Appendix C Third-Party Library Index and Use Cases
This appendix covers some of the most commonly used third-party libraries
in Python, their use cases, and installation instructions. The libraries are
categorized to help you understand which tools to use for specific tasks.
1. Data Analysis
Pandas Used for data manipulation and analysis, particularly with
structured data such as CSV files or databases.
pip install pandas
NumPy Essential for numerical computing and large, multi-dimensional
arrays and matrices.
pip install numpy

2. Web Development
Flask A micro web framework for building web applications.
pip install flask
Django A high-level Python framework that encourages rapid development
and clean, pragmatic design for web applications.
pip install django

3. Data Visualization
Matplotlib Used for creating static, animated, and interactive visualizations
in Python.
pip install matplotlib
Plotly A graphing library for creating interactive plots, particularly for
dashboards.
pip install plotly

4. Machine Learning
scikit-learn One of the most popular libraries for machine learning in
Python.
pip install scikit-learn
TensorFlow A powerful library for deep learning and neural networks.
pip install tensorflow

5. Automation and Web Scraping


Selenium Automates web browsers. Useful for testing and scraping.
pip install selenium

BeautifulSoup A library for parsing HTML and XML documents.


pip install beautifulsoup4

Appendix D

Project Ideas for Future Learning

Now that you've gained experience building applications, here are a few
project ideas to continue developing your skills and deepen your
understanding of Python and app development
1. Personal Finance Tracker
Create a personal finance tracking app where users can log their expenses,
categorize them, and view reports on spending trends.
2. Movie Recommendation System
Build a movie recommendation system using machine learning algorithms
that suggests movies based on user preferences.
3. Chatbot for Customer Service
Develop an AI-powered chatbot using Natural Language Processing (NLP)
libraries that can handle customer queries.
4. Task Manager with Kanban Board
Enhance your task manager by adding a Kanban board feature where users
can visually organize tasks into different stages (e.g., To Do, In Progress,
Done).
5. Social Media Dashboard
Create a dashboard that integrates with popular social media APIs like
Twitter or Instagram, allowing users to track their activity and post updates.
Appendix E Glossary of Python and App Development Terms
Understanding the terminology used in Python and app development is key
to mastering the language and becoming proficient in building real-world
applications. Below is a glossary of common terms.
1. API (Application Programming Interface)
A set of protocols that allow one software application to interact with
another. APIs are commonly used to fetch data from web services (e.g.,
weather data from OpenWeatherMap).
2. Debugging
The process of identifying and fixing errors (bugs) in the code. Debugging
helps to ensure that the code works as expected.
3. Framework
A framework is a collection of pre-written code that provides a structure for
building applications. For example, Flask and Django are frameworks for
building web applications in Python.
4. GUI (Graphical User Interface)
A user interface that allows users to interact with a program using visual
elements such as buttons, menus, and text fields. Tkinter is commonly used
for creating desktop GUI applications in Python.
5. IDE (Integrated Development Environment)
A software application that provides tools for writing and testing code, such
as a code editor, compiler, and debugger. Popular IDEs for Python include
PyCharm and Visual Studio Code.
6. ORM (Object-Relational Mapping)
A technique that allows developers to interact with databases using object-
oriented programming concepts instead of writing raw SQL queries.
SQLAlchemy is a popular ORM for Python.
7. REST API
A type of API that uses HTTP requests to perform CRUD (Create, Read,
Update, Delete) operations. REST APIs are stateless and commonly used in
web applications.
8. MVC (Model-View-Controller)
A design pattern used to separate concerns in software development. It
divides an application into three components the Model (data), the View
(user interface), and the Controller (logic).
9. Version Control
A system that tracks changes to files and allows multiple developers to
work on the same project simultaneously. Git is the most popular version
control system.
10. Virtual Environment
A tool to create isolated environments for Python projects, ensuring
dependencies for one project do not interfere with another. virtualenv is a
commonly used tool for creating virtual environments.
These appendices provide essential resources and further guidance as you
continue your Python journey. Whether you are revisiting concepts from
earlier chapters or exploring new ones, these appendices are designed to be
a quick reference and offer additional insights to help you grow as a Python
developer.
THE END

Common questions

Powered by AI

Bcrypt enhances security in applications by automatically salting passwords before hashing them, making it infeasible for attackers to perform hash lookups. This feature ensures that even if the hashed password is compromised, it cannot be easily reversed to the original password. Integrating bcrypt into a Flask-based login system strengthens overall security against common vulnerabilities like brute force attacks .

The Build-Measure-Learn feedback loop improves Python application development by providing a structured approach to iterative development. By building a minimum viable product (MVP), measuring its functionalities and user feedback, and learning from the results to enhance the application, developers can optimize code, fix bugs, and add features systematically. This methodology encourages continuous improvement and aligns with real-world software development practices .

The design of a command-line password manager contributes to secure data storage and retrieval by utilizing AES encryption to store passwords in an encrypted format, hiding passwords during input using secure methods like getpass, and parsing command-line arguments for operational commands with argparse. These design choices ensure that passwords are protected from unauthorized access and the encryption key is handled securely, preventing data breaches .

Project-based learning (PBL) enhances problem-solving abilities by immersing learners in practical challenges that mimic real-world scenarios, encouraging debugging, and critical thinking. In the context of Python programming, PBL not only involves learning the syntax but also applying it to solve real-world problems, which helps improve skills in algorithm design, code optimization, and dealing with edge cases .

Project-based learning is particularly effective for mastering Python because it engages learners in real-world problem-solving, leading to better retention and understanding. This method requires learners to apply theoretical knowledge immediately, fostering a deeper comprehension of practical applications as opposed to passive memorization that often lacks context and real-world relevance. Completing projects builds confidence and provides tangible outcomes like a portfolio, which is valuable for career development .

Potential extensions for the Email Reminder Bot include adding support for recurring tasks, integrating a GUI using Tkinter for broader usability, attaching files to emails, using a database like SQLite for task storage, and developing a web dashboard with Flask to track task status. These enhancements could improve user experience by providing more features and a more user-friendly interface .

Setting up a development environment with tools like Visual Studio Code or PyCharm prepares a beginner by providing a structured space to write, test, and debug Python code efficiently. These tools offer features like syntax highlighting, code completion, and integrated console support, which enhance the coding experience and help beginners understand the workflow of application development, from writing scripts to executing and debugging them .

Understanding the components of a real-time COVID-19 Tracker Dashboard enhances data visualization and API integration skills by teaching you to fetch real-time data from APIs, parse JSON data, and create interactive charts with libraries like Plotly or matplotlib. By building this project, you gain practical experience in transforming raw data into meaningful insights, improving your ability to visualize trends and make data-driven decisions .

Challenges in implementing a Python Email Reminder Bot include managing task scheduling, ensuring reliable email delivery, handling authentication for SMTP, and formatting emails appropriately. These challenges can be addressed by using Python modules like schedule for task management, smtplib for SMTP connections, and employing proper error handling and logging mechanisms to ensure reliability and traceability of email operations .

Using Python’s os and shutil modules in automating file handling tasks is beneficial because they provide robust support for accessing the file system, navigating directories, moving, and filtering files based on extensions. These modules simplify complex file operations and allow for efficient automation of tasks such as a file organizer, enhancing productivity by reducing manual file management efforts .

You might also like