Recommended Python Learning Path for Beginners to Advanced Developers

Python is one of the most popular programming languages in the world. It is simple to learn, powerful, and used in multiple industries including web development, automation, artificial intelligence, data science, cybersecurity, and cloud computing.

If you are confused about where to start learning Python or what topics to study next, this guide provides a complete recommended Python learning path from beginner to advanced level.


Why Learn Python?

Python is widely used because it offers:

  • Simple and readable syntax
  • Huge community support
  • Thousands of libraries
  • Cross-platform compatibility
  • Strong demand in jobs and freelancing

Python is used in:

  • Web Development
  • Data Science
  • Machine Learning
  • Automation
  • Cybersecurity
  • Cloud Computing
  • Artificial Intelligence

Beginner Level Python Learning Path

At the beginner stage, focus on understanding core Python concepts and writing basic programs.


1. Python Basics

Start with the fundamentals of Python.

Topics to Learn:

  • Variables
  • Data Types
  • Operators
  • Input and Output
  • Comments
  • Basic Syntax

Example:

name = "Aditya"
age = 25

print(name)
print(age)

Goal:

  • Understand how Python programs work
  • Learn syntax and basic coding logic

2. Control Flow Statements

Control flow helps programs make decisions and repeat tasks.

Topics to Learn:

  • if, elif, else
  • for loops
  • while loops
  • break and continue
  • range()

Example:

for i in range(5):
print(i)

Goal:

  • Learn program logic and decision making

3. Strings in Python

Strings are one of the most important data types.

Topics to Learn:

  • String indexing
  • String slicing
  • String methods
  • f-strings
  • String formatting

Example:

name = "Python"

print(name.upper())

Goal:

  • Learn text processing and formatting

4. Data Structures

Data structures store and organize data efficiently.

Topics to Learn:

  • Lists
  • Tuples
  • Sets
  • Dictionaries

Example:

students = ["Rahul", "Aman"]

print(students[0])

Goal:

  • Understand data storage and manipulation

5. Functions

Functions help organize reusable code.

Topics to Learn:

  • Defining functions
  • Function arguments
  • Return values
  • Lambda functions

Example:

def add(a, b):
return a + b

print(add(2, 3))

Goal:

  • Write modular and reusable code

6. File Handling

Learn how to work with files in Python.

Topics to Learn:

  • Reading files
  • Writing files
  • CSV handling
  • JSON handling

Example:

with open("data.txt", "w") as file:
file.write("Hello Python")

Goal:

  • Store and manage application data

Intermediate Level Python Learning Path

Once you are comfortable with basics, move toward structured programming and larger applications.


7. Object-Oriented Programming (OOP)

OOP is essential for professional Python development.

Topics to Learn:

  • Classes and objects
  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction

Example:

class Student:

def __init__(self, name):
self.name = name

student = Student("Aditya")

print(student.name)

Goal:

  • Build scalable and maintainable applications

8. Modules and Packages

Modules help organize Python code.

Topics to Learn:

  • Importing modules
  • Creating modules
  • pip
  • Virtual environments

Example:

import math

print(math.sqrt(25))

Goal:

  • Manage large projects efficiently

9. Exception Handling

Exception handling prevents program crashes.

Topics to Learn:

  • try
  • except
  • finally
  • Custom exceptions

Example:

try:
print(10 / 0)

except ZeroDivisionError:
print("Cannot divide by zero")

Goal:

  • Write reliable and stable applications

10. Advanced Python Concepts

Topics to Learn:

  • Iterators
  • Generators
  • Decorators
  • Context managers
  • List comprehensions

Example:

squares = [x*x for x in range(5)]

print(squares)

Goal:

  • Improve coding efficiency and performance

Advanced Level Python Learning Path

At the advanced stage, specialize in domains based on your career goals.


11. Web Development with Python

Python is widely used for backend development.

Frameworks:

  • Flask
  • Django

Topics to Learn:

  • Routing
  • Templates
  • APIs
  • Authentication
  • Database integration

Example Flask Route:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
return "Welcome"

app.run()

Goal:

  • Build websites and web applications

12. Data Science with Python

Python dominates the data science industry.

Libraries:

  • NumPy
  • Pandas
  • Matplotlib

Topics to Learn:

  • Data analysis
  • Data cleaning
  • Visualization
  • EDA

Goal:

  • Analyze and visualize data effectively

13. APIs and Networking

APIs allow applications to communicate.

Topics to Learn:

  • REST APIs
  • requests library
  • JSON handling
  • API authentication

Example:

import requests

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

print(response.status_code)

Goal:

  • Build and consume APIs

14. Automation and Scripting

Python is excellent for automation.

Topics to Learn:

  • Web scraping
  • Email automation
  • File automation
  • Scheduling scripts

Libraries:

  • BeautifulSoup
  • requests
  • schedule

Goal:

  • Automate repetitive tasks

15. Machine Learning with Python

Machine learning is one of Python’s strongest domains.

Libraries:

  • Scikit-learn
  • TensorFlow
  • PyTorch

Topics to Learn:

  • Regression
  • Classification
  • Clustering
  • Model evaluation

Goal:

  • Build intelligent predictive systems

16. Cloud & DevOps with Python

Python is heavily used in cloud automation and DevOps.

Topics to Learn:

  • AWS SDK (boto3)
  • Docker
  • CI/CD pipelines
  • Infrastructure automation

Goal:

  • Automate deployment and cloud infrastructure

Best Resources to Learn Python

Here are some of the best resources for learning Python online.


1. Python Official Documentation

Website:

https://docs.python.org

Best for:

  • Accurate reference
  • Official language documentation

2. W3Schools Python Tutorial

Website:

https://www.w3schools.com/python/

Best for:

  • Beginners
  • Quick examples

3. Real Python

Website:

https://realpython.com

Best for:

  • Practical tutorials
  • Advanced concepts

4. GeeksforGeeks Python

Website:

https://www.geeksforgeeks.org/python-programming-language/

Best for:

  • Interview preparation
  • Detailed explanations

5. Kaggle Learn Python

Website:

https://www.kaggle.com/learn/python

Best for:

  • Data science beginners
  • Hands-on exercises

Tips for Learning Python Faster

✅ Practice daily
✅ Build projects regularly
✅ Solve coding problems
✅ Read other people’s code
✅ Learn debugging techniques
✅ Use GitHub for projects
✅ Focus on practical applications


Suggested Beginner Projects

  • Calculator App
  • To-Do App
  • Weather App
  • Expense Tracker
  • File Organizer
  • Quiz Application

Suggested Advanced Projects

  • REST API
  • Chat Application
  • Machine Learning Model
  • Web Scraper
  • Data Dashboard
  • AI Chatbot

