Python coding
Web_Scraping_BeautifulSoup_Guide.pdf
Basic Python Course
Web Scraping: BeautifulSoup & Requests
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Introduction to Web Scraping
Web scraping is the process of automatically extracting data from websites.
Instead of copying and pasting information manually, Python can read a webpage's HTML and extract specific data automatically. 0
---
Why Learn Web Scraping?
Web scraping is useful for:
- Data Collection
- Market Research
- Price Monitoring
- AI Dataset Creation
- News Aggregation
- Business Intelligence
---
Required Libraries
Install the required libraries:
These libraries help us:
- Download webpage content
- Analyze HTML structure
- Extract useful information
---
2. Fetching Web Content with Requests
The first step is sending a GET request to a website.
This allows Python to download the webpage source code. 1
---
Example
---
Understanding Status Codes
Common status codes:
---
3. Parsing HTML with BeautifulSoup
After downloading a webpage, BeautifulSoup converts HTML into a searchable structure. 2
---
Example
This extracts the webpage title. 3
---
What is HTML?
HTML (HyperText Markup Language) is the language used to build web pages.
Example:
BeautifulSoup helps navigate this structure.
---
4. Finding Elements
Web pages contain different HTML tags.
Examples:
BeautifulSoup can search for these elements. 4
---
Finding All Paragraphs
---
Finding All Links
5
---
5. Scraping Tables
Many websites store data inside tables.
This is useful for:
- Product lists
- Student records
- Statistics
- Financial reports
---
Example
This finds:
- Table element
- All rows inside the table
6
---
Extracting Table Data
7
---
How It Works
Finds table rows.
---
Finds table cells.
---
Removes extra spaces.
---
6. Robust Scraping with Exception Handling
Sometimes:
- Websites are offline
- Internet connections fail
- Servers respond slowly
Exception handling prevents your program from crashing. 8
---
Example
9
---
Why Exception Handling Matters
Without exception handling:
With exception handling:
---
Real-World Applications
- AI Dataset Collection
- Stock Market Monitoring
- E-commerce Price Tracking
- News Collection
- Social Media Analysis
- Business Research
---
Practice Exercises
1. Page Title Extractor
Write a program that visits a website and prints its title.
---
2. Link Collector
Write a scraper that collects all hyperlinks from a webpage.
---
3. Table Extractor
Find an HTML table and print every row as a Python list.
---
4. Safe Scraper
Modify your scraper using
Web Scraping: BeautifulSoup & Requests
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Introduction to Web Scraping
Web scraping is the process of automatically extracting data from websites.
Instead of copying and pasting information manually, Python can read a webpage's HTML and extract specific data automatically. 0
---
Why Learn Web Scraping?
Web scraping is useful for:
- Data Collection
- Market Research
- Price Monitoring
- AI Dataset Creation
- News Aggregation
- Business Intelligence
---
Required Libraries
Install the required libraries:
pip install beautifulsoup4 requests
These libraries help us:
- Download webpage content
- Analyze HTML structure
- Extract useful information
---
2. Fetching Web Content with Requests
The first step is sending a GET request to a website.
This allows Python to download the webpage source code. 1
---
Example
import requests
url = "https://example.com"
response = requests.get(url)
print(response.status_code)
---
Understanding Status Codes
Common status codes:
200 → Success
404 → Page Not Found
500 → Server Error
403 → Access Forbidden
---
3. Parsing HTML with BeautifulSoup
After downloading a webpage, BeautifulSoup converts HTML into a searchable structure. 2
---
Example
from bs4 import BeautifulSoup
soup = BeautifulSoup(
response.content,
"html.parser"
)
print(soup.title.string)
This extracts the webpage title. 3
---
What is HTML?
HTML (HyperText Markup Language) is the language used to build web pages.
Example:
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
BeautifulSoup helps navigate this structure.
---
4. Finding Elements
Web pages contain different HTML tags.
Examples:
<p>Paragraph</p>
<a href="https://example.com">
Link
</a>
BeautifulSoup can search for these elements. 4
---
Finding All Paragraphs
paragraphs = soup.find_all('p')
for p in paragraphs:
print(p.get_text())---
Finding All Links
links = soup.find_all('a')
for link in links:
print(link.get('href'))5
---
5. Scraping Tables
Many websites store data inside tables.
This is useful for:
- Product lists
- Student records
- Statistics
- Financial reports
---
Example
table = soup.find('table')
rows = table.find_all('tr')This finds:
- Table element
- All rows inside the table
6
---
Extracting Table Data
for row in rows:
cols = row.find_all('td')
data = [
ele.text.strip()
for ele in cols
]
print(data)
7
---
How It Works
find_all('tr')Finds table rows.
---
find_all('td')Finds table cells.
---
text.strip()
Removes extra spaces.
---
6. Robust Scraping with Exception Handling
Sometimes:
- Websites are offline
- Internet connections fail
- Servers respond slowly
Exception handling prevents your program from crashing. 8
---
Example
try:
response = requests.get(
url,
timeout=10
)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
9
---
Why Exception Handling Matters
Without exception handling:
Program crashes
With exception handling:
Program continues safely
---
Real-World Applications
- AI Dataset Collection
- Stock Market Monitoring
- E-commerce Price Tracking
- News Collection
- Social Media Analysis
- Business Research
---
Practice Exercises
1. Page Title Extractor
Write a program that visits a website and prints its title.
---
2. Link Collector
Write a scraper that collects all hyperlinks from a webpage.
---
3. Table Extractor
Find an HTML table and print every row as a Python list.
---
4. Safe Scraper
Modify your scraper using
try-except so it handles connection failures without crashing.
Python coding
Python_API_Interaction_Guide.pdf
Basic Python Course
Interacting with APIs
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. What is an API?
API stands for Application Programming Interface.
An API is a set of rules that allows one software application to communicate with another.
In Python, APIs are commonly used to:
- Connect to AI models
- Access weather data
- Retrieve map information
- Access social media platforms
- Work with cloud services
---
Real-World Example
When you use a weather app:
The API acts as the messenger between the application and the server.
---
RESTful APIs
Most modern APIs use REST (Representational State Transfer).
REST APIs communicate using standard HTTP methods.
---
2. HTTP Methods
The most common HTTP methods are:
---
Example Scenario
---
3. Making Requests in Python
Python commonly uses the
---
Import Requests
---
Example
This sends a GET request to the API.
---
Checking the Response
Example Output:
---
4. Reading API Data
Many APIs return data in JSON format.
JSON stands for:
Python treats JSON data similarly to dictionaries.
---
Convert Response to JSON
---
Example
This prints the title of the first post returned by the API.
---
5. Understanding JSON
JSON stores information as key-value pairs.
Example:
---
Accessing Values
---
Accessing Multiple Fields
---
6. Understanding Status Codes
Status codes tell us whether a request succeeded or failed.
---
Common Status Codes
| Code | Meaning | Description |
|--------|--------|--------|
| 200 | OK | Request successful |
| 201 | Created | New resource created |
| 400 | Bad Request | Invalid request |
| 401 | Unauthorized | Missing or invalid authentication |
| 404 | Not Found | Resource does not exist |
| 500 | Server Error | Internal server problem |
---
Example
---
7. Why APIs Matter
APIs power most modern software.
Examples:
- ChatGPT API
- Google Maps API
- NASA API
- Weather APIs
- Payment APIs
- Social Media APIs
Without APIs, applications could not easily share information.
---
Real-World Applications
- AI Applications
- Mobile Apps
- Web Development
- Financial Systems
- Data Science
- Automation Tools
---
NASA API Example
The NASA APOD (Astronomy Picture of the Day) API provides daily space images.
Example:
---
Practice Exercises
1. Fetch Posts
Use:
Print the title of the first post.
---
2. Status Checker
Write a program that prints:
if the status code is 200.
Otherwise print:
---
3. JSON Explorer
Create a Python dictionary and practice accessing:
using dictionary keys.
---
4. NASA APOD Challenge
Use the NASA APOD API and print:
Interacting with APIs
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. What is an API?
API stands for Application Programming Interface.
An API is a set of rules that allows one software application to communicate with another.
In Python, APIs are commonly used to:
- Connect to AI models
- Access weather data
- Retrieve map information
- Access social media platforms
- Work with cloud services
---
Real-World Example
When you use a weather app:
Weather App → API → Weather Server
The API acts as the messenger between the application and the server.
---
RESTful APIs
Most modern APIs use REST (Representational State Transfer).
REST APIs communicate using standard HTTP methods.
---
2. HTTP Methods
The most common HTTP methods are:
GET → Retrieve data
POST → Create new data
PUT → Update existing data
DELETE → Remove data
---
Example Scenario
GET → Read user information
POST → Create a new account
PUT → Update profile details
DELETE → Delete an account
---
3. Making Requests in Python
Python commonly uses the
requests library to communicate with APIs.---
Import Requests
import requests
---
Example
import requests
url = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(url)
This sends a GET request to the API.
---
Checking the Response
print(response.status_code)
Example Output:
200
---
4. Reading API Data
Many APIs return data in JSON format.
JSON stands for:
JavaScript Object Notation
Python treats JSON data similarly to dictionaries.
---
Convert Response to JSON
data = response.json()
---
Example
if response.status_code == 200:
data = response.json()
print(data[0]["title"])
This prints the title of the first post returned by the API.
---
5. Understanding JSON
JSON stores information as key-value pairs.
Example:
{
"id": 1,
"title": "Hello World",
"userId": 10
}---
Accessing Values
json_data = response.json()
print(json_data["id"])
---
Accessing Multiple Fields
print(json_data["title"])
print(json_data["userId"])
---
6. Understanding Status Codes
Status codes tell us whether a request succeeded or failed.
---
Common Status Codes
| Code | Meaning | Description |
|--------|--------|--------|
| 200 | OK | Request successful |
| 201 | Created | New resource created |
| 400 | Bad Request | Invalid request |
| 401 | Unauthorized | Missing or invalid authentication |
| 404 | Not Found | Resource does not exist |
| 500 | Server Error | Internal server problem |
---
Example
if response.status_code == 200:
print("Success")
else:
print("Request Failed")
---
7. Why APIs Matter
APIs power most modern software.
Examples:
- ChatGPT API
- Google Maps API
- NASA API
- Weather APIs
- Payment APIs
- Social Media APIs
Without APIs, applications could not easily share information.
---
Real-World Applications
- AI Applications
- Mobile Apps
- Web Development
- Financial Systems
- Data Science
- Automation Tools
---
NASA API Example
The NASA APOD (Astronomy Picture of the Day) API provides daily space images.
Example:
import requests
url = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY"
response = requests.get(url)
data = response.json()
print(data["title"])
print(data["url"])
---
Practice Exercises
1. Fetch Posts
Use:
https://jsonplaceholder.typicode.com/posts
Print the title of the first post.
---
2. Status Checker
Write a program that prints:
Success
if the status code is 200.
Otherwise print:
Request Failed
---
3. JSON Explorer
Create a Python dictionary and practice accessing:
name
age
country
using dictionary keys.
---
4. NASA APOD Challenge
Use the NASA APOD API and print:
Title
Image URL
Explanation
Python coding
Python_API_Interaction_Guide.pdf
for today's astronomy picture.
Python coding
Python_Testing_and_Debugging_Guide.pdf
Basic Python Course
Testing and Debugging
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Introduction to Testing
Testing is the process of checking whether your code behaves as expected.
A program may run without errors but still produce incorrect results.
Testing helps programmers:
- Find bugs early
- Improve reliability
- Prevent future errors
- Build professional software
---
What is Unit Testing?
Unit testing is a technique where individual components such as functions and classes are tested independently.
The goal is to verify that each small part of a program works correctly before integrating it into a larger system.
---
Why Unit Testing Matters
Benefits:
- Detects bugs quickly
- Makes code easier to maintain
- Improves software quality
- Helps developers make changes confidently
---
Pro Tip
If a test fails, you can isolate the bug without worrying about the rest of the application.
---
2. Using the
Python includes a built-in testing framework called
To create tests:
1. Import
2. Create a class that inherits from
3. Write test methods
4. Run the tests
---
Example
---
Understanding the Example
Expected result:
---
``
Checks whether two values are equal.
If they are not equal, the test fails.
---
Runs all tests inside the file.
---
3. Common Assert Methods
Assertions are used to verify expected results.
---
Checking Equality
Verifies:
---
Checking True Values
Verifies that:
---
Checking Membership
Verifies that an item exists inside a collection.
Example:
---
Checking Exceptions
Verifies that specific errors are raised.
Example:
---
4. Writing Clean Code (PEP 8)
PEP 8 is Python's official style guide.
Following PEP 8 makes code easier to:
- Read
- Maintain
- Debug
- Share with other developers
---
Indentation
Use:
per indentation level.
Example:
---
Naming Conventions
Functions and variables:
Example:
---
Classes
Use:
Example:
---
Line Length
Keep lines below:
whenever possible.
---
DRY Principle
DRY means:
Avoid duplicated code.
Bad Example:
Better Example:
---
5. Debugging Strategies
Debugging is the process of finding and fixing errors.
Every programmer spends a large amount of time debugging.
---
Read the Traceback
When Python encounters an error, it provides a traceback.
Example:
Read the traceback carefully.
It usually tells you:
- What happened
- Which line failed
- Why it failed
---
Print Debugging
Use
Example:
This helps verify values during execution.
---
Simplify the Program
Temporarily remove or comment out sections of code.
Example:
Keep simplifying until the source of the bug becomes obvious.
---
Testing and Debugging
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Introduction to Testing
Testing is the process of checking whether your code behaves as expected.
A program may run without errors but still produce incorrect results.
Testing helps programmers:
- Find bugs early
- Improve reliability
- Prevent future errors
- Build professional software
---
What is Unit Testing?
Unit testing is a technique where individual components such as functions and classes are tested independently.
The goal is to verify that each small part of a program works correctly before integrating it into a larger system.
---
Why Unit Testing Matters
Benefits:
- Detects bugs quickly
- Makes code easier to maintain
- Improves software quality
- Helps developers make changes confidently
---
Pro Tip
If a test fails, you can isolate the bug without worrying about the rest of the application.
---
2. Using the
unittest FrameworkPython includes a built-in testing framework called
unittest.To create tests:
1. Import
unittest2. Create a class that inherits from
unittest.TestCase3. Write test methods
4. Run the tests
---
Example
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(
add(10, 5),
15
)
self.assertEqual(
add(-1, 1),
0
)
if __name__ == "__main__":
unittest.main()
---
Understanding the Example
add(10, 5)
Expected result:
15
---
``
python
assertEqual()
``Checks whether two values are equal.
If they are not equal, the test fails.
---
unittest.main()
Runs all tests inside the file.
---
3. Common Assert Methods
Assertions are used to verify expected results.
---
Checking Equality
self.assertEqual(a, b)
Verifies:
a == b
---
Checking True Values
self.assertTrue(x)
Verifies that:
x is True
---
Checking Membership
self.assertIn(item, collection)
Verifies that an item exists inside a collection.
Example:
self.assertIn(
"apple",
["apple", "banana"]
)
---
Checking Exceptions
self.assertRaises(Error)
Verifies that specific errors are raised.
Example:
with self.assertRaises(
ZeroDivisionError
):
5 / 0
---
4. Writing Clean Code (PEP 8)
PEP 8 is Python's official style guide.
Following PEP 8 makes code easier to:
- Read
- Maintain
- Debug
- Share with other developers
---
Indentation
Use:
4 spaces
per indentation level.
Example:
if True:
print("Hello")
---
Naming Conventions
Functions and variables:
snake_case
Example:
student_name
calculate_total()
---
Classes
Use:
CamelCase
Example:
StudentManager
BankAccount
---
Line Length
Keep lines below:
79 characters
whenever possible.
---
DRY Principle
DRY means:
Don't Repeat Yourself
Avoid duplicated code.
Bad Example:
print("Welcome")
print("Welcome")
print("Welcome")Better Example:
for i in range(3):
print("Welcome")
---
5. Debugging Strategies
Debugging is the process of finding and fixing errors.
Every programmer spends a large amount of time debugging.
---
Read the Traceback
When Python encounters an error, it provides a traceback.
Example:
ZeroDivisionError:
division by zero
Read the traceback carefully.
It usually tells you:
- What happened
- Which line failed
- Why it failed
---
Print Debugging
Use
print() to inspect variables.Example:
x = 10
print(x)
This helps verify values during execution.
---
Simplify the Program
Temporarily remove or comment out sections of code.
Example:
# process_data()
Keep simplifying until the source of the bug becomes obvious.
---
Python coding
Python_Testing_and_Debugging_Guide.pdf
Common Programming Errors
Syntax Error
Missing colon.
---
Name Error
Variable not defined.
---
Type Error
String and integer cannot be added directly.
---
Zero Division Error
Division by zero is not allowed.
---
Why Testing and Debugging Matter
Professional developers do not rely on luck.
They:
- Write tests
- Verify results
- Debug systematically
This leads to reliable and maintainable software.
---
Practice Exercises
1. Create a function called
---
2. Use
---
3. Write a test that confirms dividing by zero raises a
---
4. Create a program with an intentional bug and use
---
5. Refactor repeated code using the DRY principle.
Syntax Error
if True
print("Hello")
Missing colon.
---
Name Error
print(username)
Variable not defined.
---
Type Error
"5" + 5
String and integer cannot be added directly.
---
Zero Division Error
10 / 0
Division by zero is not allowed.
---
Why Testing and Debugging Matter
Professional developers do not rely on luck.
They:
- Write tests
- Verify results
- Debug systematically
This leads to reliable and maintainable software.
---
Practice Exercises
1. Create a function called
multiply() and write unit tests for it.---
2. Use
assertIn() to verify that "banana" exists inside a list.---
3. Write a test that confirms dividing by zero raises a
ZeroDivisionError.---
4. Create a program with an intentional bug and use
print() debugging to locate the problem.---
5. Refactor repeated code using the DRY principle.
Python coding
Version_Control_and_Deployment_Bonus.pdf
Basic Python Course
Bonus: Version Control & Deployment
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Version Control with Git
As projects become larger, simply creating multiple copies of files is not enough.
Version Control helps developers:
- Track changes
- Restore previous versions
- Work with teams
- Manage large projects efficiently
Git is the most popular version control system in the world.
---
Why Use Git?
Without Git:
This quickly becomes confusing.
With Git:
---
The Git Workflow
Git follows a simple workflow.
---
Initialize a Repository
Starts tracking a project.
---
Add Files
Selects changes that should be saved.
---
Create a Commit
Creates a snapshot of your project.
---
Push to GitHub
Uploads your project to a remote repository.
---
2. GitHub: Your Developer Portfolio
GitHub is a cloud platform used to host Git repositories.
Think of GitHub as:
---
Why GitHub Matters
Your GitHub profile can showcase:
- Python projects
- AI experiments
- Data analysis projects
- Machine learning models
- Open-source contributions
Many employers review GitHub profiles before hiring developers.
---
Benefits of GitHub
- Backup your projects
- Collaborate with others
- Share code publicly
- Build a professional portfolio
---
3. Deployment: Sharing Your Applications
Deployment means making your application available to users.
Before deployment:
After deployment:
---
Popular Deployment Platforms
- Streamlit Cloud
- Render
- Railway
- Vercel
- AWS
- Google Cloud
- Microsoft Azure
---
4. Building a Simple Streamlit App
Streamlit is one of the easiest ways to turn Python code into a web application.
---
Example
---
Displaying Data
---
Creating a Chart
---
What This Application Does
- Loads sales data
- Displays the dataset
- Creates a line chart
- Runs inside a browser
No HTML, CSS, or JavaScript required.
---
Running a Streamlit App
Save the file as:
Run:
A browser window will automatically open.
---
Why Deployment Matters
Deployment allows you to:
- Share projects
- Build SaaS products
- Create dashboards
- Publish AI applications
- Earn money from software
---
Real-World Applications
- AI Chatbots
- Business Dashboards
- Data Analysis Tools
- Stock Market Apps
- Machine Learning Predictors
- Customer Management Systems
---
5. The Roadmap to AI Architect
After mastering Python fundamentals, continue with:
---
Math for Machine Learning
Learn:
- Linear Algebra
- Calculus
- Statistics
- Probability
---
Scikit-Learn
Study:
- Regression
- Classification
- Clustering
- Model Evaluation
---
Deep Learning
Learn:
- Neural Networks
- TensorFlow
- PyTorch
---
Cloud AI
Deploy models using:
- AWS
- Google Cloud
- Microsoft Azure
---
Final Advice
The fastest way to master programming is:
Continue creating projects, publishing code, and teaching others what you learn.
---
Practice Exercises
1. Initialize a Git repository and create your first commit.
---
2. Create a GitHub account and upload one Python project.
---
3. Build a simple Streamlit application that displays a CSV file.
---
4. Add a line chart showing student grades.
---
5. Research the differences between:
and write a short comparison.
Bonus: Version Control & Deployment
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Version Control with Git
As projects become larger, simply creating multiple copies of files is not enough.
Version Control helps developers:
- Track changes
- Restore previous versions
- Work with teams
- Manage large projects efficiently
Git is the most popular version control system in the world.
---
Why Use Git?
Without Git:
project_final.py
project_final_v2.py
project_final_final.py
project_final_really_final.py
This quickly becomes confusing.
With Git:
Every change is tracked automatically.
---
The Git Workflow
Git follows a simple workflow.
---
Initialize a Repository
git init
Starts tracking a project.
---
Add Files
git add .
Selects changes that should be saved.
---
Create a Commit
git commit -m "Initial version"
Creates a snapshot of your project.
---
Push to GitHub
git push
Uploads your project to a remote repository.
---
2. GitHub: Your Developer Portfolio
GitHub is a cloud platform used to host Git repositories.
Think of GitHub as:
A portfolio for programmers
---
Why GitHub Matters
Your GitHub profile can showcase:
- Python projects
- AI experiments
- Data analysis projects
- Machine learning models
- Open-source contributions
Many employers review GitHub profiles before hiring developers.
---
Benefits of GitHub
- Backup your projects
- Collaborate with others
- Share code publicly
- Build a professional portfolio
---
3. Deployment: Sharing Your Applications
Deployment means making your application available to users.
Before deployment:
Only you can run the program.
After deployment:
Anyone can use the application online.
---
Popular Deployment Platforms
- Streamlit Cloud
- Render
- Railway
- Vercel
- AWS
- Google Cloud
- Microsoft Azure
---
4. Building a Simple Streamlit App
Streamlit is one of the easiest ways to turn Python code into a web application.
---
Example
import streamlit as st
import pandas as pd
st.title("Yehya's Sales Dashboard")
df = pd.read_csv("sales.csv")
---
Displaying Data
st.write(
"Here is the latest cleaned sales data:"
)
st.dataframe(df)
---
Creating a Chart
st.line_chart(
df["Price"]
)
---
What This Application Does
- Loads sales data
- Displays the dataset
- Creates a line chart
- Runs inside a browser
No HTML, CSS, or JavaScript required.
---
Running a Streamlit App
Save the file as:
app.py
Run:
streamlit run app.py
A browser window will automatically open.
---
Why Deployment Matters
Deployment allows you to:
- Share projects
- Build SaaS products
- Create dashboards
- Publish AI applications
- Earn money from software
---
Real-World Applications
- AI Chatbots
- Business Dashboards
- Data Analysis Tools
- Stock Market Apps
- Machine Learning Predictors
- Customer Management Systems
---
5. The Roadmap to AI Architect
After mastering Python fundamentals, continue with:
---
Math for Machine Learning
Learn:
- Linear Algebra
- Calculus
- Statistics
- Probability
---
Scikit-Learn
Study:
- Regression
- Classification
- Clustering
- Model Evaluation
---
Deep Learning
Learn:
- Neural Networks
- TensorFlow
- PyTorch
---
Cloud AI
Deploy models using:
- AWS
- Google Cloud
- Microsoft Azure
---
Final Advice
The fastest way to master programming is:
Learn → Build → Teach
Continue creating projects, publishing code, and teaching others what you learn.
---
Practice Exercises
1. Initialize a Git repository and create your first commit.
---
2. Create a GitHub account and upload one Python project.
---
3. Build a simple Streamlit application that displays a CSV file.
---
4. Add a line chart showing student grades.
---
5. Research the differences between:
AWS
Google Cloud
Azure
and write a short comparison.
Python coding
Python_Masterclass_Final_Summary.pdf
# Python Programming Masterclass
### Complete Course Summary & Reference Guide
By Yehya Oumer
Mizan Institute of Technology
From Basics to Data Science & AI Foundations
Issued: May 2026
---
# Module 1: Numerical Foundations (NumPy)
Efficient data handling starts with NumPy, providing arrays that are significantly faster than standard Python lists. 0
## NumPy Essentials
---
# Module 2: Data Analysis with Pandas
Pandas is used for cleaning, exploring, and manipulating structured data using DataFrames. 1
## Cleaning Messy Data
---
# Module 3: Statistical Visualization
Transform raw numbers into meaningful visual insights using Matplotlib and Seaborn. 2
## Visualization Toolkit
- Line Plots → Trends over time
- Scatter Plots → Relationships between variables
- Box Plots → Distribution and outlier detection
- Heatmaps → Correlation analysis
### Example
---
# Module 4: Web Scraping & APIs
Gather real-world data from the internet using Python. 3
## BeautifulSoup & Requests
---
# Module 5: Professional Development
Learn how to write reliable, maintainable, and professional Python code. 4
## Testing & PEP 8
- Follow DRY (Don't Repeat Yourself)
- Use PEP 8 naming conventions
- Prefer
### Example
---
# Conclusion & Next Steps
You have successfully completed the Python foundations required for AI Architecture.
Next topics to study:
- Machine Learning Mathematics
- Model Development
- Scikit-Learn
- Deep Learning
- AI Engineering
### Complete Course Summary & Reference Guide
By Yehya Oumer
Mizan Institute of Technology
From Basics to Data Science & AI Foundations
Issued: May 2026
---
# Module 1: Numerical Foundations (NumPy)
Efficient data handling starts with NumPy, providing arrays that are significantly faster than standard Python lists. 0
## NumPy Essentials
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Reshaping 1D to 2D
new_arr = arr.reshape(1, 5)
# Statistics
mean_val = np.mean(arr)
---
# Module 2: Data Analysis with Pandas
Pandas is used for cleaning, exploring, and manipulating structured data using DataFrames. 1
## Cleaning Messy Data
import pandas as pd
df = pd.read_csv('data.csv')
# Remove null values
df.dropna(inplace=True)
# Remove duplicate rows
df.drop_duplicates(inplace=True)
# Format date column
df['Date'] = pd.to_datetime(df['Date'])
---
# Module 3: Statistical Visualization
Transform raw numbers into meaningful visual insights using Matplotlib and Seaborn. 2
## Visualization Toolkit
- Line Plots → Trends over time
- Scatter Plots → Relationships between variables
- Box Plots → Distribution and outlier detection
- Heatmaps → Correlation analysis
### Example
import seaborn as sns
import matplotlib.pyplot as plt
sns.heatmap(df.corr(), annot=True)
plt.show()
---
# Module 4: Web Scraping & APIs
Gather real-world data from the internet using Python. 3
## BeautifulSoup & Requests
import requests
from bs4 import BeautifulSoup
res = requests.get("https://example.com")
soup = BeautifulSoup(
res.content,
"html.parser"
)
print(soup.find('h1').text)
---
# Module 5: Professional Development
Learn how to write reliable, maintainable, and professional Python code. 4
## Testing & PEP 8
- Follow DRY (Don't Repeat Yourself)
- Use PEP 8 naming conventions
- Prefer
snake_case for variables and functions### Example
import unittest
class TestProject(unittest.TestCase):
def test_logic(self):
self.assertEqual(
2 + 2,
4
)
---
# Conclusion & Next Steps
You have successfully completed the Python foundations required for AI Architecture.
Next topics to study:
- Machine Learning Mathematics
- Model Development
- Scikit-Learn
- Deep Learning
- AI Engineering
✓ Course Completed Successfully
Python coding
Advanced_Python_Architecture_Mastery.pdf
Advanced Python Architecture
By Yehya Oumer
Mizan Institute of Technology
Issued: 2026
---
# 1. Object-Oriented Programming (OOP) Mastery
In AI architecture, almost everything is built around objects.
Frameworks such as PyTorch use classes and inheritance extensively to build neural network layers and reusable components. 0
---
## Classes, Methods, and Inheritance
---
## Why OOP Matters
Benefits:
- Reusable code
- Better organization
- Easier maintenance
- Scalable software architecture
- Foundation of modern AI frameworks
---
# 2. Decorators: Enhancing Functions
Decorators allow you to modify the behavior of a function without changing its original source code. 1
They are commonly used for:
- Logging
- Monitoring
- Timing functions
- Authentication
- Performance measurement
---
## Example
---
## What Happens Here?
Wraps the function automatically.
---
Measures execution time.
---
Useful for:
- AI training sessions
- Performance optimization
- Benchmarking
---
# 3. Generators & Memory Efficiency
Large-scale applications cannot always load huge datasets into memory.
Generators solve this problem by producing data one item at a time. 2
---
## Example
---
## Understanding
Unlike
Stops the function completely.
---
Pauses the function and remembers its state.
---
Benefits:
- Lower memory usage
- Faster processing
- Better scalability
---
# 4. Asynchronous Programming (asyncio)
Asynchronous programming allows multiple tasks to run concurrently without blocking each other. 3
This is useful when:
- Calling APIs
- Downloading files
- Working with networks
- Processing multiple requests
---
## Example
---
## Understanding Key Concepts
Defines an asynchronous function.
---
Waits without blocking the entire program.
---
Runs multiple tasks concurrently.
---
Benefits:
- Faster applications
- Better responsiveness
- Efficient network operations
---
# 5. Context Managers (
Context managers safely manage resources.
They ensure resources are released properly even if an error occurs. 4
---
## Example
class DatabaseConnection:
enterer__(self):
print(
"Connected to AI Database"
)
return self
By Yehya Oumer
Mizan Institute of Technology
Issued: 2026
---
# 1. Object-Oriented Programming (OOP) Mastery
In AI architecture, almost everything is built around objects.
Frameworks such as PyTorch use classes and inheritance extensively to build neural network layers and reusable components. 0
---
## Classes, Methods, and Inheritance
class AIModel:
def __init__(self, name):
self.name = name
def predict(self, data):
raise NotImplementedError(
"Subclasses must implement this!"
)
class NeuralNetwork(AIModel):
def predict(self, data):
return (
f"Processing {data} "
f"using {self.name} architecture..."
)
model = NeuralNetwork(
"Transformer-V2"
)
print(
model.predict(
[0.1, 0.5, 0.9]
)
)
---
## Why OOP Matters
Benefits:
- Reusable code
- Better organization
- Easier maintenance
- Scalable software architecture
- Foundation of modern AI frameworks
---
# 2. Decorators: Enhancing Functions
Decorators allow you to modify the behavior of a function without changing its original source code. 1
They are commonly used for:
- Logging
- Monitoring
- Timing functions
- Authentication
- Performance measurement
---
## Example
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(
*args,
**kwargs
)
print(
f"Execution time: "
f"{time.time() - start:.4f}s"
)
return result
return wrapper
@timer_decorator
def train_model():
time.sleep(1.5)
return "Model Trained!"
train_model()
---
## What Happens Here?
@timer_decorator
Wraps the function automatically.
---
time.time()
Measures execution time.
---
Useful for:
- AI training sessions
- Performance optimization
- Benchmarking
---
# 3. Generators & Memory Efficiency
Large-scale applications cannot always load huge datasets into memory.
Generators solve this problem by producing data one item at a time. 2
---
## Example
def batch_generator(
data,
batch_size
):
for i in range(
0,
len(data),
batch_size
):
yield data[
i:i + batch_size
]
large_dataset = list(
range(1000000)
)
for batch in batch_generator(
large_dataset,
32
):
pass
---
## Understanding
yieldUnlike
return:return
Stops the function completely.
---
yield
Pauses the function and remembers its state.
---
Benefits:
- Lower memory usage
- Faster processing
- Better scalability
---
# 4. Asynchronous Programming (asyncio)
Asynchronous programming allows multiple tasks to run concurrently without blocking each other. 3
This is useful when:
- Calling APIs
- Downloading files
- Working with networks
- Processing multiple requests
---
## Example
import asyncio
async def fetch_api_data(id):
print(
f"Starting request {id}..."
)
await asyncio.sleep(2)
return (
f"Data {id} received"
)
async def main():
results = await asyncio.gather(
fetch_api_data(1),
fetch_api_data(2)
)
print(results)
asyncio.run(main())
---
## Understanding Key Concepts
async def
Defines an asynchronous function.
---
await
Waits without blocking the entire program.
---
asyncio.gather()
Runs multiple tasks concurrently.
---
Benefits:
- Faster applications
- Better responsiveness
- Efficient network operations
---
# 5. Context Managers (
with Statement)Context managers safely manage resources.
They ensure resources are released properly even if an error occurs. 4
---
## Example
`pythonclass DatabaseConnection:
enterer__(self):
print(
"Connected to AI Database"
)
return self
Python coding
Advanced_Python_Architecture_Mastery.pdf
def exit(
self,
exc_type,
exc_val,
exc_tb
):
print(
"Connection Closed Safely"
)
with DatabaseConnection() as db:
print(
"Running queries..."
)
python
Open resource
Do work
Manually close resource
python
Open resource
Do work
Automatically close resource
text
OOP → Structure
Decorators → Flexibility
Generators → Scale
Asyncio → Speed
Context Managers → Safety
python
Robot
python
name
version
speak()
text
Function Started
Function Finished
python
1 to 100
python
asyncio.gather()
text
Resource Opened
text
Resource Closed
when exiting.
self,
exc_type,
exc_val,
exc_tb
):
print(
"Connection Closed Safely"
)
with DatabaseConnection() as db:
print(
"Running queries..."
)
---
## Why Context Managers Matter
Without context managers:
python
Open resource
Do work
Manually close resource
Easy to forget.
---
With context managers:
python
Open resource
Do work
Automatically close resource
Safer and cleaner.
---
Common Uses
- Files
- Databases
- Network connections
- Cloud resources
---
# The AI Architect Mindset
Advanced Python is not only about writing code.
It is about designing systems that are:
- Scalable
- Maintainable
- Efficient
- Professional
Use:
text
OOP → Structure
Decorators → Flexibility
Generators → Scale
Asyncio → Speed
Context Managers → Safety
These concepts form the foundation of professional software engineering and AI architecture. 5
---
# Practice Exercises
### 1. OOP Challenge
Create a class called:
python
Robot
Add:
python
name
version
speak()
---
### 2. Decorator Challenge
Create a decorator that prints:
text
Function Started
Function Finished
before and after execution.
---
### 3. Generator Challenge
Create a generator that yields:
python
1 to 100
one number at a time.
---
### 4. Async Challenge
Create three asynchronous functions and execute them using:
python
asyncio.gather()
---
### 5. Context Manager Challenge
Create a custom context manager that prints:
text
Resource Opened
when entering and:
text
Resource Closed
`when exiting.
❤1
━━━━━━━━━━━━━━━━━━━━━━
🎓 COURSE COMPLETED
━━━━━━━━━━━━━━━━━━━━━━
Congratulations!
You have successfully completed the Python Programming Masterclass.
From Python fundamentals to Advanced Python Architecture, you have gained the knowledge and skills needed to continue your journey in software development, data science, and AI.
However, learning does not stop here.
In the coming days, this channel will continue to provide:
✓ Practice Questions
✓ Quizzes and Tests
✓ Programming Challenges
✓ Projects
✓ Advanced Tips
✓ Learning Resources
✓ Course Updates
✓ AI & Technology Content
Make sure to stay active, participate in discussions, and complete the upcoming exercises to strengthen your understanding.
The course may be complete, but the journey of mastery has only begun.
Keep learning.
Keep building.
Keep improving.
━━━━━━━━━━━━━━━━━━━━━━
Course Status: COMPLETED ✓
Next Phase: Practice & Mastery
━━━━━━━━━━━━━━━━━━━━━━
By Yehya Oumer
Mizan Institute of Technology
2026
🎓 COURSE COMPLETED
━━━━━━━━━━━━━━━━━━━━━━
Congratulations!
You have successfully completed the Python Programming Masterclass.
From Python fundamentals to Advanced Python Architecture, you have gained the knowledge and skills needed to continue your journey in software development, data science, and AI.
However, learning does not stop here.
In the coming days, this channel will continue to provide:
✓ Practice Questions
✓ Quizzes and Tests
✓ Programming Challenges
✓ Projects
✓ Advanced Tips
✓ Learning Resources
✓ Course Updates
✓ AI & Technology Content
Make sure to stay active, participate in discussions, and complete the upcoming exercises to strengthen your understanding.
The course may be complete, but the journey of mastery has only begun.
Keep learning.
Keep building.
Keep improving.
━━━━━━━━━━━━━━━━━━━━━━
Course Status: COMPLETED ✓
Next Phase: Practice & Mastery
━━━━━━━━━━━━━━━━━━━━━━
By Yehya Oumer
Mizan Institute of Technology
2026
📢 New Chapter Started
The lessons are finished.
Now we focus on what matters most:
Building.
Expect daily Python content:
✓ Projects
✓ Useful Scripts
✓ Coding Challenges
✓ AI Tools
✓ Python Tips
✓ Career Advice
✓ Advanced Concepts
Don't become someone who completed a course.
Become someone who uses what they learned.
Stay tuned.
The lessons are finished.
Now we focus on what matters most:
Building.
Expect daily Python content:
✓ Projects
✓ Useful Scripts
✓ Coding Challenges
✓ AI Tools
✓ Python Tips
✓ Career Advice
✓ Advanced Concepts
Don't become someone who completed a course.
Become someone who uses what they learned.
Stay tuned.
🐍 Python Tip #1: List Comprehensions
List comprehensions allow you to create lists in a shorter and cleaner way.
Instead of:
You can write:
Output:
---
You can also perform operations while creating the list.
Example:
Output:
---
Using conditions:
Output:
---
Why use list comprehensions?
✓ Cleaner code
✓ Fewer lines
✓ Faster execution
✓ Widely used in Data Science and AI
Challenge:
Create a list comprehension that generates:
without manually typing the numbers.
List comprehensions allow you to create lists in a shorter and cleaner way.
Instead of:
numbers = []
for i in range(1, 6):
numbers.append(i)
print(numbers)
You can write:
numbers = [i for i in range(1, 6)]
print(numbers)
Output:
[1, 2, 3, 4, 5]
---
You can also perform operations while creating the list.
Example:
squares = [x**2 for x in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
---
Using conditions:
even_numbers = [
x for x in range(1, 11)
if x % 2 == 0
]
print(even_numbers)
Output:
[2, 4, 6, 8, 10]
---
Why use list comprehensions?
✓ Cleaner code
✓ Fewer lines
✓ Faster execution
✓ Widely used in Data Science and AI
Challenge:
Create a list comprehension that generates:
[10, 20, 30, 40, 50]
without manually typing the numbers.
Python coding
🐍 Python Tip #1: List Comprehensions List comprehensions allow you to create lists in a shorter and cleaner way. Instead of: numbers = [] for i in range(1, 6): numbers.append(i) print(numbers) You can write: numbers = [i for i in range(1, 6)] print(numbers)…
💡 Python Tip #2: The
When looping through a list, you often need both the item's index and its value.
Instead of writing:
You can use
Output:
---
Starting the Index from a Different Number
By default,
You can change the starting number:
Output:
---
Why use
✓ Cleaner and more readable code
✓ No need to manually manage indexes
✓ Reduces common indexing mistakes
✓ Frequently used in real-world Python projects
---
Challenge:
Without using
using this list:
enumerate() FunctionWhen looping through a list, you often need both the item's index and its value.
Instead of writing:
fruits = ["Apple", "Banana", "Orange"]
for i in range(len(fruits)):
print(i, fruits[i])
You can use
enumerate():fruits = ["Apple", "Banana", "Orange"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 Apple
1 Banana
2 Orange
---
Starting the Index from a Different Number
By default,
enumerate() starts counting from 0.You can change the starting number:
fruits = ["Apple", "Banana", "Orange"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
Output:
1 Apple
2 Banana
3 Orange
---
Why use
enumerate()?✓ Cleaner and more readable code
✓ No need to manually manage indexes
✓ Reduces common indexing mistakes
✓ Frequently used in real-world Python projects
---
Challenge:
Without using
range(len()), print the following output using enumerate():Student 1: Ahmed
Student 2: Sara
Student 3: John
using this list:
students = ["Ahmed", "Sara", "John"]
Python coding
💡 Python Tip #2: The enumerate() Function When looping through a list, you often need both the item's index and its value. Instead of writing: fruits = ["Apple", "Banana", "Orange"] for i in range(len(fruits)): print(i, fruits[i]) You can use enumerate():…
🔥 Python Trick #3: Multiple Variable Assignment
Python allows you to assign multiple variables in a single line.
Instead of:
You can write:
---
You can also assign the same value to multiple variables.
Example:
Simplified:
---
Unpacking a Collection
Python can unpack a list or tuple directly into variables.
Example:
Output:
---
Ignoring Values
If you only need some values, use
Example:
Output:
---
Why use multiple assignment?
✓ Cleaner code
✓ Less typing
✓ Easier to read
✓ Commonly used in professional Python code
---
Challenge:
Without creating temporary variables, write Python code that swaps the values of:
so the final output becomes:
Python allows you to assign multiple variables in a single line.
Instead of:
name = "Yehya"
age = 16
country = "Ethiopia"
You can write:
name, age, country = "Yehya", 16, "Ethiopia"
---
You can also assign the same value to multiple variables.
Example:
x = 0
y = 0
z = 0
Simplified:
x = y = z = 0
---
Unpacking a Collection
Python can unpack a list or tuple directly into variables.
Example:
languages = ["Python", "Java", "C++"]
first, second, third = languages
print(first)
print(second)
print(third)
Output:
Python
Java
C++
---
Ignoring Values
If you only need some values, use
_ for the ones you don't care about.Example:
numbers = (10, 20, 30)
first, _, third = numbers
print(first)
print(third)
Output:
10
30
---
Why use multiple assignment?
✓ Cleaner code
✓ Less typing
✓ Easier to read
✓ Commonly used in professional Python code
---
Challenge:
Without creating temporary variables, write Python code that swaps the values of:
a = 15
b = 40
so the final output becomes:
a = 40
b = 15
Python coding
🔥 Python Trick #3: Multiple Variable Assignment Python allows you to assign multiple variables in a single line. Instead of: name = "Yehya" age = 16 country = "Ethiopia" You can write: name, age, country = "Yehya", 16, "Ethiopia" --- You can also assign…
🐍 Python Tip #4: The
The
Example:
Output:
---
Using
You can combine more than two lists.
Example:
Output:
---
Converting
The
To see all paired values, convert it into a list.
Example:
Output:
---
Why use
✓ Iterate over multiple lists at the same time
✓ Write cleaner and shorter code
✓ Avoid manual indexing with
✓ Frequently used in data processing and automation
---
Challenge:
Using
using these lists:
zip() FunctionThe
zip() function combines two or more iterables element by element.Example:
names = ["Ahmed", "Sara", "John"]
scores = [95, 88, 91]
for name, score in zip(names, scores):
print(name, score)
Output:
Ahmed 95
Sara 88
John 91
---
Using
zip() with Three ListsYou can combine more than two lists.
Example:
names = ["Ahmed", "Sara", "John"]
ages = [18, 19, 20]
countries = ["Egypt", "Ethiopia", "Canada"]
for name, age, country in zip(names, ages, countries):
print(name, age, country)
Output:
Ahmed 18 Egypt
Sara 19 Ethiopia
John 20 Canada
---
Converting
zip() to a ListThe
zip() function returns a zip object.To see all paired values, convert it into a list.
Example:
letters = ["A", "B", "C"]
numbers = [1, 2, 3]
result = list(zip(letters, numbers))
print(result)
Output:
[('A', 1), ('B', 2), ('C', 3)]---
Why use
zip()?✓ Iterate over multiple lists at the same time
✓ Write cleaner and shorter code
✓ Avoid manual indexing with
range() ✓ Frequently used in data processing and automation
---
Challenge:
Using
zip(), print the following output:Ali scored 90
Sara scored 85
John scored 95
using these lists:
students = ["Ali", "Sara", "John"]
marks = [90, 85, 95]