Final Thoughts

Python is one of the best programming languages for beginners and professionals alike. The key to mastering Python is consistency, project-building, and gradual progression from basics to advanced topics.

Follow this roadmap step by step:

Beginner → Intermediate → Advanced

and continue building real-world projects to strengthen your skills.

Whether your goal is:

  • Web Development
  • Data Science
  • Automation
  • Machine Learning
  • Cloud Computing

Python provides endless opportunities for growth and career development.

25. Final Projects in Python

Final projects help apply all Python concepts in real-world applications.

These projects improve:

  • Problem-solving skills
  • Coding experience
  • Portfolio quality
  • Practical understanding

Suggested Final Projects

  1. Calculator App
  2. To-Do Application
  3. Chat Application
  4. Web Scraper
  5. Data Dashboard
  6. Machine Learning Project
  7. REST API Project

1. Calculator App

A calculator performs arithmetic operations.

Concepts Used:

  • Variables
  • Functions
  • Conditions
  • GUI (optional)

Console Calculator

def add(a, b):
return a + b

def subtract(a, b):
return a - b

def multiply(a, b):
return a * b

def divide(a, b):

if b == 0:
return "Cannot divide by zero"

return a / b

print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Choose option: ")

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

if choice == "1":
print(add(num1, num2))

elif choice == "2":
print(subtract(num1, num2))

elif choice == "3":
print(multiply(num1, num2))

elif choice == "4":
print(divide(num1, num2))

else:
print("Invalid choice")

GUI Calculator (Tkinter)

import tkinter as tk

def calculate():

result = eval(entry.get())

label.config(text=result)

root = tk.Tk()

entry = tk.Entry(root)

entry.pack()

button = tk.Button(
root,
text="Calculate",
command=calculate
)

button.pack()

label = tk.Label(root)

label.pack()

root.mainloop()

2. To-Do Application

A to-do app manages tasks.

Features:

  • Add tasks
  • Delete tasks
  • Mark completed tasks

Simple To-Do App

tasks = []

while True:

print("\n1. Add Task")
print("2. View Tasks")
print("3. Exit")

choice = input("Choose: ")

if choice == "1":

task = input("Enter task: ")

tasks.append(task)

elif choice == "2":

for index, task in enumerate(tasks):

print(index + 1, task)

elif choice == "3":
break

3. Chat Application

A chat app allows communication between users.

Concepts Used:

  • Socket programming
  • Networking
  • Multithreading

Server Code

import socket

server = socket.socket()

server.bind(("localhost", 12345))

server.listen(1)

client, addr = server.accept()

while True:

message = client.recv(1024)

print("Client:", message.decode())

Client Code

import socket

client = socket.socket()

client.connect(("localhost", 12345))

while True:

message = input("You: ")

client.send(message.encode())

4. Web Scraper

Extracts information from websites.

Concepts Used:

  • Requests
  • BeautifulSoup
  • Automation

Example Web Scraper

import requests
from bs4 import BeautifulSoup

url = "https://example.com"

response = requests.get(url)

soup = BeautifulSoup(
response.text,
"html.parser"
)

print(soup.title.text)

Extract All Links

for link in soup.find_all("a"):

print(link.get("href"))

5. Data Dashboard

Displays charts and analytics.

Concepts Used:

  • Pandas
  • Matplotlib
  • Streamlit or Flask

Install Streamlit

pip install streamlit

Dashboard Example

import streamlit as st
import pandas as pd

data = {
"Month": ["Jan", "Feb", "Mar"],
"Sales": [100, 200, 150]
}

df = pd.DataFrame(data)

st.title("Sales Dashboard")

st.line_chart(df["Sales"])

Run app:

streamlit run app.py

6. Machine Learning Project

Build predictive systems using ML.

Examples:

  • House price prediction
  • Spam detection
  • Student score prediction

Student Score Prediction

from sklearn.linear_model import LinearRegression
import numpy as np

hours = np.array([
[1],
[2],
[3],
[4]
])

scores = np.array([
20,
40,
60,
80
])

model = LinearRegression()

model.fit(hours, scores)

prediction = model.predict([[5]])

print(prediction)

7. REST API Project

Create APIs using Flask.

Concepts Used:

  • Flask
  • JSON
  • CRUD operations

Simple Flask API

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/")

def home():
return "API Running"

@app.route("/users")

def users():

data = [
{"name": "Aditya"},
{"name": "Rahul"}
]

return jsonify(data)

app.run(debug=True)

Advanced REST API Example

from flask import Flask, request, jsonify

app = Flask(__name__)

students = []

@app.route("/students", methods=["POST"])
def add_student():

data = request.json

students.append(data)

return jsonify({
"message": "Student added"
})

@app.route("/students", methods=["GET"])
def get_students():

return jsonify(students)

app.run(debug=True)

Suggested Improvements

You can enhance projects by adding:

  • Database support
  • Authentication
  • GUI
  • Cloud deployment
  • Docker support

Project Folder Structure Example

project/

├── app.py
├── requirements.txt
├── templates/
├── static/
└── database.db

GitHub Portfolio Tips

Upload projects to GitHub with:

  • README.md
  • Screenshots
  • Requirements file
  • Proper documentation

Example requirements.txt

flask
requests
pandas
numpy
scikit-learn

Best Practices

✅ Write clean code
✅ Use virtual environments
✅ Add comments and documentation
✅ Handle errors properly
✅ Use Git for version control


Capstone Project Ideas

Advanced ideas:

  • AI chatbot
  • Expense tracker
  • Weather application
  • Face recognition system
  • E-commerce backend
  • Social media API

Summary

In this chapter you learned:

✅ Calculator project
✅ To-do application
✅ Chat application
✅ Web scraper
✅ Data dashboard
✅ Machine learning project
✅ REST API project

24. Performance Optimization in Python

Performance optimization improves:

  • Speed
  • Memory usage
  • Efficiency

Optimization is important for:

  • Large applications
  • Data processing
  • APIs
  • Machine learning
  • Automation scripts

Why Performance Optimization Matters

Benefits:

  • Faster execution
  • Lower memory consumption
  • Better scalability
  • Improved user experience

Performance Optimization Areas

Main areas:

  • Profiling
  • Memory optimization
  • Efficient coding practices

Profiling in Python

Profiling helps identify:

  • Slow functions
  • CPU usage
  • Performance bottlenecks

Using time Module

Simple way to measure execution time.

import time

start = time.time()

total = 0

for i in range(1000000):
total += i

end = time.time()

print("Execution Time:", end - start)

Using timeit

timeit measures small code snippets accurately.

import timeit

code = """
sum(range(1000))
"""

execution_time = timeit.timeit(
code,
number=1000
)

print(execution_time)

cProfile Module

cProfile is built-in profiler.


Example

import cProfile

def calculate():

total = 0

for i in range(100000):

total += i

return total

cProfile.run("calculate()")

Sample Output

function calls
ordered by cumulative time

Line Profiler

Used for line-by-line profiling.

Install:

pip install line_profiler

Example

@profile
def test():

total = 0

for i in range(10000):

total += i

return total

Run:

kernprof -l script.py
python -m line_profiler script.py.lprof

Memory Optimization

Memory optimization reduces RAM usage.

Important for:

  • Large datasets
  • Long-running applications
  • High-performance systems

Using sys.getsizeof

Check object memory size.

import sys

numbers = [1, 2, 3]

print(sys.getsizeof(numbers))

Generator vs List

Generators use less memory.


List Example

numbers = [x for x in range(1000000)]

Consumes large memory.


Generator Example

numbers = (x for x in range(1000000))

Consumes less memory.


Using Generators

def generate_numbers():

for i in range(5):
yield i

for num in generate_numbers():
print(num)

Delete Unused Variables

data = [1] * 1000000

del data

Use Appropriate Data Structures

Choose correct structure for performance.

StructureBest Use
ListOrdered data
SetFast lookup
TupleImmutable data
DictionaryKey-value storage

Fast Membership with Sets

numbers = {1, 2, 3, 4}

print(3 in numbers)

Efficient Coding Practices

Writing optimized code improves performance.


Avoid Repeated Computation


Bad Example

for i in range(1000):

result = sum(range(100))

Better Example

result = sum(range(100))

for i in range(1000):

print(result)

Use List Comprehensions

Faster than loops.


Traditional Loop

squares = []

for i in range(10):

squares.append(i * i)

List Comprehension

squares = [i * i for i in range(10)]

String Joining Optimization


Slow Method

text = ""

for word in ["Python", "is", "fast"]:

text += word

Faster Method

words = ["Python", "is", "fast"]

text = " ".join(words)

Use Built-in Functions

Built-in functions are optimized in C.

numbers = [1, 2, 3]

print(sum(numbers))
print(max(numbers))

Avoid Global Variables

Global variables are slower.


Better Example

def calculate():

local_var = 10

return local_var

Use enumerate

Cleaner and efficient iteration.

names = ["A", "B", "C"]

for index, name in enumerate(names):

print(index, name)

Use zip

Efficient iteration over multiple lists.

names = ["A", "B"]
scores = [90, 80]

for name, score in zip(names, scores):

print(name, score)

Memoization

Caches repeated computations.


Using lru_cache

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):

if n < 2:
return n

return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(30))

NumPy for Performance

NumPy operations are faster than Python loops.


Python Loop

numbers = [1, 2, 3]

result = []

for n in numbers:

result.append(n * 2)

NumPy Version

import numpy as np

arr = np.array([1, 2, 3])

print(arr * 2)

Multithreading and Multiprocessing

Use concurrency for faster execution.

  • Threads → I/O tasks
  • Processes → CPU tasks

Example Using Multiprocessing

from multiprocessing import Pool

def square(n):
return n * n

with Pool() as pool:

results = pool.map(
square,
[1, 2, 3, 4]
)

print(results)

Garbage Collection

Python automatically manages memory.


Manual Garbage Collection

import gc

gc.collect()

Practical Example

Compare List vs Generator Memory

import sys

list_data = [x for x in range(100000)]

gen_data = (x for x in range(100000))

print(
"List:",
sys.getsizeof(list_data)
)

print(
"Generator:",
sys.getsizeof(gen_data)
)

Optimization Best Practices

✅ Profile before optimizing
✅ Use generators for large data
✅ Avoid unnecessary loops
✅ Use built-in functions
✅ Use efficient data structures
✅ Cache repeated computations


Common Optimization Mistakes

❌ Premature optimization
❌ Ignoring readability
❌ Excessive memory allocation
❌ Using wrong data structures


Summary

In this chapter you learned:

✅ Profiling techniques
✅ Memory optimization
✅ Efficient coding practices
✅ Generators and caching
✅ Performance improvement methods

23. Python for Cloud & DevOps

Python is widely used in:

  • Cloud computing
  • DevOps automation
  • Infrastructure management
  • Deployment pipelines

Python helps automate:

  • Server tasks
  • Cloud services
  • CI/CD workflows
  • Container management

What is Cloud Computing?

Cloud computing provides:

  • Servers
  • Storage
  • Databases
  • Networking

over the internet.

Popular cloud providers:

  • AWS
  • Azure
  • Google Cloud

What is DevOps?

DevOps combines:

  • Development
  • Operations

to improve software delivery.

DevOps focuses on:

  • Automation
  • Continuous integration
  • Continuous deployment

AWS SDK for Python (boto3)

AWS SDK allows Python programs to interact with Amazon Web Services.

Using boto3, you can manage:

  • S3 buckets
  • EC2 servers
  • DynamoDB
  • Lambda functions

Install boto3

pip install boto3

Import boto3

import boto3

Configure AWS Credentials

Use command:

aws configure

Enter:

  • Access key
  • Secret key
  • Region

Create S3 Client

import boto3

s3 = boto3.client("s3")

List S3 Buckets

response = s3.list_buckets()

for bucket in response["Buckets"]:

print(bucket["Name"])

Upload File to S3

s3.upload_file(
"data.txt",
"my-bucket",
"data.txt"
)

print("File uploaded")

Download File from S3

s3.download_file(
"my-bucket",
"data.txt",
"downloaded.txt"
)

Create EC2 Resource

ec2 = boto3.resource("ec2")

List EC2 Instances

for instance in ec2.instances.all():

print(
instance.id,
instance.state["Name"]
)

Launch EC2 Instance

ec2.create_instances(
ImageId="ami-123456",
MinCount=1,
MaxCount=1,
InstanceType="t2.micro"
)

Docker with Python

Docker is used to package applications into containers.

Containers include:

  • Application code
  • Dependencies
  • Environment settings

Benefits of Docker

✅ Consistent environments
✅ Easy deployment
✅ Lightweight containers
✅ Faster development


Install Docker SDK for Python

pip install docker

Import Docker SDK

import docker

Connect to Docker

client = docker.from_env()

List Docker Containers

containers = client.containers.list()

for container in containers:

print(container.name)

Run Docker Container

client.containers.run(
"nginx",
detach=True
)

Stop Container

container = client.containers.get(
"container_id"
)

container.stop()

Dockerfile Example

A Dockerfile defines container instructions.

FROM python:3.11

WORKDIR /app

COPY . .

RUN pip install -r requirements.txt

CMD ["python", "app.py"]

Build Docker Image

docker build -t myapp .

Run Docker Container

docker run -p 5000:5000 myapp

CI/CD Basics

CI/CD stands for:

TermMeaning
CIContinuous Integration
CDContinuous Delivery/Deployment

Continuous Integration (CI)

CI automatically:

  • Builds code
  • Runs tests
  • Detects issues

whenever code changes.


Continuous Deployment (CD)

CD automatically deploys applications after successful testing.


CI/CD Workflow

Code → Build → Test → Deploy

Popular CI/CD Tools

  • GitHub Actions
  • Jenkins
  • GitLab CI/CD
  • CircleCI

GitHub Actions Example

.github/workflows/python.yml

name: Python CI

on:
push:
branches:
- main

jobs:

build:

runs-on: ubuntu-latest

steps:

- uses: actions/checkout@v3

- name: Setup Python
uses: actions/setup-python@v4

with:
python-version: 3.11

- name: Install dependencies
run: pip install -r requirements.txt

- name: Run tests
run: pytest

Jenkins Pipeline Example

pipeline {

agent any

stages {

stage('Build') {

steps {
sh 'pip install -r requirements.txt'
}
}

stage('Test') {

steps {
sh 'pytest'
}
}
}
}

Deploy Flask App with Docker

FROM python:3.11

WORKDIR /app

COPY . .

RUN pip install flask

CMD ["python", "app.py"]

Flask App Example

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
return "Cloud App Running"

app.run(host="0.0.0.0")

Infrastructure Automation

Python can automate:

  • Server provisioning
  • Monitoring
  • Deployment
  • Configuration management

Popular tools:

  • Ansible
  • Terraform
  • Kubernetes APIs

Example: Run Shell Command

import subprocess

result = subprocess.run(
["ls"],
capture_output=True,
text=True
)

print(result.stdout)

Monitoring Example

import psutil

cpu = psutil.cpu_percent()

memory = psutil.virtual_memory().percent

print("CPU:", cpu)

print("Memory:", memory)

Practical Example

Upload File to AWS S3

import boto3

s3 = boto3.client("s3")

file_name = "report.txt"

bucket = "my-bucket"

s3.upload_file(
file_name,
bucket,
file_name
)

print("Upload completed")

Advantages of Python in Cloud & DevOps

✅ Easy automation
✅ Strong cloud SDK support
✅ Fast scripting
✅ DevOps integration
✅ Infrastructure management


Best Practices

✅ Secure cloud credentials
✅ Use environment variables
✅ Automate testing
✅ Use containers for deployment
✅ Monitor infrastructure regularly


Summary

In this chapter you learned:

✅ AWS SDK with boto3
✅ Docker with Python
✅ Dockerfiles
✅ CI/CD basics
✅ GitHub Actions
✅ Infrastructure automation

22. GUI Development in Python

GUI (Graphical User Interface) development allows users to interact with applications using windows, buttons, menus, forms, and graphics instead of command-line text.


1. Introduction to GUI Programming

What is GUI?

GUI stands for Graphical User Interface.

Examples:

  • Calculator app
  • Text editor
  • Login form
  • Desktop software

Python provides several GUI libraries:

  • Tkinter (built-in)
  • PyQt
  • Kivy
  • wxPython

2. Tkinter Basics

What is Tkinter?

Tkinter is Python’s standard GUI library.

Features

  • Built into Python
  • Easy to learn
  • Cross-platform
  • Good for small/medium desktop apps

3. Creating First Tkinter Window

import tkinter as tk

root = tk.Tk()

root.title("My First App")
root.geometry("400x300")

root.mainloop()

Explanation

  • Tk() → creates main window
  • title() → window title
  • geometry() → window size
  • mainloop() → keeps window running

4. Tkinter Widgets

Widgets are GUI elements.

Common widgets:

  • Label
  • Button
  • Entry
  • Text
  • Checkbutton
  • Radiobutton
  • Listbox

5. Label Widget

import tkinter as tk

root = tk.Tk()

label = tk.Label(root, text="Hello Tkinter")
label.pack()

root.mainloop()

6. Button Widget

import tkinter as tk

def hello():
print("Button Clicked")

root = tk.Tk()

btn = tk.Button(root, text="Click Me", command=hello)
btn.pack()

root.mainloop()

7. Entry Widget

import tkinter as tk

def show():
print(entry.get())

root = tk.Tk()

entry = tk.Entry(root)
entry.pack()

btn = tk.Button(root, text="Submit", command=show)
btn.pack()

root.mainloop()

8. Text Widget

import tkinter as tk

root = tk.Tk()

text = tk.Text(root, height=5, width=30)
text.pack()

root.mainloop()

9. Geometry Managers

Used for arranging widgets.

pack()

label.pack()

grid()

label.grid(row=0, column=0)

place()

label.place(x=50, y=100)

10. Message Box

from tkinter import messagebox
import tkinter as tk

root = tk.Tk()

def show():
messagebox.showinfo("Info", "Welcome")

btn = tk.Button(root, text="Show", command=show)
btn.pack()

root.mainloop()

11. Frames in Tkinter

Frames group widgets together.

import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root)
frame.pack()

tk.Button(frame, text="Button 1").pack(side="left")
tk.Button(frame, text="Button 2").pack(side="left")

root.mainloop()

12. Event Handling in Tkinter

Events occur when user interacts with GUI.

Examples:

  • Mouse click
  • Keyboard press
  • Window close

13. Mouse Click Event

import tkinter as tk

def clicked(event):
print("Mouse Clicked")

root = tk.Tk()

label = tk.Label(root, text="Click Here")
label.pack()

label.bind("<Button-1>", clicked)

root.mainloop()

14. Keyboard Event

import tkinter as tk

def key_pressed(event):
print("Key:", event.char)

root = tk.Tk()

root.bind("<Key>", key_pressed)

root.mainloop()

15. Menu Bar

import tkinter as tk

root = tk.Tk()

menu = tk.Menu(root)
root.config(menu=menu)

file_menu = tk.Menu(menu)
menu.add_cascade(label="File", menu=file_menu)

file_menu.add_command(label="Open")
file_menu.add_command(label="Exit", command=root.quit)

root.mainloop()

16. Simple Calculator GUI

import tkinter as tk

def calculate():
result = int(num1.get()) + int(num2.get())
output.config(text=str(result))

root = tk.Tk()

num1 = tk.Entry(root)
num1.pack()

num2 = tk.Entry(root)
num2.pack()

btn = tk.Button(root, text="Add", command=calculate)
btn.pack()

output = tk.Label(root, text="")
output.pack()

root.mainloop()

17. Introduction to PyQt

What is PyQt?

PyQt is a powerful GUI framework based on Qt.

Advantages

  • Modern UI
  • Advanced widgets
  • Professional applications
  • Better design tools

Installation

pip install PyQt5

18. First PyQt Application

import sys
from PyQt5.QtWidgets import QApplication, QWidget

app = QApplication(sys.argv)

window = QWidget()
window.setWindowTitle("PyQt App")
window.resize(400, 300)

window.show()

sys.exit(app.exec_())

19. PyQt Widgets

Common widgets:

  • QLabel
  • QPushButton
  • QLineEdit
  • QTextEdit
  • QComboBox

20. Button in PyQt

import sys
from PyQt5.QtWidgets import QApplication, QPushButton

app = QApplication(sys.argv)

button = QPushButton("Click Me")
button.show()

sys.exit(app.exec_())

21. Event Handling in PyQt

import sys
from PyQt5.QtWidgets import QApplication, QPushButton

def clicked():
print("Button clicked")

app = QApplication(sys.argv)

button = QPushButton("Click")
button.clicked.connect(clicked)

button.show()

sys.exit(app.exec_())

22. Layouts in PyQt

Layouts manage widget positions.

Types:

  • QVBoxLayout
  • QHBoxLayout
  • QGridLayout

Example:

import sys
from PyQt5.QtWidgets import (
QApplication,
QWidget,
QVBoxLayout,
QPushButton
)

app = QApplication(sys.argv)

window = QWidget()

layout = QVBoxLayout()

layout.addWidget(QPushButton("Button 1"))
layout.addWidget(QPushButton("Button 2"))

window.setLayout(layout)

window.show()

sys.exit(app.exec_())

23. Tkinter vs PyQt

FeatureTkinterPyQt
Built-inYesNo
Easy to LearnYesMedium
Modern UIBasicExcellent
PerformanceGoodVery Good
Best ForBeginnersProfessional Apps

24. Mini Projects for Practice

Beginner

  • Calculator
  • Login form
  • To-do app
  • Unit converter

Intermediate

  • Text editor
  • Music player
  • Chat application
  • Image viewer

Advanced

  • IDE/editor
  • Billing software
  • Inventory system

25. Best Practices

  • Separate GUI and logic
  • Use functions/classes
  • Validate user input
  • Keep UI simple
  • Use layouts properly

26. Summary

In this chapter you learned:

  • GUI fundamentals
  • Tkinter basics
  • Widgets and layouts
  • Event handling
  • PyQt basics
  • Building desktop applications

21. Cybersecurity & Ethical Hacking with Python

Cybersecurity protects systems, networks, and data from attacks.

Ethical hacking involves legally testing systems for security weaknesses.

Python is widely used in cybersecurity because it is:

  • Easy to learn
  • Powerful
  • Rich in networking libraries
  • Excellent for automation

Important Note

Ethical hacking should only be performed:

  • On systems you own
  • With proper authorization

Unauthorized hacking is illegal.


Python in Cybersecurity

Python is used for:

  • Network scanning
  • Packet analysis
  • Password auditing
  • Automation tools
  • Security testing

Popular libraries:

  • socket
  • scapy
  • cryptography
  • requests

Network Scanning

Network scanning identifies:

  • Active devices
  • Open ports
  • Running services

Using socket

Python provides:

socket

module for network communication.


Simple Port Scanner

import socket

target = "127.0.0.1"

for port in range(1, 101):

sock = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
)

result = sock.connect_ex(
(target, port)
)

if result == 0:
print(f"Port {port} is open")

sock.close()

Scan Specific Port

import socket

host = "google.com"
port = 80

sock = socket.socket()

result = sock.connect_ex(
(host, port)
)

if result == 0:
print("Port open")
else:
print("Port closed")

sock.close()

Banner Grabbing

Used to identify running services.

import socket

sock = socket.socket()

sock.connect(("example.com", 80))

sock.send(b"HEAD / HTTP/1.1\r\n\r\n")

banner = sock.recv(1024)

print(banner.decode())

sock.close()

Packet Sniffing

Packet sniffing captures network packets.

Used for:

  • Traffic analysis
  • Security monitoring
  • Network debugging

Scapy Library

Install:

pip install scapy

Capture Packets

from scapy.all import sniff

def packet_callback(packet):
print(packet.summary())

sniff(count=5, prn=packet_callback)

Filter TCP Packets

from scapy.all import sniff

sniff(
filter="tcp",
count=10,
prn=lambda p: p.summary()
)

View Packet Details

from scapy.all import sniff

packet = sniff(count=1)[0]

packet.show()

Cryptography Basics

Cryptography secures data using encryption.

Main concepts:

  • Encryption
  • Decryption
  • Hashing

Symmetric Encryption

Same key used for:

  • Encryption
  • Decryption

Install Cryptography Library

pip install cryptography

Generate Encryption Key

from cryptography.fernet import Fernet

key = Fernet.generate_key()

print(key)

Encrypt Data

from cryptography.fernet import Fernet

key = Fernet.generate_key()

cipher = Fernet(key)

message = b"Python Security"

encrypted = cipher.encrypt(message)

print(encrypted)

Decrypt Data

decrypted = cipher.decrypt(encrypted)

print(decrypted.decode())

Hashing

Hashing converts data into fixed-length output.

Used for:

  • Password storage
  • Integrity verification

SHA256 Hash Example

import hashlib

text = "password123"

hash_value = hashlib.sha256(
text.encode()
).hexdigest()

print(hash_value)

Password Checker Example

import hashlib

password = input("Enter password: ")

hashed = hashlib.sha256(
password.encode()
).hexdigest()

print("Hash:", hashed)

Automation Tools

Python can automate security-related tasks.

Examples:

  • Log monitoring
  • File scanning
  • Vulnerability checks

File Integrity Checker

import hashlib

def calculate_hash(filename):

sha256 = hashlib.sha256()

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

while chunk := file.read(4096):

sha256.update(chunk)

return sha256.hexdigest()

print(calculate_hash("data.txt"))

Automated Website Status Checker

import requests

websites = [
"https://google.com",
"https://github.com"
]

for site in websites:

try:

response = requests.get(site)

print(
site,
response.status_code
)

except Exception as e:

print(site, "Error")

Simple Keylogger Warning

Keyloggers capture keyboard input and can be illegal or harmful.

They should only be studied in controlled ethical environments.


Network Monitoring Tool

import psutil

network = psutil.net_io_counters()

print("Bytes Sent:", network.bytes_sent)

print("Bytes Received:", network.bytes_recv)

WHOIS Lookup Example

import socket

domain = "example.com"

ip = socket.gethostbyname(domain)

print("IP Address:", ip)

Practical Example

Simple Network Scanner

import socket

target = input("Enter IP: ")

start_port = 1
end_port = 100

for port in range(
start_port,
end_port + 1
):

sock = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
)

sock.settimeout(0.5)

result = sock.connect_ex(
(target, port)
)

if result == 0:
print(f"Port {port} open")

sock.close()

Advantages of Python in Cybersecurity

✅ Easy scripting
✅ Strong networking support
✅ Excellent automation
✅ Large security libraries
✅ Fast development


Best Practices

✅ Always get permission before testing
✅ Use ethical hacking responsibly
✅ Keep tools updated
✅ Secure sensitive data
✅ Avoid illegal activities


Summary

In this chapter you learned:

✅ Network scanning
✅ Packet sniffing
✅ Cryptography basics
✅ Hashing and encryption
✅ Automation tools in cybersecurity

20. Multithreading and Multiprocessing

Multithreading and multiprocessing help Python programs perform multiple tasks simultaneously.

Used for:

  • Faster execution
  • Background tasks
  • Parallel processing
  • Network applications

Concurrency vs Parallelism

ConceptMeaning
ConcurrencyMultiple tasks progress together
ParallelismMultiple tasks run at same time

What is a Thread?

A thread is a lightweight unit of execution inside a process.

Threads share:

  • Memory
  • Resources

Useful for:

  • I/O operations
  • File handling
  • Network requests

Multithreading in Python

Python provides:

threading

module.


Creating a Thread

import threading

def task():
print("Thread running")

thread = threading.Thread(target=task)

thread.start()

thread.join()

print("Main program finished")

Multiple Threads Example

import threading

def print_numbers():

for i in range(5):
print("Number:", i)

def print_letters():

for letter in "ABCDE":
print("Letter:", letter)

t1 = threading.Thread(
target=print_numbers
)

t2 = threading.Thread(
target=print_letters
)

t1.start()
t2.start()

t1.join()
t2.join()

Thread with Arguments

import threading

def greet(name):
print("Hello", name)

thread = threading.Thread(
target=greet,
args=("Aditya",)
)

thread.start()

Thread Benefits

✅ Faster I/O operations
✅ Background execution
✅ Improved responsiveness


What is a Process?

A process is an independent program execution unit.

Each process has:

  • Separate memory
  • Separate resources

Useful for:

  • CPU-intensive tasks
  • Heavy computations

Multiprocessing in Python

Python provides:

multiprocessing

module.


Creating a Process

from multiprocessing import Process

def task():
print("Process running")

process = Process(target=task)

process.start()

process.join()

Multiple Processes Example

from multiprocessing import Process

def square():
for i in range(5):
print(i * i)

def cube():
for i in range(5):
print(i * i * i)

p1 = Process(target=square)
p2 = Process(target=cube)

p1.start()
p2.start()

p1.join()
p2.join()

Thread vs Process

FeatureThreadProcess
MemorySharedSeparate
SpeedFasterSlower
Best ForI/O tasksCPU tasks
CommunicationEasierMore complex

Synchronization

Synchronization prevents conflicts when multiple threads access shared data.


Race Condition

Occurs when threads modify shared resource simultaneously.


Example Problem

counter = 0

Multiple threads updating this variable can create incorrect results.


Lock in Python

Use:

Lock

to synchronize threads.


Example Using Lock

import threading

counter = 0

lock = threading.Lock()

def increment():

global counter

for _ in range(1000):

lock.acquire()

counter += 1

lock.release()

threads = []

for i in range(5):

thread = threading.Thread(
target=increment
)

threads.append(thread)

thread.start()

for thread in threads:
thread.join()

print(counter)

Using with Lock

Cleaner approach.

import threading

lock = threading.Lock()

with lock:
print("Critical section")

Semaphore

Controls access to limited resources.

import threading

semaphore = threading.Semaphore(2)

Async Programming (asyncio)

Async programming allows non-blocking execution.

Useful for:

  • APIs
  • Web servers
  • Network applications

Python provides:

asyncio

module.


Basic Async Function

import asyncio

async def hello():

print("Hello")

asyncio.run(hello())

Async with await

import asyncio

async def task():

print("Task started")

await asyncio.sleep(2)

print("Task completed")

asyncio.run(task())

Running Multiple Async Tasks

import asyncio

async def task1():

await asyncio.sleep(1)

print("Task 1 done")

async def task2():

await asyncio.sleep(2)

print("Task 2 done")

async def main():

await asyncio.gather(
task1(),
task2()
)

asyncio.run(main())

Async vs Threading

FeatureAsyncioThreading
Best ForAsync I/OConcurrent tasks
Uses ThreadsNoYes
Memory UsageLowerHigher

Thread Pool

Python provides thread pools for managing threads efficiently.


Example: ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor

def square(n):
return n * n

with ThreadPoolExecutor() as executor:

results = executor.map(
square,
[1, 2, 3, 4]
)

print(list(results))

Process Pool

from concurrent.futures import ProcessPoolExecutor

def cube(n):
return n * n * n

with ProcessPoolExecutor() as executor:

results = executor.map(
cube,
[1, 2, 3]
)

print(list(results))

Practical Example

Download Multiple URLs Concurrently

import threading
import requests

urls = [
"https://example.com",
"https://example.org"
]

def download(url):

response = requests.get(url)

print(
url,
response.status_code
)

threads = []

for url in urls:

thread = threading.Thread(
target=download,
args=(url,)
)

threads.append(thread)

thread.start()

for thread in threads:
thread.join()

Advantages of Multithreading and Multiprocessing

✅ Faster execution
✅ Better CPU utilization
✅ Improved responsiveness
✅ Handles multiple tasks efficiently


Best Practices

✅ Use threads for I/O tasks
✅ Use processes for CPU tasks
✅ Synchronize shared resources
✅ Avoid unnecessary threads
✅ Use async for network applications


Summary

In this chapter you learned:

✅ Threads
✅ Processes
✅ Synchronization
✅ Locks and semaphores
✅ Async programming with asyncio
✅ Thread pools and process pools

19. Testing in Python

Testing ensures that Python programs work correctly and reliably.

Benefits of testing:

  • Finds bugs early
  • Improves code quality
  • Makes maintenance easier
  • Prevents unexpected errors

Types of Testing

TypePurpose
Unit TestingTest individual functions/modules
Integration TestingTest combined components
Functional TestingTest application behavior
System TestingTest entire application

Unit Testing

Unit testing checks small units of code such as:

  • Functions
  • Methods
  • Classes

Python provides:

unittest

module for unit testing.


Example Function

def add(a, b):
return a + b

Writing Unit Test

import unittest

def add(a, b):
return a + b

class TestMath(unittest.TestCase):

def test_add(self):
self.assertEqual(add(2, 3), 5)

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

Running Tests

Save file as:

test_math.py

Run:

python test_math.py

Common Assertion Methods

MethodPurpose
assertEqual(a, b)Check equality
assertNotEqual(a, b)Check inequality
assertTrue(x)Check true
assertFalse(x)Check false
assertIsNone(x)Check None
assertIn(a, b)Check membership

Example: Multiple Tests

import unittest

class TestString(unittest.TestCase):

def test_upper(self):
self.assertEqual(
"python".upper(),
"PYTHON"
)

def test_isdigit(self):
self.assertFalse("abc".isdigit())

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

Setup and Teardown Methods

Used for preparing and cleaning test environment.


Example

import unittest

class TestExample(unittest.TestCase):

def setUp(self):
print("Setup executed")

def tearDown(self):
print("Teardown executed")

def test_sample(self):
self.assertEqual(1 + 1, 2)

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

pytest

pytest is a powerful third-party testing framework.

Advantages:

  • Simpler syntax
  • Better output
  • Easy fixtures

Install pytest

pip install pytest

Simple pytest Example

def add(a, b):
return a + b

def test_add():
assert add(2, 3) == 5

Run pytest

pytest

Multiple pytest Tests

def multiply(a, b):
return a * b

def test_multiply():
assert multiply(2, 4) == 8

def test_negative():
assert multiply(-1, 5) == -5

pytest Fixtures

Fixtures provide reusable test setup.

import pytest

@pytest.fixture
def sample_data():
return [1, 2, 3]

def test_length(sample_data):
assert len(sample_data) == 3

Mocking in Python

Mocking replaces real objects with fake objects during testing.

Useful when testing:

  • APIs
  • Databases
  • External services

Python provides:

unittest.mock

Example Function

import requests

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

return response.status_code

Mocking API Request

from unittest.mock import patch
import unittest

class TestAPI(unittest.TestCase):

@patch("requests.get")
def test_get_data(self, mock_get):

mock_get.return_value.status_code = 200

import requests

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

self.assertEqual(
response.status_code,
200
)

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

Mock Object Example

from unittest.mock import Mock

database = Mock()

database.get_user.return_value = {
"name": "Aditya"
}

print(database.get_user())

Debugging Techniques

Debugging helps identify and fix errors.


Using print()

Simplest debugging method.

x = 10

print("Value of x:", x)

Using pdb Debugger

Python provides built-in debugger:

pdb

Example

import pdb

x = 10
y = 0

pdb.set_trace()

print(x / y)

Common pdb Commands

CommandPurpose
nNext line
cContinue
qQuit
p variablePrint variable

Exception Traceback

Python displays traceback for errors.

def divide(a, b):
return a / b

print(divide(10, 0))

Output:

ZeroDivisionError

Logging for Debugging

Use logging instead of many print statements.


Example

import logging

logging.basicConfig(level=logging.INFO)

logging.info("Program started")

logging.warning("Warning message")

logging.error("Error occurred")

Debugging with VS Code

VS Code provides:

  • Breakpoints
  • Variable inspection
  • Step execution

Steps:

  1. Open Python file
  2. Click beside line number
  3. Press F5
  4. Start debugging

Test Coverage

Coverage measures how much code is tested.

Install coverage:

pip install coverage

Run coverage:

coverage run test_math.py
coverage report

Practical Example

Calculator Testing

import unittest

def divide(a, b):
return a / b

class TestCalculator(unittest.TestCase):

def test_divide(self):
self.assertEqual(
divide(10, 2),
5
)

def test_zero_division(self):

with self.assertRaises(
ZeroDivisionError
):

divide(10, 0)

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

Best Practices

✅ Write small test cases
✅ Test edge cases
✅ Use mocking for external services
✅ Use logging for debugging
✅ Automate tests regularly


Summary

In this chapter you learned:

✅ Unit testing
unittest module
pytest basics
✅ Mocking
✅ Debugging techniques

18. APIs and Networking

APIs and networking allow applications to:

  • Communicate with each other
  • Exchange data
  • Connect over networks

Python provides powerful libraries for:

  • REST APIs
  • HTTP requests
  • JSON handling
  • Authentication
  • Socket programming

What is an API?

API stands for:

Application Programming Interface

An API allows software applications to communicate.

Examples:

  • Weather apps
  • Payment gateways
  • Social media integrations

REST APIs

REST stands for:

Representational State Transfer

REST APIs use HTTP methods:

MethodPurpose
GETRetrieve data
POSTCreate data
PUTUpdate data
DELETERemove data

Example API URL

https://api.example.com/users

Using requests Library

The requests library is used to send HTTP requests.


Install Requests

pip install requests

Import Requests

import requests

GET Request

Used to fetch data.

import requests

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

print(response.status_code)
print(response.text)

Response Status Codes

CodeMeaning
200Success
404Not found
500Server error
401Unauthorized

JSON Response

Most APIs return JSON data.

data = response.json()

print(data)

POST Request

Used to send data.

import requests

data = {
"name": "Aditya",
"course": "Python"
}

response = requests.post(
"https://httpbin.org/post",
json=data
)

print(response.json())

PUT Request

Used to update data.

data = {
"name": "Updated Name"
}

response = requests.put(
"https://httpbin.org/put",
json=data
)

print(response.status_code)

DELETE Request

Used to remove data.

response = requests.delete(
"https://httpbin.org/delete"
)

print(response.status_code)

Request Headers

Headers provide additional information.

headers = {
"User-Agent": "Python App"
}

response = requests.get(
"https://api.github.com",
headers=headers
)

Query Parameters

params = {
"page": 1,
"limit": 5
}

response = requests.get(
"https://httpbin.org/get",
params=params
)

print(response.url)

JSON Handling

JSON stands for:

JavaScript Object Notation

Used for storing and exchanging data.


Python Dictionary to JSON

import json

data = {
"name": "Aditya",
"age": 25
}

json_data = json.dumps(data)

print(json_data)

JSON to Python Dictionary

import json

text = '{"name":"Aditya"}'

data = json.loads(text)

print(data)

Read JSON File

import json

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

data = json.load(file)

print(data)

Write JSON File

import json

data = {
"course": "Python"
}

with open("data.json", "w") as file:

json.dump(data, file, indent=4)

API Authentication

Many APIs require authentication for security.

Common authentication methods:

  • API Keys
  • Tokens
  • OAuth

API Key Authentication

headers = {
"Authorization": "Bearer YOUR_API_KEY"
}

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

Token Authentication Example

token = "your_token"

headers = {
"Authorization": f"Bearer {token}"
}

response = requests.get(
"https://api.example.com/profile",
headers=headers
)

Basic Authentication

from requests.auth import HTTPBasicAuth

response = requests.get(
"https://api.example.com",
auth=HTTPBasicAuth(
"username",
"password"
)
)

Handling API Errors

import requests

try:

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

response.raise_for_status()

print(response.json())

except requests.exceptions.RequestException as e:
print("Error:", e)

Socket Programming Basics

Socket programming enables communication between devices over a network.

Used for:

  • Chat applications
  • Multiplayer games
  • Real-time systems

Python provides:

socket

module.


Import Socket Module

import socket

Socket Server Example

import socket

server = socket.socket()

server.bind(("localhost", 12345))

server.listen(1)

print("Waiting for connection...")

client, address = server.accept()

print("Connected:", address)

client.send(
"Hello Client".encode()
)

client.close()

Socket Client Example

import socket

client = socket.socket()

client.connect(("localhost", 12345))

message = client.recv(1024)

print(message.decode())

client.close()

UDP Socket Example

import socket

sock = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)

sock.sendto(
b"Hello",
("localhost", 12345)
)

Practical Example

Weather API Example

import requests

url = "https://api.openweathermap.org/data/2.5/weather"

params = {
"q": "Delhi",
"appid": "YOUR_API_KEY"
}

response = requests.get(
url,
params=params
)

data = response.json()

print(data)

Advantages of APIs

✅ Easy data exchange
✅ Connect multiple applications
✅ Automation support
✅ Real-time communication
✅ Scalable integration


Best Practices

✅ Secure API keys
✅ Handle API errors properly
✅ Use HTTPS APIs
✅ Validate JSON responses
✅ Avoid excessive API requests


Summary

In this chapter you learned:

✅ REST APIs
✅ Using requests
✅ JSON handling
✅ API authentication
✅ Socket programming basics

17. Automation and Scripting in Python

Automation means using programs to perform repetitive tasks automatically.

Python is widely used for automation because it is:

  • Simple
  • Powerful
  • Cross-platform

Automation can save:

  • Time
  • Effort
  • Manual work

Common Automation Tasks

Python can automate:

  • File handling
  • Web scraping
  • Email sending
  • Data entry
  • System tasks
  • Scheduled jobs

Automating Tasks

Python scripts can perform repetitive operations automatically.


Example: Automatic File Creation

with open("notes.txt", "w") as file:
file.write("Python Automation")

Example: Rename Multiple Files

import os

files = os.listdir()

for index, file in enumerate(files):

if file.endswith(".txt"):

new_name = f"file_{index}.txt"

os.rename(file, new_name)

print("Files renamed")

Example: Folder Creation

import os

for i in range(1, 6):

folder_name = f"Folder_{i}"

os.mkdir(folder_name)

print("Folders created")

Web Scraping

Web scraping extracts data from websites.

Popular libraries:

  • Requests
  • BeautifulSoup

Install Libraries

pip install requests beautifulsoup4

Send HTTP Request

import requests

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

print(response.status_code)

Parse HTML with BeautifulSoup

from bs4 import BeautifulSoup

html = """
<html>
<h1>Python</h1>
</html>
"""

soup = BeautifulSoup(html, "html.parser")

print(soup.h1.text)

Output:

Python

Extract All Links

from bs4 import BeautifulSoup

html = """
<a href='https://google.com'>Google</a>
<a href='https://github.com'>GitHub</a>
"""

soup = BeautifulSoup(html, "html.parser")

for link in soup.find_all("a"):
print(link.get("href"))

Scrape Website Title

import requests
from bs4 import BeautifulSoup

url = "https://example.com"

response = requests.get(url)

soup = BeautifulSoup(
response.text,
"html.parser"
)

print(soup.title.text)

Email Automation

Python can send emails automatically.

Uses:

  • Notifications
  • Reports
  • OTP emails
  • Bulk emails

Using smtplib

import smtplib

Send Simple Email

import smtplib

server = smtplib.SMTP(
"smtp.gmail.com",
587
)

server.starttls()

server.login(
"your_email@gmail.com",
"your_password"
)

message = "Hello from Python"

server.sendmail(
"your_email@gmail.com",
"receiver@gmail.com",
message
)

server.quit()

print("Email sent")

Email with Subject

from email.message import EmailMessage
import smtplib

msg = EmailMessage()

msg["Subject"] = "Python Email"

msg["From"] = "your_email@gmail.com"

msg["To"] = "receiver@gmail.com"

msg.set_content("Hello from Python")

server = smtplib.SMTP(
"smtp.gmail.com",
587
)

server.starttls()

server.login(
"your_email@gmail.com",
"password"
)

server.send_message(msg)

server.quit()

File Automation

Python can automate file operations such as:

  • Copying files
  • Moving files
  • Deleting files
  • Organizing folders

Copy File

import shutil

shutil.copy(
"source.txt",
"destination.txt"
)

Move File

import shutil

shutil.move(
"source.txt",
"new_folder/source.txt"
)

Delete File

import os

os.remove("data.txt")

Organize Files by Extension

import os
import shutil

files = os.listdir()

for file in files:

if file.endswith(".jpg"):

if not os.path.exists("Images"):
os.mkdir("Images")

shutil.move(file, f"Images/{file}")

Scheduling Scripts

Scheduling allows scripts to run automatically at specific times.


Using schedule Library


Install Schedule

pip install schedule

Example Scheduler

import schedule
import time

def task():
print("Task executed")

schedule.every(5).seconds.do(task)

while True:

schedule.run_pending()

time.sleep(1)

Run Daily Task

schedule.every().day.at("10:00").do(task)

System Scheduler

You can also use:

  • Windows Task Scheduler
  • Linux Cron Jobs

Cron Job Example (Linux)

0 10 * * * python3 script.py

Runs script daily at 10:00 AM.


Windows Task Scheduler

Steps:

  1. Open Task Scheduler
  2. Create Basic Task
  3. Select Python script
  4. Set schedule time

Practical Example

Automatic Backup Script

import shutil
import datetime

source = "data.txt"

date = datetime.datetime.now().strftime(
"%Y%m%d_%H%M%S"
)

backup = f"backup_{date}.txt"

shutil.copy(source, backup)

print("Backup created:", backup)

Advantages of Automation

✅ Saves time
✅ Reduces manual work
✅ Improves productivity
✅ Reduces errors
✅ Handles repetitive tasks efficiently


Best Practices

✅ Handle exceptions properly
✅ Avoid hardcoded passwords
✅ Use logging for scripts
✅ Schedule scripts carefully
✅ Respect website scraping policies


Summary

In this chapter you learned:

✅ Automating tasks
✅ Web scraping
✅ Email automation
✅ File automation
✅ Scheduling scripts