<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Emmanuel Akalumhe on Medium]]></title>
        <description><![CDATA[Stories by Emmanuel Akalumhe on Medium]]></description>
        <link>https://medium.com/@akalumheemmanuel?source=rss-47f639a5724c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EcmRxR6ErET5n4sF-1V58w@2x.jpeg</url>
            <title>Stories by Emmanuel Akalumhe on Medium</title>
            <link>https://medium.com/@akalumheemmanuel?source=rss-47f639a5724c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:11:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akalumheemmanuel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Data Cleaning and Exploratory Data Analysis (EDA) with Python: A Beginner’s Practical Guide Using…]]></title>
            <link>https://medium.com/@akalumheemmanuel/data-cleaning-and-exploratory-data-analysis-eda-with-python-a-beginners-practical-guide-using-331bcbf1f665?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/331bcbf1f665</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 16:33:04 GMT</pubDate>
            <atom:updated>2026-11-03T15:09:25.192Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Cleaning and Exploratory Data Analysis (EDA) with Python: A Beginner’s Practical Guide Using Jupyter Notebook</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bDW-CwdsZhNzRAYwigpqg.png" /></figure><p><em>Learn how to inspect, clean, transform, analyze, and visualize a real-world dataset using Python, Pandas, Matplotlib, and Seaborn.</em></p><h3>Introduction</h3><p>Data is everywhere. From financial transactions and customer records to environmental monitoring, healthcare, education, and business operations, organizations collect enormous amounts of information every day.</p><p>However, raw data is rarely ready for analysis.</p><p>It may contain missing values, duplicated records, inconsistent naming conventions, incorrect data types, unusual observations, and other inconsistencies that can affect the reliability of analytical results.</p><p>This is where <strong>Data Cleaning and Exploratory Data Analysis (EDA)</strong> become important.</p><p>In this tutorial, we will walk through a complete beginner-friendly data analysis workflow using Python. We will work with a forest biodiversity dataset containing information about forest types, geographical regions, vegetation, wildlife, environmental conditions, human disturbance, and conservation status.</p><p>By the end of this tutorial, you should understand how to:</p><ol><li>Set up a Python environment using Jupyter Notebook.</li><li>Import datasets into Python.</li><li>Inspect and understand a dataset.</li><li>Identify missing values and duplicate records.</li><li>Detect and handle inconsistent categorical values.</li><li>Identify suspicious numerical observations.</li><li>Clean and transform data using Pandas.</li><li>Perform descriptive statistical analysis.</li><li>Explore relationships between variables.</li><li>Create meaningful visualizations.</li><li>Interpret analytical findings.</li><li>Export a cleaned dataset for further analysis.</li></ol><p>You do not need to be an advanced Python programmer to follow this tutorial. Basic knowledge of Python variables, lists, functions, and data types will be helpful.</p><h3>1. Understanding the Dataset</h3><p>Our project will use a dataset called:</p><p>dirty_forest_biodiversity.csv</p><p>The dataset contains forest monitoring records. Each record represents a forest survey observation, with information about the forest environment and its biodiversity.</p><p>It contains <strong>415 rows and 16 columns</strong>.</p><h3>Understanding the dataset columns</h3><p>Before performing any analysis, it is important to understand what each column represents.</p><p>Site_ID: Unique identifier assigned to a forest site</p><p>Forest_Type: Classification of the forest ecosystem</p><p>Region: Geographical region where the forest is located</p><p>Survey_Date: Date the forest survey was conducted</p><p>Tree_Density: Number of trees recorded per unit area</p><p>Canopy_Cover: Percentage of the ground covered by the forest canopy</p><p>Plant_Species_Count: Number of plant species recorded</p><p>Bird_Species_Count: Number of bird species recorded</p><p>Mammal_Species_Count: Number of mammal species recorded</p><p>Insect_Species_Count: Number of insect species recorded</p><p>Soil_pH: Acidity or alkalinity of the soil.</p><p>Rainfall_mm: Rainfall measurement in millimetres</p><p>Temperature_C: Temperature measured in degrees Celsius</p><p>Deforestation_Rate: Recorded deforestation rate</p><p>Human_Disturbance: Level of human disturbance</p><p>Conservation_Status: Conservation classification of the forest site</p><h3>What questions can we answer with this dataset?</h3><p>A good data analyst does not simply load a dataset and start creating charts. The analyst first thinks about the questions the data could help answer.</p><p>For this project, we might investigate:</p><ul><li>Which forest type has the highest biodiversity?</li><li>Which geographical region has the highest average tree density?</li><li>Is there a relationship between canopy cover and biodiversity?</li><li>Does human disturbance appear to be associated with deforestation?</li><li>How does conservation status vary across forest types?</li><li>What is the distribution of rainfall and temperature across the surveyed locations?</li><li>Are there noticeable differences in biodiversity between protected and unprotected forests?</li></ul><p>These questions will guide our analysis.</p><p><strong>Important:</strong> The dataset is suitable for learning analytical techniques. We should not automatically treat its observations as verified ecological measurements or interpret associations as proof of causation.</p><h3>2. Setting Up Your Python Environment</h3><p>We will use <strong>Jupyter Notebook</strong> throughout this tutorial.</p><p>Jupyter Notebook is an interactive environment that allows us to write and execute Python code in individual cells. It also allows us to combine code, explanations, mathematical expressions, tables, and visualizations in one document.</p><p>This makes it particularly useful for data analysis and teaching.</p><h3>Step 1: Install Anaconda</h3><p>If you do not already have Python installed, I recommend installing Anaconda.</p><p>Anaconda provides Python, Jupyter Notebook, and several popular data science libraries.</p><p>Download it from:</p><p><a href="https://www.anaconda.com/download">https://www.anaconda.com/download</a></p><p>Follow the installation instructions for your operating system.</p><h3>Step 2: Launch Jupyter Notebook</h3><p>After installing Anaconda:</p><ol><li>Open Anaconda Navigator.</li><li>Locate Jupyter Notebook.</li><li>Click Launch.</li><li>Your browser should open the Jupyter Notebook interface.</li><li>Navigate to the folder containing your dataset.</li><li>Create a new Python notebook.</li></ol><p>Alternatively, you can launch Jupyter Notebook through your terminal or Anaconda Prompt:</p><pre>jupyter notebook</pre><h3>Step 3: Install the required libraries</h3><p>We will use the following Python libraries:</p><ul><li>Pandas: Data manipulation and cleaning.</li><li>NumPy: Numerical operations.</li><li>Matplotlib: Data visualization.</li><li>Seaborn: Statistical visualization.</li></ul><p>If these libraries are not already installed, run:</p><pre>!pip install pandas numpy matplotlib seaborn</pre><p>The exclamation mark allows us to execute a terminal command from a Jupyter Notebook cell. But if you have these librarires already installed please skip this step.</p><h3>Step 4: Import the libraries</h3><p>Let’s import the libraries into our notebook.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><p>Let’s understand what each import does.</p><p><strong>Pandas</strong></p><p>Pandas is one of the most important Python libraries for data analysis. It provides tools for reading, manipulating, filtering, cleaning, and analyzing structured datasets.</p><p>We use the alias pd to make it easier to reference.</p><p><strong>NumPy</strong></p><p>NumPy provides support for numerical calculations and array operations. We will use it for certain transformations and missing-value operations.</p><p><strong>Matplotlib</strong></p><p>Matplotlib is a visualization library that allows us to create charts such as histograms, bar charts, scatter plots, and line graphs.</p><p><strong>Seaborn</strong></p><p>Seaborn is built on top of Matplotlib. It provides a higher-level interface for creating statistical visualizations.</p><p>We also set a few visualization preferences:</p><pre>sns.set_theme(style=&quot;whitegrid&quot;)<br>plt.rcParams[&quot;figure.figsize&quot;] = (10, 6)</pre><p>This gives our charts a consistent and clean appearance.</p><h3>3. Importing the Dataset into Jupyter Notebook</h3><p>Now that our libraries are ready, let’s load the dataset.</p><p>Make sure dirty_forest_biodiversity.csv is in the same folder as your Jupyter Notebook.</p><p>Run:</p><pre>df = pd.read_csv(&quot;dirty_forest_biodiversity.csv&quot;)</pre><p>Let’s break this down.</p><ul><li>pd refers to Pandas.</li><li>read_csv() is a Pandas function used to read CSV files.</li><li>&quot;dirty_forest_biodiversity.csv&quot; is the filename.</li><li>df is the variable that stores the imported dataset.</li></ul><p>We commonly use df as shorthand for DataFrame.</p><p>A <strong>DataFrame</strong> is a two-dimensional tabular data structure consisting of rows and columns, similar to a spreadsheet.</p><p>To confirm that the dataset has been imported successfully:</p><pre>df.head()</pre><p>The head() method displays the first five rows by default.</p><p>You can also display more rows:</p><pre>df.head(10)</pre><p>To display the last five rows:</p><pre>df.tail()</pre><p>To display a random sample:</p><pre>df.sample(5)</pre><h3>Why do we inspect the first few rows?</h3><p>Before cleaning or analyzing a dataset, we need to understand what the data looks like.</p><p>Looking at the first few rows helps us identify:</p><ul><li>Column names.</li><li>The structure of the dataset.</li><li>The types of values stored in each column.</li><li>Possible formatting inconsistencies.</li><li>Whether the dataset was imported correctly.</li></ul><p>At this stage, we are only getting familiar with the data. We have not started cleaning it.</p><h3>4. Understanding the Structure of the Dataset</h3><p>Now that the dataset has been imported, let’s investigate its structure.</p><h3>4.1 Checking the number of rows and columns</h3><pre>df.shape</pre><p>Output:</p><pre>(415, 16)</pre><p>This means:</p><ul><li>415 rows.</li><li>16 columns.</li></ul><p>The first number represents the number of rows, while the second represents the number of columns.</p><p>Why is this important?</p><p>It gives us an immediate understanding of the size of the dataset.</p><p>For example, if you import a dataset that you expect to contain 10,000 records but shape returns (500, 15), you may need to investigate whether the correct file was loaded.</p><h3>4.2 Checking column names</h3><pre>df.columns</pre><p>This displays all the column names in the dataset.</p><p>You can also convert them into a list:</p><pre>df.columns.tolist()</pre><p>This is useful when you want to reference column names programmatically.</p><h3>4.3 Understanding data types</h3><p>One of the most important steps in data exploration is understanding the data types of each column.</p><p>Run:</p><pre>df.dtypes</pre><p>You will notice different data types, including:</p><ul><li>object: Usually represents strings or mixed Python objects.</li><li>int64: Represents integers.</li><li>float64: Represents floating-point numbers.</li></ul><p>For example:</p><p>Site_ID: object</p><p>Forest_Type: object</p><p>Survey_Date: object</p><p>Tree_Density: float64</p><p>Plant_Species_Count: int64</p><p>Soil_pH: float64</p><p>An important observation is that Survey_Date is currently stored as an object.</p><p>Although the values look like dates, Pandas has imported them as strings.</p><p>We will correct this later.</p><h3>4.4 Using info()</h3><p>The info() method provides a summary of the dataset.</p><pre>df.info()</pre><p>Our dataset returns information similar to:</p><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 415 entries, 0 to 414<br>Data columns (total 16 columns):<br>...<br>dtypes: float64(7), int64(3), object(6)<br>memory usage: 52.0+ KB</pre><p>This tells us:</p><ul><li>The dataset contains 415 records.</li><li>There are 16 columns.</li><li>Seven columns contain floating-point values.</li><li>Three columns contain integers.</li><li>Six columns contain object values.</li><li>The approximate memory usage is 52 KB.</li></ul><p>It also displays the number of non-null values in each column.</p><p>This is particularly useful because it helps us identify missing data.</p><h3>5. Identifying Missing Values</h3><p>Missing values are one of the most common problems encountered during data analysis.</p><p>A missing value occurs when an observation has no recorded value for a particular variable.</p><p>For example, a forest survey might have information about tree density and temperature but no recorded soil pH.</p><p>Let’s investigate missing values in our dataset.</p><h3>5.1 Checking missing values</h3><pre>df.isnull().sum()</pre><p>The output shows the number of missing values in each column.</p><p>Our dataset contains:</p><p>Tree_Density: 25</p><p>Bird_Species_Count: 26</p><p>Soil_pH: 27</p><p>Rainfall_mm: 25</p><p>All other columns: 0</p><p>This tells us that four columns contain missing values.</p><h3>5.2 Calculating missing-value percentages</h3><p>Counting missing values is useful, but percentages provide additional context.</p><p>For example, 25 missing values in a dataset of 415 rows represent a different situation from 25 missing values in a dataset of 50,000 rows.</p><p>Let’s calculate the percentage of missing values.</p><pre>missing_percentage = (df.isnull().sum() / len(df)) * 100<br>missing_percentage</pre><p>We can organize the results into a DataFrame:</p><pre>missing_data = pd.DataFrame({<br>    &quot;Missing_Count&quot;: df.isnull().sum(),<br>    &quot;Missing_Percentage&quot;: missing_percentage<br>})<br><br>missing_data = missing_data[missing_data[&quot;Missing_Count&quot;] &gt; 0]<br>missing_data</pre><p>This gives us a clearer picture of where missing values occur.</p><h3>5.3 Visualizing missing values</h3><p>We can use Seaborn to visualize missing values.</p><pre>plt.figure(figsize=(12, 6))<br><br>sns.heatmap(<br>    df.isnull(),<br>    cbar=False,<br>    yticklabels=False,<br>    cmap=&quot;viridis&quot;<br>)<br>plt.title(&quot;Missing Values in Forest Biodiversity Dataset&quot;)<br>plt.show()</pre><p>The heatmap helps us see which columns contain missing observations.</p><h3>5.4 Handling missing values</h3><p>There are different approaches to handling missing values.</p><p>The correct approach depends on the nature of the data and the purpose of the analysis.</p><p>Some common methods include:</p><ol><li>Removing rows containing missing values.</li><li>Removing columns containing excessive missing values.</li><li>Replacing missing numerical values with the mean.</li><li>Replacing missing numerical values with the median.</li><li>Replacing missing categorical values with the mode.</li><li>Using more advanced imputation techniques.</li></ol><p>Let’s examine two common approaches.</p><p><strong>Method A: Removing missing values</strong></p><pre>df.dropna()</pre><p>This returns a DataFrame with rows containing missing values removed.</p><p>To modify the existing DataFrame:</p><pre>df.dropna(inplace=True)</pre><p>However, be careful with this approach. Removing every row containing a missing value could result in significant data loss.</p><p>For our dataset, we have missing observations in four columns. Removing all affected rows would discard a considerable portion of the available data.</p><p>We should not remove observations without considering the consequences.</p><p><strong>Method B: Replacing missing values with the median</strong></p><p>For numerical variables, the median is often a useful choice when the data contains outliers or is not normally distributed.</p><p>The median is the middle value after arranging observations in ascending order.</p><p>Let’s calculate the median of the affected columns:</p><pre>df[[<br>    &quot;Tree_Density&quot;,<br>    &quot;Bird_Species_Count&quot;,<br>    &quot;Soil_pH&quot;,<br>    &quot;Rainfall_mm&quot;<br>]].median()</pre><p>We can replace the missing values using:</p><pre>columns_to_impute = [<br>    &quot;Tree_Density&quot;,<br>    &quot;Bird_Species_Count&quot;,<br>    &quot;Soil_pH&quot;,<br>    &quot;Rainfall_mm&quot;<br>]<br><br>for column in columns_to_impute:<br>    df[column] = df[column].fillna(df[column].median())</pre><p>The loop goes through each specified column and fills its missing values with that column’s median.</p><p>We should also verify the result:</p><pre>df.isnull().sum()</pre><p>Ideally, these four columns should now have no missing values.</p><p><strong>An important consideration:</strong> We will first investigate invalid numerical values before finalizing our cleaning strategy. If an impossible value is included when calculating the median, it can distort the imputation result. In a production workflow, perform domain validation before calculating replacement statistics.</p><h3>6. Identifying and Removing Duplicate Records</h3><p>Another common data-quality problem is duplicated records.</p><p>A duplicate occurs when the same observation appears more than once in a dataset.</p><p>Duplicates can affect statistical calculations, counts, averages, and other analytical results.</p><p>Let’s investigate.</p><h3>6.1 Checking duplicate records</h3><pre>df.duplicated().sum()</pre><p>Our dataset contains:</p><pre>15</pre><p>This means 15 rows are exact duplicates of earlier rows.</p><h3>6.2 Displaying duplicate records</h3><pre>duplicates = df[df.duplicated(keep=False)]<br>duplicates.head(10)</pre><p>The keep=False argument marks every occurrence of duplicated rows rather than marking only subsequent occurrences.</p><h3>6.3 Removing duplicate records</h3><p>Since these 15 records are exact duplicates across all columns, we can remove the repeated copies after confirming that the dataset’s intended record structure does not require repeated observations.</p><pre>df = df.drop_duplicates()</pre><p>Let’s verify:</p><pre>df.duplicated().sum()</pre><p>Expected result:</p><pre>0</pre><p>Our dataset now contains 400 rows.</p><p><strong>Important:</strong> Do not automatically remove every repeated Site_ID in a real forest-monitoring project. A forest site might legitimately be surveyed on multiple dates. The correct definition of a duplicate depends on the unit of observation. Here, we have removed exact duplicate rows, not simply records sharing an identifier.</p><h3>7. Cleaning Inconsistent Categorical Data</h3><p>Categorical variables describe groups or classifications.</p><p>Examples in our dataset include:</p><ul><li>Forest_Type</li><li>Region</li><li>Human_Disturbance</li><li>Conservation_Status</li></ul><p>One issue we discovered is inconsistent formatting.</p><p>For example, the Forest_Type column contains:</p><pre>Montane Forest<br>MANGROVE<br>Mangrov<br>tropical rainforest<br>Savannah</pre><p>These values are problematic because:</p><ul><li>MANGROVE uses uppercase letters.</li><li>tropical rainforest uses lowercase letters.</li><li>Mangrov appears to be a misspelling or abbreviation of Mangrove.</li></ul><p>Similarly, the Region column contains unnecessary spaces.</p><p>The Human_Disturbance column also contains inconsistent capitalization:</p><pre>HIGH<br>Medium<br>low</pre><p>Let’s clean these values.</p><h3>7.1 Removing unnecessary spaces</h3><p>We can use the .str.strip() method.</p><pre>df[&quot;Region&quot;] = df[&quot;Region&quot;].str.strip()</pre><p>This removes whitespace from the beginning and end of each string.</p><h3>7.2 Standardizing capitalization</h3><p>We can use .str.title():</p><pre>df[&quot;Forest_Type&quot;] = df[&quot;Forest_Type&quot;].str.strip().str.title()<br><br>df[&quot;Human_Disturbance&quot;] = (<br>    df[&quot;Human_Disturbance&quot;].str.strip().str.title()<br>)</pre><p>Now values such as:</p><pre>MANGROVE<br>tropical rainforest</pre><p>become:</p><pre>Mangrove<br>Tropical Rainforest</pre><h3>7.3 Correcting spelling inconsistencies</h3><p>We still have the value Mangrov.</p><p>Let’s replace it with Mangrove.</p><pre>df[&quot;Forest_Type&quot;] = df[&quot;Forest_Type&quot;].replace({<br>    &quot;Mangrov&quot;: &quot;Mangrove&quot;<br>})</pre><h3>7.4 Checking the results</h3><pre>df[&quot;Forest_Type&quot;].value_counts()</pre><p>We should now have four standardized forest types:</p><ul><li>Mangrove</li><li>Montane Forest</li><li>Savannah</li><li>Tropical Rainforest</li></ul><p>Let’s check the remaining categorical columns:</p><pre>print(df[&quot;Region&quot;].value_counts())<br>print(df[&quot;Human_Disturbance&quot;].value_counts())<br>print(df[&quot;Conservation_Status&quot;].value_counts())<br></pre><p>Standardizing categorical data is important because inconsistent labels can make one category appear as multiple categories during analysis.</p><p>For example, if we do not standardize MANGROVE and Mangrove, Pandas may treat them as separate forest types.</p><p>This could lead to misleading visualizations and summary statistics.</p><h3>8. Converting Data Types</h3><p>Data types determine how Python interprets and processes values.</p><p>Sometimes, a dataset contains values stored using an inappropriate data type.</p><p>We previously discovered that Survey_Date was imported as an object.</p><p>Let’s convert it to a proper datetime format.</p><h3>8.1 Converting the survey date</h3><pre>df[&quot;Survey_Date&quot;] = pd.to_datetime(<br>    df[&quot;Survey_Date&quot;],<br>    errors=&quot;coerce&quot;<br>)</pre><p>Let’s understand the parameters:</p><ul><li>pd.to_datetime() converts values into datetime objects.</li><li>errors=&quot;coerce&quot; converts invalid date values into NaT (Not a Time).</li></ul><p>Now check the result:</p><pre>df[&quot;Survey_Date&quot;].dtype</pre><p>Expected output:</p><pre>datetime64[ns]</pre><h3>8.2 Why is this important?</h3><p>Once dates are converted, we can extract useful information such as:</p><ul><li>Year of survey.</li><li>Month of survey.</li><li>Day of survey.</li><li>Quarter of survey.</li></ul><p>For example:</p><pre>df[&quot;Survey_Year&quot;] = df[&quot;Survey_Date&quot;].dt.year<br><br>df[&quot;Survey_Month&quot;] = df[&quot;Survey_Date&quot;].dt.month<br><br>df[&quot;Survey_Quarter&quot;] = df[&quot;Survey_Date&quot;].dt.quarter</pre><p>We have now created three additional columns.</p><p>Let’s inspect them:</p><pre>df[[<br>    &quot;Survey_Date&quot;,<br>    &quot;Survey_Year&quot;,<br>    &quot;Survey_Month&quot;,<br>    &quot;Survey_Quarter&quot;<br>]].head()</pre><p>These new variables can be useful when analyzing how environmental measurements differ over time.</p><h3>9. Detecting Outliers and Invalid Numerical Values</h3><p>This is one of the most important stages of data cleaning.</p><p>An outlier is an observation that differs considerably from other observations.</p><p>However, not every unusual observation is an error.</p><p>For example, a forest may naturally have significantly higher rainfall than another forest. That does not automatically make the measurement incorrect.</p><p>We need to distinguish between:</p><ul><li>Genuine extreme observations.</li><li>Measurement errors.</li><li>Data-entry mistakes.</li><li>Values that violate known physical or logical constraints.</li></ul><p>Let’s examine our numerical variables.</p><h3>9.1 Using descriptive statistics</h3><pre>df.describe()</pre><p>The describe() method provides:</p><ul><li>Count</li><li>Mean</li><li>Standard deviation</li><li>Minimum</li><li>25th percentile</li><li>Median</li><li>75th percentile</li><li>Maximum</li></ul><p>One particularly important observation in our dataset is:</p><p>Canopy_Cover: Min 20.37: Max 150.00</p><p>Soil_pH: Min 3.51: Max 25.00</p><p>Deforestation_Rate: Min -10.00: Max 14.99</p><p>These values deserve further investigation.</p><p>Why?</p><p><strong>Canopy_Cover:</strong> If this variable represents percentage cover, its valid range should be 0–100%. A value of 150% is not physically meaningful.</p><p><strong>Soil_pH:</strong> The conventional pH scale is 0–14. A value of 25 is outside that scale.</p><p><strong>Deforestation_Rate:</strong> If this variable represents a percentage rate of deforestation, a negative value is suspicious because a deforestation percentage should not be negative.</p><p>These are examples of domain-based validation.</p><p>The limits should always be confirmed against the dataset documentation and the actual measurement definitions.</p><h3>9.2 Detecting outliers using the IQR method</h3><p>Another common approach is the Interquartile Range (IQR).</p><p>The IQR measures the spread of the middle 50% of the observations.</p><p>The formula is:</p><p>[<br>IQR = Q3 — Q1<br>]</p><p>Where:</p><ul><li>Q1 is the 25th percentile.</li><li>Q3 is the 75th percentile.</li></ul><p>We calculate the lower and upper boundaries using:</p><p>[<br>Lower = Q1–1.5(IQR)<br>]</p><p>[<br>Upper = Q3 + 1.5(IQR)<br>]</p><p>Values outside these boundaries are flagged as potential outliers.</p><p>Let’s implement this in Python.</p><pre>Q1 = df[&quot;Tree_Density&quot;].quantile(0.25)<br>Q3 = df[&quot;Tree_Density&quot;].quantile(0.75)<br>IQR = Q3 - Q1<br>lower_bound = Q1 - 1.5 * IQR<br>upper_bound = Q3 + 1.5 * IQR<br>outliers = df[<br>    (df[&quot;Tree_Density&quot;] &lt; lower_bound) |<br>    (df[&quot;Tree_Density&quot;] &gt; upper_bound)<br>]<br>print(&quot;Lower Bound:&quot;, lower_bound)<br>print(&quot;Upper Bound:&quot;, upper_bound)<br>print(&quot;Number of potential outliers:&quot;, len(outliers))</pre><p>This identifies potential outliers in the Tree_Density column.</p><h3>9.3 Visualizing outliers with a boxplot</h3><pre>plt.figure(figsize=(10, 5))<br>sns.boxplot(x=df[&quot;Tree_Density&quot;])<br>plt.title(&quot;Distribution of Tree Density&quot;)<br>plt.xlabel(&quot;Tree Density&quot;)<br>plt.show()</pre><p>A boxplot helps us visualize the median, quartiles, spread, and potential outliers.</p><h3>9.4 Handling invalid values</h3><p>For our dataset, let’s assume that the documented measurement rules confirm:</p><ul><li>Canopy cover must be between 0 and 100%.</li><li>Soil pH must be between 0 and 14.</li><li>Deforestation rate is expressed as a percentage between 0 and 100%.</li></ul><p>We can flag invalid values by replacing them with missing values.</p><pre>df.loc[<br>    ~df[&quot;Canopy_Cover&quot;].between(0, 100),<br>    &quot;Canopy_Cover&quot;<br>] = np.nan<br>df.loc[<br>    ~df[&quot;Soil_pH&quot;].between(0, 14),<br>    &quot;Soil_pH&quot;<br>] = np.nan<br>df.loc[<br>    ~df[&quot;Deforestation_Rate&quot;].between(0, 100),<br>    &quot;Deforestation_Rate&quot;<br>] = np.nan</pre><p>Why use np.nan?</p><p>Because we do not know the correct measurement for these observations.</p><p>Replacing an invalid value with a missing value allows us to investigate it and apply an appropriate imputation strategy rather than pretending we know the original value.</p><p>We can now recalculate the medians and impute missing values:</p><pre>columns_to_impute = [<br>    &quot;Tree_Density&quot;,<br>    &quot;Bird_Species_Count&quot;,<br>    &quot;Soil_pH&quot;,<br>    &quot;Rainfall_mm&quot;,<br>    &quot;Canopy_Cover&quot;,<br>    &quot;Deforestation_Rate&quot;<br>]<br><br>for column in columns_to_impute:<br>    df[column] = df[column].fillna(df[column].median())</pre><p><strong>A professional consideration:</strong> In a real research project, median imputation is not automatically the best method. The reason a measurement is missing matters. We should investigate the missingness mechanism, consider whether missing values differ systematically across forest types or regions, and document every imputation decision. It is also useful to preserve missingness indicators before imputation.</p><h3>10. Creating a Clean Dataset</h3><p>We have now performed several cleaning operations:</p><ul><li>Identified missing values.</li><li>Removed exact duplicate records.</li><li>Standardized categorical values.</li><li>Corrected inconsistent spelling.</li><li>Converted the survey date into datetime format.</li><li>Identified invalid numerical observations.</li><li>Handled missing numerical values.</li></ul><p>Let’s perform a final quality check.</p><pre>print(&quot;Dataset Shape:&quot;, df.shape)<br>print(&quot;\nMissing Values:&quot;)<br>print(df.isnull().sum())<br>print(&quot;\nDuplicate Rows:&quot;)<br>print(df.duplicated().sum())<br>print(&quot;\nData Types:&quot;)<br>print(df.dtypes)</pre><p>We should also inspect the cleaned dataset:</p><pre>df.head()</pre><p>And review the updated statistics:</p><pre>df.describe()</pre><h3>Exporting the cleaned dataset</h3><p>It is good practice to preserve the cleaned dataset separately rather than overwrite the original file.</p><p>Let’s export our results.</p><pre>df.to_csv(&quot;cleaned_forest_biodiversity.csv&quot;, index=False)</pre><p>The index=False argument prevents Pandas from writing the DataFrame&#39;s index as an additional column.</p><p>We now have a cleaned dataset that can be used for exploratory analysis.</p><h3>11. Introduction to Exploratory Data Analysis (EDA)</h3><p>Now that our data is cleaned, we can move to Exploratory Data Analysis.</p><p>Exploratory Data Analysis is the process of examining, summarizing, and visualizing data to understand its structure, identify patterns, discover relationships, and generate useful insights.</p><p>In simple terms, EDA helps us understand what our data is telling us before we attempt to build statistical or machine learning models.</p><p>EDA generally involves:</p><ol><li>Univariate analysis.</li><li>Bivariate analysis.</li><li>Multivariate analysis.</li><li>Descriptive statistics.</li><li>Data visualization.</li><li>Interpretation of findings.</li></ol><p>Let’s explore each of these using our forest biodiversity dataset.</p><h3>12. Univariate Analysis</h3><p>Univariate analysis involves examining one variable at a time.</p><p>For example, we may want to understand:</p><ul><li>How tree density is distributed.</li><li>Which forest types appear most frequently.</li><li>What the average temperature is.</li><li>How rainfall measurements vary.</li></ul><p>Let’s begin.</p><h3>12.1 Descriptive statistics</h3><p>We can use:</p><pre>df.describe()</pre><p>This provides a statistical summary of the numerical columns.</p><p>For individual columns:</p><pre>df[&quot;Tree_Density&quot;].mean()</pre><p>This calculates the average tree density.</p><p>Other useful statistical methods include:</p><pre>df[&quot;Tree_Density&quot;].median()<br>df[&quot;Tree_Density&quot;].mode()<br>df[&quot;Tree_Density&quot;].std()<br>df[&quot;Tree_Density&quot;].min()<br>df[&quot;Tree_Density&quot;].max()</pre><p>Let’s understand them:</p><p>mean(): Calculates the average</p><p>median():Returns the middle value</p><p>mode():Returns the most frequently occurring value</p><p>std():Calculates standard deviation</p><p>min():Returns the minimum</p><p>max():Returns the maximum</p><p>These methods help us understand the central tendency and spread of numerical variables.</p><h3>12.2 Frequency distribution of categorical variables</h3><p>Let’s investigate the different forest types.</p><pre>df[&quot;Forest_Type&quot;].value_counts()</pre><p>This returns the number of observations belonging to each forest type.</p><p>To calculate percentages:</p><pre>df[&quot;Forest_Type&quot;].value_counts(normalize=True) * 100</pre><p>This helps us understand the proportion of each forest type represented in the dataset.</p><h3>12.3 Visualizing categorical variables with a bar chart</h3><pre>plt.figure(figsize=(10, 6))<br>sns.countplot(<br>    data=df,<br>    x=&quot;Forest_Type&quot;,<br>    order=df[&quot;Forest_Type&quot;].value_counts().index<br>)<br>plt.title(&quot;Distribution of Forest Types&quot;)<br>plt.xlabel(&quot;Forest Type&quot;)<br>plt.ylabel(&quot;Number of Observations&quot;)<br>plt.xticks(rotation=30)<br>plt.show()</pre><p>What should we look for?</p><ul><li>Which forest type has the highest number of observations?</li><li>Which has the lowest?</li><li>Are the observations evenly distributed?</li></ul><p>Remember that the number of records for a forest type does not necessarily represent its actual geographical coverage.</p><p>It only describes the composition of our dataset.</p><h3>12.4 Visualizing numerical variables with histograms</h3><p>A histogram shows how numerical observations are distributed across different intervals.</p><p>Let’s visualize tree density.</p><pre>plt.figure(figsize=(10, 6))<br>sns.histplot(<br>    data=df,<br>    x=&quot;Tree_Density&quot;,<br>    bins=20,<br>    kde=True<br>)<br>plt.title(&quot;Distribution of Tree Density&quot;)<br>plt.xlabel(&quot;Tree Density&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.show()</pre><p>The histogram helps us identify:</p><ul><li>Whether the distribution is approximately normal.</li><li>Whether the data is skewed.</li><li>Whether observations are concentrated around certain values.</li><li>Whether potential extreme values exist.</li></ul><p>We can repeat this process for other variables.</p><pre>sns.histplot(df[&quot;Temperature_C&quot;], bins=20, kde=True)<br>plt.title(&quot;Distribution of Temperature&quot;)<br>plt.show()</pre><p>And:</p><pre>sns.histplot(df[&quot;Rainfall_mm&quot;], bins=20, kde=True)<br>plt.title(&quot;Distribution of Rainfall&quot;)<br>plt.show()</pre><h3>13. Bivariate Analysis</h3><p>Bivariate analysis examines the relationship between two variables.</p><p>For example:</p><ul><li>Does tree density vary with canopy cover?</li><li>Is rainfall associated with temperature?</li><li>Does biodiversity differ across forest types?</li><li>Is human disturbance associated with deforestation?</li></ul><p>Let’s investigate.</p><h3>13.1 Relationship between forest type and plant species count</h3><p>We can calculate the average plant species count for each forest type.</p><pre>df.groupby(&quot;Forest_Type&quot;)[&quot;Plant_Species_Count&quot;].mean()</pre><p>The groupby() method groups observations based on a specified category.</p><p>Here, we are grouping the dataset by forest type and calculating the average plant species count within each group.</p><p>We can also organize the result:</p><pre>plant_diversity = (<br>    df.groupby(&quot;Forest_Type&quot;)[&quot;Plant_Species_Count&quot;]<br>    .mean()<br>    .sort_values(ascending=False)<br>)<br><br>plant_diversity</pre><p>Let’s visualize the results.</p><pre>plt.figure(figsize=(10, 6))<br>sns.barplot(<br>    x=plant_diversity.index,<br>    y=plant_diversity.values<br>)<br>plt.title(&quot;Average Plant Species Count by Forest Type&quot;)<br>plt.xlabel(&quot;Forest Type&quot;)<br>plt.ylabel(&quot;Average Plant Species Count&quot;)<br>plt.xticks(rotation=30)<br>plt.show()</pre><p>This chart allows us to compare average plant species counts across forest types.</p><h3>13.2 Relationship between region and tree density</h3><p>Let’s investigate whether average tree density differs across geographical regions.</p><pre>regional_tree_density = (<br>    df.groupby(&quot;Region&quot;)[&quot;Tree_Density&quot;]<br>    .mean()<br>    .sort_values(ascending=False)<br>)<br><br>regional_tree_density</pre><p>Visualize the results:</p><pre>plt.figure(figsize=(10, 6))<br>sns.barplot(<br>    x=regional_tree_density.index,<br>    y=regional_tree_density.values<br>)<br>plt.title(&quot;Average Tree Density by Region&quot;)<br>plt.xlabel(&quot;Region&quot;)<br>plt.ylabel(&quot;Average Tree Density&quot;)<br>plt.xticks(rotation=30)<br>plt.show()</pre><p>This helps us identify which region has the highest average tree density in the dataset.</p><h3>13.3 Relationship between canopy cover and plant species count</h3><p>A scatter plot is useful for examining the relationship between two numerical variables.</p><pre>plt.figure(figsize=(10, 6))<br>sns.scatterplot(<br>    data=df,<br>    x=&quot;Canopy_Cover&quot;,<br>    y=&quot;Plant_Species_Count&quot;,<br>    hue=&quot;Forest_Type&quot;<br>)<br>plt.title(&quot;Canopy Cover vs Plant Species Count&quot;)<br>plt.xlabel(&quot;Canopy Cover (%)&quot;)<br>plt.ylabel(&quot;Plant Species Count&quot;)<br>plt.show()</pre><p>What should we look for?</p><ul><li>Do observations appear to move upward or downward?</li><li>Is there a visible relationship?</li><li>Are there clusters?</li><li>Are there unusual observations?</li><li>Do forest types appear to follow different patterns?</li></ul><p>A scatter plot can suggest a relationship, but it does not establish causation.</p><h3>13.4 Relationship between human disturbance and deforestation</h3><p>Let’s compare average deforestation rates across human disturbance levels.</p><pre>disturbance_analysis = (<br>    df.groupby(&quot;Human_Disturbance&quot;)[&quot;Deforestation_Rate&quot;]<br>    .mean()<br>)<br>disturbance_analysis</pre><p>Visualize:</p><pre>plt.figure(figsize=(9, 5))<br>sns.barplot(<br>    data=df,<br>    x=&quot;Human_Disturbance&quot;,<br>    y=&quot;Deforestation_Rate&quot;,<br>    order=[&quot;Low&quot;, &quot;Medium&quot;, &quot;High&quot;]<br>)<br>plt.title(&quot;Deforestation Rate by Human Disturbance Level&quot;)<br>plt.xlabel(&quot;Human Disturbance&quot;)<br>plt.ylabel(&quot;Average Deforestation Rate&quot;)<br>plt.show()</pre><p>This analysis can help us investigate whether higher human disturbance levels are associated with higher average deforestation rates.</p><p>However, we must remember that other factors may influence deforestation, including agricultural expansion, logging, infrastructure development, and differences in conservation enforcement.</p><h3>14. Multivariate Analysis</h3><p>Multivariate analysis involves examining three or more variables simultaneously.</p><p>It helps us understand more complex relationships within a dataset.</p><p>Let’s explore some examples.</p><h3>14.1 Correlation analysis</h3><p>Correlation measures the strength and direction of a statistical relationship between two numerical variables.</p><p>A common measure is Pearson correlation.</p><p>The Pearson correlation coefficient ranges from -1 to +1.</p><p>CorrelationInterpretation+1Perfect positive linear correlationClose to +1Strong positive linear association0No linear associationClose to -1Strong negative linear association-1Perfect negative linear correlation</p><p>Let’s calculate the correlation matrix.</p><pre>numerical_df = df.select_dtypes(include=&quot;number&quot;)<br>correlation_matrix = numerical_df.corr(method=&quot;pearson&quot;)<br>correlation_matrix</pre><p>This calculates pairwise Pearson correlations between numerical columns.</p><h3>14.2 Visualizing the correlation matrix</h3><p>A heatmap provides a convenient way to visualize correlations.</p><pre>plt.figure(figsize=(14, 10))<br>sns.heatmap(<br>    correlation_matrix,<br>    annot=True,<br>    cmap=&quot;coolwarm&quot;,<br>    fmt=&quot;.2f&quot;,<br>    linewidths=0.5<br>)<br>plt.title(&quot;Correlation Matrix of Forest Biodiversity Variables&quot;)<br>plt.show()</pre><p>How do we interpret this?</p><ul><li>Positive values indicate that two variables tend to increase together.</li><li>Negative values indicate that one variable tends to decrease as the other increases.</li><li>Values close to zero indicate weak or no linear association.</li></ul><p>For example, we may investigate whether canopy cover is positively associated with tree density.</p><p>We can also examine whether deforestation rate is negatively associated with biodiversity measurements.</p><p><strong>Important:</strong> Correlation does not imply causation. A correlation between two variables does not prove that one causes the other. Also, Pearson correlation measures linear association, so nonlinear relationships may require other analytical methods.</p><h3>14.3 Comparing biodiversity across conservation statuses</h3><p>Let’s investigate whether biodiversity measurements differ across conservation categories.</p><pre>conservation_analysis = (<br>    df.groupby(&quot;Conservation_Status&quot;)[<br>        [<br>            &quot;Plant_Species_Count&quot;,<br>            &quot;Bird_Species_Count&quot;,<br>            &quot;Mammal_Species_Count&quot;,<br>            &quot;Insect_Species_Count&quot;<br>        ]<br>    ].mean()<br>)<br>conservation_analysis</pre><p>This produces the average species counts for each conservation category.</p><p>We can visualize plant species counts:</p><pre>plt.figure(figsize=(10, 6))<br>sns.boxplot(<br>    data=df,<br>    x=&quot;Conservation_Status&quot;,<br>    y=&quot;Plant_Species_Count&quot;<br>)<br>plt.title(&quot;Plant Species Count by Conservation Status&quot;)<br>plt.xlabel(&quot;Conservation Status&quot;)<br>plt.ylabel(&quot;Plant Species Count&quot;)<br>plt.show()</pre><p>A boxplot allows us to compare:</p><ul><li>Median species counts.</li><li>Variation within each conservation category.</li><li>Potential outliers.</li><li>Differences in the overall distributions.</li></ul><p>This is more informative than comparing averages alone.</p><p>However, differences between conservation categories do not establish that conservation status caused the differences. Forest type, location, survey effort, and other factors may also matter.</p><h3>15. Time-Based Exploratory Analysis</h3><p>Our dataset contains survey dates ranging from 2022 to 2025.</p><p>This provides an opportunity to examine how recorded observations vary over time.</p><p>First, let’s ensure our date column is correctly formatted.</p><pre>df[&quot;Survey_Date&quot;] = pd.to_datetime(df[&quot;Survey_Date&quot;])</pre><p>We previously extracted the survey year:</p><pre>df[&quot;Survey_Year&quot;] = df[&quot;Survey_Date&quot;].dt.year</pre><h3>15.1 Average temperature by survey year</h3><pre>yearly_temperature = (<br>    df.groupby(&quot;Survey_Year&quot;)[&quot;Temperature_C&quot;]<br>    .mean()<br>)<br>yearly_temperature</pre><p>Visualize:</p><pre>plt.figure(figsize=(10, 6))<br>sns.lineplot(<br>    x=yearly_temperature.index,<br>    y=yearly_temperature.values,<br>    marker=&quot;o&quot;<br>)<br>plt.title(&quot;Average Recorded Temperature by Survey Year&quot;)<br>plt.xlabel(&quot;Survey Year&quot;)<br>plt.ylabel(&quot;Average Temperature (°C)&quot;)<br>plt.show()</pre><h3>15.2 Average rainfall by survey year</h3><pre>yearly_rainfall = (<br>    df.groupby(&quot;Survey_Year&quot;)[&quot;Rainfall_mm&quot;]<br>    .mean()<br>)<br>plt.figure(figsize=(10, 6))<br>sns.lineplot(<br>    x=yearly_rainfall.index,<br>    y=yearly_rainfall.values,<br>    marker=&quot;o&quot;<br>)<br>plt.title(&quot;Average Recorded Rainfall by Survey Year&quot;)<br>plt.xlabel(&quot;Survey Year&quot;)<br>plt.ylabel(&quot;Average Rainfall (mm)&quot;)<br>plt.show()</pre><p>These visualizations help us investigate temporal patterns.</p><p>However, our dataset contains survey observations collected on different dates and potentially from different sites. Differences between yearly averages should not automatically be interpreted as climate trends.</p><p>For stronger time-series conclusions, we would need to account for consistent sampling, seasonality, geographical coverage, and repeated measurements.</p><h3>16. Creating a Summary Table for the Analysis</h3><p>A useful analytical practice is to create a summary table containing important measurements grouped by a meaningful category.</p><p>Let’s create a biodiversity summary by forest type.</p><pre>biodiversity_summary = (<br>    df.groupby(&quot;Forest_Type&quot;)<br>    .agg(<br>        Average_Tree_Density=(&quot;Tree_Density&quot;, &quot;mean&quot;),<br>        Average_Canopy_Cover=(&quot;Canopy_Cover&quot;, &quot;mean&quot;),<br>        Average_Plant_Species=(&quot;Plant_Species_Count&quot;, &quot;mean&quot;),<br>        Average_Bird_Species=(&quot;Bird_Species_Count&quot;, &quot;mean&quot;),<br>        Average_Mammal_Species=(&quot;Mammal_Species_Count&quot;, &quot;mean&quot;),<br>        Average_Insect_Species=(&quot;Insect_Species_Count&quot;, &quot;mean&quot;)<br>    )<br>    .round(2)<br>)<br>biodiversity_summary</pre><p>Let’s understand what we have done.</p><ul><li>groupby(&quot;Forest_Type&quot;) groups records by forest type.</li><li>agg() allows us to perform multiple aggregation operations.</li><li>Each output column receives a descriptive name.</li><li>mean calculates the average of each measurement.</li><li>round(2) rounds the results to two decimal places.</li></ul><p>This is a useful technique because it allows us to compare several variables across different categories in one table.</p><p>We can export the summary:</p><pre>biodiversity_summary.to_csv(<br>    &quot;forest_biodiversity_summary.csv&quot;<br>)</pre><h3>17. Documenting Your Findings</h3><p>Data analysis does not end when you finish writing Python code or generating visualizations.</p><p>A good data analyst must communicate findings clearly.</p><p>For this project, your analytical report should address the following questions:</p><p><strong>Dataset overview</strong></p><ul><li>How many observations were available initially?</li><li>How many columns were present?</li><li>What types of variables were included?</li></ul><p><strong>Data quality</strong></p><ul><li>Which columns contained missing values?</li><li>How many duplicate records were identified?</li><li>Which categorical variables required standardization?</li><li>Were there invalid or suspicious numerical values?</li><li>What cleaning decisions were made?</li></ul><p><strong>Exploratory findings</strong></p><ul><li>Which forest type had the highest average plant species count?</li><li>Which region had the highest average tree density?</li><li>Was there a noticeable relationship between canopy cover and plant diversity?</li><li>Did deforestation rates differ across human disturbance categories?</li><li>Were there differences in biodiversity across conservation statuses?</li></ul><p><strong>Limitations</strong></p><ul><li>Were any values imputed?</li><li>Could imputation influence the results?</li><li>Was the sample representative of all forest ecosystems?</li><li>Were there enough repeated observations to establish temporal trends?</li><li>Could other variables explain the observed relationships?</li></ul><p>Your conclusions should be supported by the actual output of your notebook. Avoid inventing findings simply because a chart appears to suggest something.</p><h3>18. Recommended Jupyter Notebook Structure</h3><p>For students working through this project, I recommend organizing the notebook into the following sections.</p><p>SectionContent1Project introduction2Importing libraries3Loading the dataset4Initial data inspection5Data quality assessment6Handling missing values7Removing duplicates8Standardizing categorical data9Correcting data types10Outlier and invalid-value investigation11Exporting cleaned data12Univariate analysis13Bivariate analysis14Multivariate analysis15Time-based analysis16Summary tables17Findings and conclusions</p><p>Use Markdown cells for explanations and Code cells for Python instructions.</p><p>To change a Jupyter Notebook cell into Markdown, select the cell and press M while in command mode. To change it back to code, press Y.</p><p>You can execute a cell using Shift + Enter.</p><p>This approach makes your notebook easier to read, understand, present, and share.</p><h3>19. Practical Assignment for Students</h3><p>Now that we have completed the tutorial, it is time to apply what we have learned.</p><p>Try completing these exercises independently before looking for solutions.</p><h3>Exercise 1: Dataset inspection</h3><ol><li>Import the forest biodiversity dataset.</li><li>Display the first 10 rows.</li><li>Find the number of rows and columns.</li><li>Display the data types.</li><li>Identify all columns containing missing values.</li></ol><h3>Exercise 2: Data cleaning</h3><ol><li>Remove exact duplicate records.</li><li>Standardize the Forest_Type column.</li><li>Remove unnecessary spaces from the Region column.</li><li>Correct the inconsistent Mangrov label.</li><li>Convert Survey_Date into datetime format.</li><li>Identify invalid canopy cover and soil pH measurements.</li><li>Handle missing numerical values appropriately.</li></ol><h3>Exercise 3: Univariate analysis</h3><ol><li>Find the average tree density.</li><li>Calculate the median rainfall.</li><li>Identify the most frequently occurring forest type.</li><li>Visualize the distribution of temperature.</li><li>Create a bar chart showing the number of observations by conservation status.</li></ol><h3>Exercise 4: Bivariate analysis</h3><ol><li>Calculate average plant species counts by forest type.</li><li>Compare average tree density across geographical regions.</li><li>Investigate the relationship between rainfall and temperature.</li><li>Compare deforestation rates across human disturbance categories.</li><li>Visualize canopy cover against bird species count.</li></ol><h3>Exercise 5: Advanced exploratory analysis</h3><ol><li>Create a correlation matrix for all numerical variables.</li><li>Identify the strongest positive correlation.</li><li>Identify the strongest negative correlation.</li><li>Compare average biodiversity across conservation categories.</li><li>Investigate changes in recorded temperature across survey years.</li><li>Write five observations supported by your analysis.</li></ol><h3>Bonus project</h3><p>Create a small analytical report titled:</p><p><strong>Forest Biodiversity and Conservation Analysis Using Python</strong></p><p>Your report should contain:</p><ul><li>Introduction.</li><li>Dataset description.</li><li>Data cleaning methodology.</li><li>Exploratory data analysis.</li><li>At least five visualizations.</li><li>Key findings.</li><li>Limitations.</li><li>Recommendations.</li></ul><h3>20. Conclusion</h3><p>Data cleaning and Exploratory Data Analysis are fundamental skills for anyone pursuing a career in data analytics, data science, business intelligence, or machine learning.</p><p>In this tutorial, we have worked through a complete analytical workflow using Python and Jupyter Notebook.</p><p>We started by importing the forest biodiversity dataset, inspecting its structure, and identifying data-quality problems. We then handled missing values, removed exact duplicate records, standardized categorical variables, converted data types, and investigated invalid numerical observations.</p><p>After cleaning the data, we explored it using descriptive statistics, frequency distributions, histograms, bar charts, scatter plots, boxplots, line charts, and correlation heatmaps.</p><p>More importantly, we learned that data analysis is not simply about writing Python code. It involves asking the right questions, understanding the data, making defensible cleaning decisions, interpreting results, and communicating findings accurately.</p><p>One principle worth remembering is:</p><p><strong>Garbage in, garbage out.</strong></p><p>The quality of your analytical results depends heavily on the quality of the data and the decisions made during the analysis process.</p><p>If you are just beginning your journey into data analytics, do not rush into machine learning before becoming comfortable with data cleaning and exploratory analysis. These skills form the foundation for almost every meaningful data science project.</p><p>Happy coding!</p><p><em>Recommended tools and resources</em></p><ul><li>Python: <a href="https://www.python.org/">https://www.python.org/</a></li><li>Anaconda: <a href="https://www.anaconda.com/download">https://www.anaconda.com/download</a></li><li>Jupyter Notebook: <a href="https://jupyter.org/">https://jupyter.org/</a></li><li>Pandas documentation: <a href="https://pandas.pydata.org/docs/">https://pandas.pydata.org/docs/</a></li><li>NumPy documentation: <a href="https://numpy.org/doc/">https://numpy.org/doc/</a></li><li>Matplotlib documentation: <a href="https://matplotlib.org/stable/">https://matplotlib.org/stable/</a></li><li>Seaborn documentation: <a href="https://seaborn.pydata.org/">https://seaborn.pydata.org/</a></li></ul><p><em>Dataset used: dirty_forest_biodiversity.csv</em></p><p><em>All code examples in this tutorial are designed to be executed in Jupyter Notebook.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=331bcbf1f665" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Pseudocode: How to Think Like a Programmer Before You Write a Single Line of Code]]></title>
            <link>https://medium.com/@akalumheemmanuel/the-art-of-pseudocode-how-to-think-like-a-programmer-before-you-write-a-single-line-of-code-53dad51b3634?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/53dad51b3634</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[pseudocode]]></category>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 12:30:35 GMT</pubDate>
            <atom:updated>2026-10-21T12:30:35.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6786LwrCE3GWUZg-FjrMPw.png" /></figure><h3><em>Great programmers don’t just know how to write code. They know how to think through a problem before they start writing it.</em></h3><p>When people begin learning programming, they often make the same mistake: they rush to write code.</p><p>They open VS Code, Jupyter Notebook, or their favourite code editor and immediately start typing. They memorise Python syntax, practise if statements, learn loops, explore dictionaries, and try to understand functions.</p><p>And these things matter.</p><p>But after a while, something interesting happens.</p><p>They can explain what a for loop does. They understand how to write a function. They know how to use a dictionary to store data.</p><p>Yet, when someone gives them a practical problem and asks them to build something from scratch, they get stuck.</p><p>They know the language, but they don’t know where to begin.</p><p><strong>The problem is not always a lack of coding knowledge. Sometimes, it is a lack of problem-solving practice.</strong></p><p>This is where pseudocode comes in.</p><p>Pseudocode is one of the simplest yet most underrated tools a beginner can use to develop the kind of thinking that makes someone a better programmer.</p><p>It teaches you to look beyond syntax and focus on the problem itself.</p><p>And once you learn to do that, programming begins to make a lot more sense.</p><h3>1. Before You Learn to Code, Learn to Think</h3><p>Imagine someone gives you this assignment:</p><p>“Build a program that analyses students’ scores, calculates the class average, identifies the highest and lowest scores, and assigns letter grades.”</p><p>If you are a beginner, your first instinct might be to ask:</p><ul><li>Which Python functions should I use?</li><li>Should I use a list or a dictionary?</li><li>How do I calculate the average?</li><li>How do I assign grades?</li><li>What should my code look like?</li></ul><p>These are reasonable questions, but notice something important: they are mostly questions about implementation.</p><p>Before answering them, you need to answer a more fundamental question:</p><p><strong>What exactly must the program do?</strong></p><p>Think about how a teacher would solve the same problem without a computer.</p><p>The teacher would collect the students’ scores, add them together, divide the total by the number of students, identify the highest and lowest scores, and compare each student’s performance with the class average.</p><p>Finally, the teacher would assign a grade to each student according to the grading scale.</p><p>That is already a solution.</p><p>You have not written a single line of Python, but you understand what needs to happen.</p><p>That is the beginning of programming.</p><p>A good programmer does not necessarily start by asking, “What code should I write?”</p><p>A better starting point is, “What steps would solve this problem?”</p><h3>2. What Exactly Is Pseudocode?</h3><p>Pseudocode is a way of describing the steps required to solve a problem using plain language and programming-like structures.</p><p>It is not a formal programming language. It does not require strict syntax, and a computer cannot execute it directly.</p><p>Its purpose is to help you organise your thoughts before translating them into actual code.</p><p>For example, suppose you want to determine whether a student passed or failed.</p><p>You could immediately write Python:</p><pre>score = 65<br>if score &gt;= 50:<br>    print(&quot;Pass&quot;)<br>else:<br>    print(&quot;Fail&quot;)</pre><p>This code is simple enough. But let’s take a step back.</p><p>What is the logic behind it?</p><p>In pseudocode, we might write:</p><pre>START<br>Get the student&#39;s score<br>IF the score is 50 or higher<br>    Display &quot;Pass&quot;<br>OTHERWISE<br>    Display &quot;Fail&quot;<br>END</pre><p>Notice the difference.</p><p>The Python version focuses on the language’s syntax. The pseudocode version focuses on the decision the program must make.</p><p>The logic remains understandable even if you have never used Python before.</p><p>You could translate the same steps into JavaScript, Java, C++, or another programming language.</p><p>That is the beauty of pseudocode: <strong>it separates your understanding of a problem from your knowledge of a programming language.</strong></p><p>Once you understand the logic, learning the syntax becomes much easier.</p><h3>3. The Real Skill: Breaking Big Problems into Smaller Ones</h3><p>One of the most important habits of good programmers is learning how to break a large problem into smaller, manageable tasks.</p><p>This approach is often called <em>decomposition</em>.</p><p>Let’s return to our Student Grade Analyzer.</p><p>At first glance, the project sounds like one big assignment. But when we examine it closely, we discover that it consists of several smaller problems.</p><p>The program needs to:</p><ol><li>Store student names and scores.</li><li>Calculate the class average.</li><li>Find the highest score.</li><li>Find the lowest score.</li><li>Determine whether each student scored above, below, or exactly at the average.</li><li>Assign a letter grade to each student.</li><li>Display the results clearly.</li></ol><p>Suddenly, the problem looks less intimidating.</p><p>Instead of trying to build an entire application at once, you can solve one part at a time.</p><p>Let’s see how we might plan it using pseudocode.</p><pre>START<br>Create a collection of students and their scores<br>Calculate the class average<br>Find the highest score<br>Find the lowest score<br>FOR each student<br>    Get the student&#39;s score<br>    Determine the student&#39;s letter grade<br>    Compare the student&#39;s score with the class average<br>    Display the student&#39;s name, score, grade, and status<br>END FOR<br>Display the class summary<br>END</pre><p>This is not the only valid way to organise the solution. For example, you could display the class summary before processing individual students.</p><p>What matters is that you have identified the major tasks and given yourself a sensible starting point.</p><p>You have transformed a vague assignment into a sequence of actions.</p><p>That is a valuable programming skill.</p><h3>Why does this matter?</h3><p>When you encounter a more complex project, such as a sales dashboard, a banking application, or a machine learning system, you will need the same ability.</p><p>You cannot solve every detail simultaneously.</p><p>You must identify the smaller problems, understand how they relate to one another, and solve them in a logical order.</p><p>The projects may become more complicated, but the underlying thinking remains remarkably similar.</p><h3>4. Think About the Data Before the Code</h3><p>A common beginner mistake is to start writing logic without first understanding the data the program will work with.</p><p>In our example, we have students and their scores.</p><p>We need a way to associate each student with the correct score.</p><p>Consider this data:</p><pre>Victoria: 92<br>Morayo: 74<br>Ope: 88<br>Sam: 61<br>Funmilayo: 95<br>Misturah: 78</pre><p>We could store the information in a Python dictionary:</p><pre>students = {<br>    &quot;Victoria&quot;: 92,<br>    &quot;Morayo&quot;: 74,<br>    &quot;Ope&quot;: 88,<br>    &quot;Sam&quot;: 61,<br>    &quot;Funmilayo&quot;: 95,<br>    &quot;Misturah&quot;: 78<br>}</pre><p>But the important question comes before the code:</p><p><strong>What information do we have, and what is the best way to organise it?</strong></p><p>Each student has a name and a corresponding score. A dictionary is a reasonable choice because it associates each name with a value.</p><p>If we were storing several subjects per student, the structure might need to change. We could use a nested dictionary, a list of dictionaries, or another appropriate data structure.</p><p>The point is not that dictionaries are always the best option.</p><p>The point is that good programmers consider the nature of their data before deciding how to represent it.</p><p>They ask questions such as:</p><ul><li>What information do I have?</li><li>What information do I need to produce?</li><li>How are these pieces of information related?</li><li>Will I need to retrieve, update, or compare them?</li><li>What structure makes those operations straightforward?</li></ul><p>Choosing an appropriate data structure is not merely a syntax decision. It is a design decision.</p><p>And design decisions affect how easy your program will be to understand, maintain, and extend.</p><h3>5. Learn to Ask the Right Questions</h3><p>Pseudocode is not simply about writing instructions in English. It is also about identifying questions that your program must answer.</p><p>Let’s examine the class average.</p><p>We know that the average is calculated by dividing the sum of the scores by the number of students.</p><p>In pseudocode:</p><pre>Add all the students&#39; scores together</pre><pre>Count the number of students</pre><pre>Divide the total score by the number of students</pre><pre>Store the result as the class average</pre><p>Only after understanding these steps should you translate them into Python.</p><pre>scores = list(students.values())</pre><pre>average = sum(scores) / len(scores)</pre><p>The code uses two useful Python functions:</p><ul><li>sum() adds the scores together.</li><li>len() counts how many scores there are.</li></ul><p>The division produces the average.</p><p>But there is another question worth asking:</p><p>What happens if there are no students?</p><p>If the dictionary is empty, len(scores) will be zero, and dividing by zero will raise an error.</p><p>Our original project assumes that at least one student exists. However, a more robust program should recognise the possibility of an empty collection and handle it appropriately.</p><p>For example:</p><pre>if not students:<br>    print(&quot;No student records available.&quot;)<br>else:<br>    scores = list(students.values())<br>    average = sum(scores) / len(scores)<br>    print(f&quot;Class Average: {average:.1f}&quot;)</pre><p>This illustrates an important principle.</p><p><strong>Good programmers do not only think about what should happen when everything works. They also consider what could go wrong.</strong></p><p>You do not need to anticipate every imaginable problem before writing your first program. However, learning to identify important assumptions and edge cases will make your solutions more reliable.</p><h3>6. Decisions: Teach Your Program How to Choose</h3><p>Programming involves more than performing calculations. It also involves making decisions based on conditions.</p><p>Our Student Grade Analyzer needs to assign a letter grade to every student.</p><p>The grading scale is:</p><p>Score 90–100 Grade A</p><p>Score 80–89 Garde B</p><p>Score 70–79 Grade C</p><p>Score 60–69 Grade D</p><p>Score Below 60 Grade F</p><p>Before writing the code, we need to determine the decision-making process.</p><p>Here is one way to express it:</p><pre>IF the score is 90 or higher<br>    Assign grade A<br>OTHERWISE, IF the score is 80 or higher<br>    Assign grade B<br>OTHERWISE, IF the score is 70 or higher<br>    Assign grade C<br>OTHERWISE, IF the score is 60 or higher<br>    Assign grade D<br>OTHERWISE<br>    Assign grade F</pre><p>Now we can translate that logic into Python:</p><pre>def assign_grade(score):<br>    if score &gt;= 90:<br>        return &quot;A&quot;<br>    elif score &gt;= 80:<br>        return &quot;B&quot;<br>    elif score &gt;= 70:<br>        return &quot;C&quot;<br>    elif score &gt;= 60:<br>        return &quot;D&quot;<br>    else:<br>        return &quot;F&quot;</pre><p>Why do we check the conditions in this order?</p><p>Suppose the score is 95.</p><p>The first condition is true, so the function returns &quot;A&quot;.</p><p>Suppose the score is 84.</p><p>The first condition is false, but the second condition is true, so the function returns &quot;B&quot;.</p><p>Suppose the score is 55.</p><p>None of the first four conditions is true, so the function returns &quot;F&quot;.</p><p>Understanding the order of these decisions is more important than memorising the syntax of if, elif, and else.</p><p>For instance, if you checked whether the score was greater than or equal to 60 first, a score of 95 would also satisfy that condition. If the program immediately assigned grade D, it would never reach the correct A condition.</p><p>This is why planning the logic matters.</p><p><strong>A computer follows the instructions you give it, not the result you intended.</strong></p><p>If your instructions are poorly organised, the program can produce incorrect results even when every line of code is syntactically valid.</p><h3>7. Learn to Recognise Repetition</h3><p>Look at the grading process again.</p><p>We need to assign a grade to Alice, then Bob, then Carol, and every other student.</p><p>Would it make sense to write the same grading conditions separately for each person?</p><p>No.</p><p>We can place the grading logic inside a function and reuse it whenever needed.</p><p>This is an example of <em>abstraction</em>: giving a task a clear name and hiding its implementation details behind a simple interface.</p><p>Our function is called assign_grade().</p><p>Whenever we need a student’s grade, we can simply call:</p><pre>grade = assign_grade(92)</pre><p>The function returns &quot;A&quot;.</p><p>We do not need to repeat the grading conditions every time.</p><p>In pseudocode, the idea might look like this:</p><pre>CREATE a function called ASSIGN_GRADE<br>Receive a student&#39;s score<br>    Determine the appropriate letter grade<br>    Return the grade<br>END FUNCTION</pre><p>We can then describe the main program:</p><pre>FOR each student in the student collection<br>Get the student&#39;s score<br>    Call ASSIGN_GRADE using that score<br>    Store the returned grade<br>END FOR</pre><p>The main program does not need to know every detail of the grading process. It only needs to know that the function can provide the correct grade.</p><p>This makes the program easier to understand.</p><p>It also means that if the grading scale changes, you can update the function rather than search through the entire program for repeated conditions.</p><h3>The lesson</h3><p>Whenever you notice a task being repeated, ask yourself:</p><ul><li>Can I give this task a clear name?</li><li>Can I turn it into a reusable function?</li><li>What information does it need?</li><li>What result should it return?</li></ul><p>Learning to identify these opportunities is part of developing good programming habits.</p><h3>8. Loops: Think About What Must Happen Repeatedly</h3><p>After calculating the class average, highest score, and lowest score, we still need to analyse each student’s performance.</p><p>We want to compare every student’s score with the class average.</p><p>The logic is straightforward:</p><pre>FOR each student<br>Compare the student&#39;s score with the class average<br>    IF the student&#39;s score is greater than the average<br>        Mark the student as above average<br>    OTHERWISE, IF the score is less than the average<br>        Mark the student as below average<br>    OTHERWISE<br>        Mark the student as equal to the average<br>    Display the student&#39;s results<br>END FOR</pre><p>This is a natural situation for a loop.</p><p>In Python:</p><pre>for name, score in students.items():<br>    if score &gt; average:<br>        status = &quot;Above average&quot;<br>    elif score &lt; average:<br>        status = &quot;Below average&quot;<br>    else:<br>        status = &quot;Equal to average&quot;</pre><pre>    print(name, score, status)</pre><p>Notice how the loop works with two pieces of information: the student’s name and their score.</p><p>The dictionary’s .items() method allows us to access both the key and its corresponding value.</p><p>More importantly, the loop saves us from writing separate instructions for every student.</p><p>If we add 100 students to the dictionary, the same logic can process all of them.</p><p>That is one of the advantages of programming: a well-designed set of instructions can handle many records without needing to be rewritten for each one.</p><p>When thinking through a problem, always look for operations that must be performed repeatedly. Those are often good candidates for loops.</p><h3>9. A Programmer’s Job Is Not Finished When the Code Runs</h3><p>Imagine you have completed your Student Grade Analyzer.</p><p>It runs without an error and produces a class average.</p><p>Does that mean the program is correct?</p><p>Not necessarily.</p><p>A program can run successfully and still produce incorrect results.</p><p>For example, what if your grading function assigns grade A to a score of 89?</p><p>What if the program identifies the wrong student as having the highest score?</p><p>What if a student whose score equals the class average is incorrectly labelled as below average?</p><p>These are logic errors, and they can be more difficult to identify than syntax errors.</p><p>One way to prevent them is to think about test cases before writing the code.</p><p>For our grading function, we should test scores around the boundaries of each grade:</p><p>Score 100: Expected grade A</p><p>Score 90: Expected grade A</p><p>Score 89: Expected grade B</p><p>Score 80: Expected grade B</p><p>Score 79: Expected grade C</p><p>Score 70: Expected grade C</p><p>Score 69: Expected grade D</p><p>Score 60: Expected grade D</p><p>Score 59: Expected grade F</p><p>Score 0: Expected grade F</p><p>Why test 90 and 89 separately?</p><p>Because they sit on opposite sides of a grading boundary.</p><p>If the program handles both correctly, we gain confidence that the transition between grades works as intended.</p><p>We should also consider:</p><ul><li>What happens when all students have the same score?</li><li>What happens when there is only one student?</li><li>What happens when the student collection is empty?</li><li>What happens when a score is outside the permitted range?</li></ul><p>The last question matters because our original project assumes scores are numeric and between 0 and 100. If those assumptions are not guaranteed by the program’s input process, we may need validation.</p><p>Testing is not an activity reserved for experienced software engineers. Beginners should develop the habit from the start.</p><p><strong>Writing code is only part of solving a problem. Checking whether your solution actually solves it is equally important.</strong></p><h3>10. From Pseudocode to a Complete Solution</h3><p>Let’s bring everything together.</p><p>We have identified the data, broken the problem into smaller tasks, planned the decisions, recognised repeated operations, and considered how to test the result.</p><p>Now the Python implementation becomes much easier to organise.</p><p>Here is the complete solution:</p><pre>students = {<br>    &quot;Victoria&quot;: 92,<br>    &quot;Morayo&quot;: 74,<br>    &quot;Ope&quot;: 88,<br>    &quot;Sam&quot;: 61,<br>    &quot;Funmilayo&quot;: 95,<br>    &quot;Misturah&quot;: 78<br>}<br></pre><pre>def assign_grade(score):<br>    if score &gt;= 90:<br>        return &quot;A&quot;<br>    elif score &gt;= 80:<br>        return &quot;B&quot;<br>    elif score &gt;= 70:<br>        return &quot;C&quot;<br>    elif score &gt;= 60:<br>        return &quot;D&quot;<br>    else:<br>        return &quot;F&quot;<br></pre><pre>def analyze_grades(students):<br>    if not students:<br>        print(&quot;No student records available.&quot;)<br>        return</pre><pre>    scores = list(students.values())<br>    average = sum(scores) / len(scores)</pre><pre>    print(f&quot;Class Average: {average:.1f}&quot;)<br>    print(f&quot;Highest Score: {max(scores)}&quot;)<br>    print(f&quot;Lowest Score: {min(scores)}&quot;)<br>    print()</pre><pre>    for name, score in students.items():<br>        grade = assign_grade(score)</pre><pre>        if score &gt; average:<br>            status = &quot;Above average&quot;<br>        elif score &lt; average:<br>            status = &quot;Below average&quot;<br>        else:<br>            status = &quot;Equal to average&quot;</pre><pre>        print(<br>            f&quot;{name:&lt;12} {score:&gt;5}  &quot;<br>            f&quot;Grade: {grade}  ({status})&quot;<br>        )<br></pre><pre>analyze_grades(students)</pre><p>The important thing is not simply that this program works.</p><p>It is that each part has a clear responsibility.</p><ul><li>The dictionary stores the student records.</li><li>assign_grade() determines a student&#39;s letter grade.</li><li>analyze_grades() calculates the class statistics and processes the students.</li><li>The loop compares individual scores with the average and displays the results.</li></ul><p>There is one more subtle but important point: we did not need to put everything inside one enormous function or write the entire program in one continuous block.</p><p>We organised the solution into understandable pieces.</p><p>That makes it easier to read, test, debug, and extend.</p><p>Imagine that the teacher later asks for the program to calculate the percentage of students who passed, identify students who need extra support, or export the results to a CSV file.</p><p>A clear structure makes those additions easier to plan.</p><p>That is the value of thoughtful design.</p><h3>11. Do Good Programmers Always Write Pseudocode First?</h3><p>No.</p><p>And this is an important distinction.</p><p>Pseudocode is a tool, not a compulsory ritual.</p><p>Experienced programmers sometimes start coding immediately when the task is small, familiar, or straightforward. They may sketch an idea on paper, write a few tests, build a quick prototype, or explain the solution verbally.</p><p>The goal is not to write pseudocode for every single operation.</p><p>The goal is to think clearly enough to choose an appropriate approach.</p><p>For a beginner, however, pseudocode is particularly useful because it creates space to reason without being distracted by syntax errors.</p><p>When you are still learning Python, it is easy to confuse two separate problems:</p><ol><li>You do not understand how to solve the problem.</li><li>You understand the solution but do not know the correct Python syntax.</li></ol><p>Pseudocode helps you separate these challenges.</p><p>If you can explain the steps in plain language but cannot translate them into Python, you know that you need to practise the language.</p><p>If you cannot explain the steps at all, learning another Python function may not solve the underlying problem.</p><p>You need to work on breaking down the task.</p><p>Knowing which problem you are facing helps you learn more effectively.</p><h3>12. How to Practise Thinking Like a Programmer</h3><p>You do not need to wait until you are working on a large project to develop these skills.</p><p>Start with small problems and deliberately practise the thinking process.</p><p>Here is a simple routine you can follow whenever you receive a programming assignment.</p><p><strong>Step 1: Understand the problem.</strong></p><p>Read the instructions carefully. Identify what the program must accomplish.</p><p>Do not start coding immediately.</p><p><strong>Step 2: Identify the inputs and outputs.</strong></p><p>Ask yourself what information the program will receive and what results it should produce.</p><p>For the Student Grade Analyzer, the inputs are student names and scores. The outputs include the average, highest and lowest scores, letter grades, and performance statuses.</p><p><strong>Step 3: Break the problem into smaller tasks.</strong></p><p>Identify the calculations, decisions, and repeated operations required to produce the outputs.</p><p><strong>Step 4: Write the steps in plain English.</strong></p><p>Describe the solution without worrying about Python syntax.</p><p>Your pseudocode does not have to be beautiful. It needs to be understandable and logically complete.</p><p><strong>Step 5: Identify important assumptions and edge cases.</strong></p><p>Consider what could happen with unusual or unexpected inputs.</p><p><strong>Step 6: Translate each step into code.</strong></p><p>Use the Python concepts you have learned: variables, dictionaries, conditionals, loops, functions, and other relevant tools.</p><p><strong>Step 7: Test the result.</strong></p><p>Check normal cases, boundary values, and important edge cases. Compare the actual output with what you expected.</p><p><strong>Step 8: Improve the solution.</strong></p><p>Once the program works, ask whether the code is clear, whether repeated logic can be reused, and whether the solution could be organised more effectively.</p><p>Follow this process consistently, and you will gradually become more comfortable approaching unfamiliar problems.</p><p>You will also begin to recognise patterns. Calculating averages, filtering records, comparing values, and repeating operations appear in many different programming tasks.</p><p>The more problems you solve, the easier it becomes to identify these patterns.</p><h3>13. A Challenge for You: Extend the Student Grade Analyzer</h3><p>Understanding an example is useful, but solving a problem yourself is what develops your skills.</p><p>Try extending the project with the following requirements.</p><p><strong>Challenge 1: Count the students who passed.</strong></p><p>Assume a score of 50 or higher is a pass.</p><p>Write pseudocode that counts how many students passed, then translate it into Python.</p><p><strong>Challenge 2: Calculate the pass percentage.</strong></p><p>Use the number of students who passed and the total number of students to calculate the percentage.</p><p>Remember to consider what would happen if the class had no students.</p><p><strong>Challenge 3: Identify students who need extra support.</strong></p><p>Create a collection containing students who scored below 50.</p><p>Think about which data structure would be suitable and why.</p><p><strong>Challenge 4: Add input validation.</strong></p><p>Modify the program so that it does not accept scores below 0 or above 100.</p><p>Consider how the program should respond when someone enters text instead of a number.</p><p><strong>Challenge 5: Plan before you code.</strong></p><p>For each challenge, write pseudocode first. Then implement your solution in Python.</p><p>Do not immediately search for a complete solution. Give yourself time to reason through the problem.</p><p>If you get stuck, identify the exact point where your thinking breaks down. Is it the calculation, the condition, the loop, the data structure, or the overall sequence?</p><p>That question is often more useful than simply asking, “What code should I write?”</p><h3>Programming Is More Than Knowing a Language</h3><p>Learning Python is valuable. Understanding functions, loops, dictionaries, and conditional statements is essential.</p><p>But these are tools.</p><p>The deeper skill is learning how to use those tools to solve problems.</p><p>Good programmers learn to understand requirements, break complicated tasks into smaller pieces, reason about data, make decisions, recognise repetition, test assumptions, and improve their solutions.</p><p>Pseudocode gives you a practical way to develop these habits.</p><p>It allows you to focus on the thinking behind a solution before dealing with the technical details of implementation.</p><p>And perhaps the most important lesson is this:</p><p><strong>You do not become a good programmer simply by writing more code. You become a better programmer by learning to solve problems more clearly, then expressing those solutions in code.</strong></p><p>So, the next time you receive a programming assignment, resist the urge to open your editor immediately.</p><p>Take a breath.</p><p>Understand the problem. Break it down. Write the steps. Think through the decisions. Consider what could go wrong.</p><p>Then start coding.</p><p>Your goal should not be to memorise enough code to solve familiar exercises. It should be to develop the ability to approach problems you have never seen before and work your way towards a solution.</p><p>That is the art of pseudocode.</p><p>And that is where the journey towards becoming a better programmer truly begins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53dad51b3634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Simple Linear Regression Model with Streamlit]]></title>
            <link>https://medium.com/@akalumheemmanuel/deploy-a-simple-linear-regression-model-with-streamlit-96f50479d50f?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/96f50479d50f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 12:07:53 GMT</pubDate>
            <atom:updated>2026-10-20T12:07:53.800Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s build a simple machine learning application from scratch, train a Linear Regression model, and deploy it using Streamlit Community Cloud so that other people can access it through a web link.</p><p>We’ll use Python, Scikit-learn, Pandas, and Streamlit. I’ll explain what each file does and why we need it.</p><h3>What we will be doing</h3><p>1. Prepare the data</p><p>Create a dataset containing study hours and exam scores.</p><p>2. Train the model</p><p>Use Scikit-learn to learn the relationship between study hours and exam scores.</p><p>3. Build the web app</p><p>Let users enter study hours and get a predicted score.</p><p>4. Deploy online</p><p>Push the project to GitHub and connect it to Streamlit Community Cloud.</p><h3>Step 1 Understand the project</h3><p>Our example is a model that predicts an exam score from the number of hours a student studies.</p><p>The model uses the linear regression equation:</p><p>y = mx + b</p><p>Where:</p><ul><li>(y) is the predicted exam score.</li><li>(x) is the number of study hours.</li><li>(m) is the slope learned by the model.</li><li>(b) is the intercept learned by the model.</li></ul><p>For example, the model might learn that more study hours are associated with higher scores. The actual slope and intercept will be calculated from our training data.</p><h3>Step 2 Set up your project folder</h3><p>Create a folder named linear-regression-streamlit.</p><p>Inside it, create these three files:</p><p>linear-regression-streamlit/</p><ol><li>app.py</li></ol><p>The Streamlit user interface and prediction logic.</p><p>2. train_model.py</p><p>Trains and saves the machine learning model.</p><p>3. requirements.txt</p><p>Lists the Python packages needed to run the app.</p><p>You can create these files in VS Code, PyCharm, or another code editor. Make sure the filenames match exactly.</p><h3>Step 3 Install the required libraries</h3><p>Open your terminal in the project folder and run:</p><pre>python -m venv .venv</pre><p>Activate the virtual environment.</p><p>Windows (PowerShell):</p><pre>.venv\Scripts\Activate.ps1</pre><p>macOS or Linux:</p><pre>source .venv/bin/activate</pre><p>Then install the packages:</p><pre>pip install streamlit scikit-learn pandas joblib</pre><p>What each package does:</p><p>1. streamlit</p><p>Builds the web application.</p><p>2. scikit-learn</p><p>Provides the Linear Regression algorithm.</p><p>3. pandas</p><p>Organizes data into tables.</p><p>4. joblib</p><p>Saves and loads the trained model.</p><h3>Step 4 Create the training script</h3><p>Open train_model.py and enter the following code.</p><pre>import pandas as pdfrom sklearn.linear_model <br>import LinearRegression<br>from joblib import dump<br><br># 1. Create our sample dataset<br>data = {<br>    &quot;hours&quot;: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],    <br>    &quot;scores&quot;: [12, 18, 28, 35, 42, 52, 58, 68, 75, 85]<br>}<br>df = pd.DataFrame(data)<br><br># 2. Separate features (X) and target (y)<br>X = df[[&quot;hours&quot;]]<br>y = df[&quot;scores&quot;]<br><br># 3. Create the model<br>model = LinearRegression()<br><br># 4. Train the model<br>model.fit(X, y)<br><br># 5. Save the trained model<br>dump(model, &quot;model.joblib&quot;)<br><br># 6. Display model information<br>print(&quot;Model trained successfully!&quot;)<br>print(&quot;Slope:&quot;, model.coef_[0])<br>print(&quot;Intercept:&quot;, model.intercept_)<br>print(&quot;R-squared:&quot;, model.score(X, y))</pre><h3>Let’s understand the codebase above</h3><p>1. Create the dataset</p><p>We create a small dataset with two columns: hours and scores. Each row represents one student&#39;s study hours and corresponding score.</p><p>2. Separate the inputs and outputs</p><pre>X = df[[&quot;hours&quot;]]y = df[&quot;scores&quot;]</pre><ul><li>X contains the input feature, study hours.</li><li>y contains the target variable, the score we want to predict.</li></ul><p>Notice the double brackets in df[[&quot;hours&quot;]]. Scikit-learn expects the input features in a two-dimensional structure, even when there is only one feature.</p><p>3. Create and train the model</p><pre>model = LinearRegression()model.fit(X, y)</pre><p>The first line creates the algorithm. The second lets it learn the best-fitting straight line from the examples.</p><p>4. Save the model</p><pre>dump(model, &quot;model.joblib&quot;)</pre><p>This creates a file containing the fitted model, allowing our Streamlit application to load it without retraining every time a user opens the app.</p><p>5. Inspect the model</p><ul><li>model.coef_[0] gives the slope.</li><li>model.intercept_ gives the intercept.</li><li>model.score(X, y) gives the (R^2) score on the training data.</li></ul><p>The last metric is calculated on the same data used to train the model, so it is only a demonstration, not a reliable measure of how well it will predict unseen students’ scores.</p><h3>Step 5 Train the model</h3><p>Run this command in your terminal:</p><pre>python train_model.py</pre><p>You should see output similar to this:</p><pre>Model trained successfully!<br>Slope: ...<br>Intercept: ...<br>R-squared: ...</pre><p>The exact values are calculated by your Python environment.</p><p>Your project folder should now contain a fourth file:</p><pre>linear-regression-streamlit/<br>├── app.py<br>├── train_model.py<br>└── model.joblib</pre><p>model.joblib is generated when you run the training script. You should not need to create it manually.</p><h3>Step 6 Build the Streamlit application</h3><p>Now let’s create the part users will interact with.</p><p>Open app.py and add the following code:</p><pre><br>import streamlit as st<br>import pandas as pd<br>from joblib import load<br><br># 1. Configure the page<br>st.set_page_config(<br>    page_title=&quot;Exam Score Predictor&quot;,<br>    page_icon=&quot;📚&quot;,<br>    layout=&quot;centered&quot;<br>)<br><br># 2. Load the trained model<br>model = load(&quot;model.joblib&quot;)<br><br># 3. Create the application interface<br>st.title(&quot;📚 Exam Score Predictor&quot;)<br><br>st.write(<br>    &quot;Predict an exam score based on the number &quot;<br>    &quot;of hours spent studying.&quot;<br>)<br><br># 4. Collect user input<br>hours = st.number_input(<br>    &quot;How many hours did you study?&quot;,<br>    min_value=0.0,<br>    max_value=10.0,<br>    value=5.0,<br>    step=0.5<br>)<br><br># 5. Make a prediction<br>if st.button(&quot;Predict Score&quot;):<br>    input_data = pd.DataFrame({<br>        &quot;hours&quot;: [hours]<br>    })<br><br>    prediction = model.predict(input_data)[0]<br><br>    # 6. Display the result<br>    st.success(<br>        f&quot;Predicted exam score: {prediction:.2f}&quot;<br>    )<br><br>    st.caption(<br>        &quot;This is an educational demonstration using &quot;<br>        &quot;a small sample dataset, not a validated &quot;<br>        &quot;exam prediction system.&quot;<br>    )</pre><h3>How the application works</h3><p>User enters study hours</p><p>Example:</p><ol><li>User enter “5” hours</li></ol><p>2. Streamlit collects the input and creates a one-row DataFrame</p><p>3. Trained model makes a prediction by using the learned linear relationship</p><p>4. Predicted score appears on screen</p><p>A few important details:</p><ul><li>st.title() displays the page heading.</li><li>st.number_input() creates a numeric input field.</li><li>st.button() creates the button the user clicks.</li><li>model.predict(input_data) sends the input to the trained model.</li><li>:.2f formats the result to two decimal places.</li></ul><p>We also use a Pandas DataFrame for the prediction input, with the same feature name (hours) used during training. This helps keep the input format consistent.</p><h3>Step 7 Create requirements.txt</h3><p>Streamlit Community Cloud needs to know which packages to install when deploying your project.</p><p>Open requirements.txt and add:</p><pre>streamlit<br>scikit-learn<br>pandas<br>joblib</pre><p>Save the file. You don’t need to include Python’s built-in modules because they are already available.</p><h3>Step 8 Run the application locally</h3><p>Before deploying online, test everything on your own computer.</p><p>Run:</p><pre>streamlit run app.py</pre><p>Streamlit should start a local server and provide a URL, usually:</p><p><a href="http://localhost:8501/">http://localhost:8501</a></p><p>Open that URL in your browser.</p><p>You should see the Exam Score Predictor interface. Enter a number of study hours and click Predict Score.</p><p>Example of the app interface</p><p>Interactive mock-up of the deployed experience.</p><h3>Check for common errors</h3><p>If the app does not start, check these points:</p><ul><li>FileNotFoundError — you probably haven&#39;t run python train_model.py, or model.joblib is not in the expected folder.</li><li>ModuleNotFoundError — activate your virtual environment and install the missing package.</li><li>Feature-name warning — ensure you pass a DataFrame with the column name hours, as shown in the code.</li><li>Command not recognized — try python -m streamlit run app.py instead.</li></ul><h3>Step 9 Upload your project to GitHub</h3><p>To deploy the application, we’ll put the project on GitHub and connect the repository to Streamlit Community Cloud.</p><p>If you don’t already have an account, create one at <a href="http://github.com/">GitHub</a>.</p><h3>9.1 Create a repository</h3><ol><li>Sign in to GitHub.</li><li>Click New repository.</li><li>Name it linear-regression-streamlit.</li><li>Choose Public for the simplest deployment workflow.</li><li>Click Create repository.</li></ol><h3>9.2 Upload your project files</h3><p>Upload these four files to the repository:</p><ol><li>app.py</li></ol><p>2. train_model.py</p><p>3. model.joblib</p><p>4. requirements.txt</p><p>You can use Git from your terminal instead of uploading files manually. If Git is installed, run these commands from your project directory:</p><pre>git init<br>git add app.py train_model.py model.joblib requirements.txt<br>git commit -m &quot;Build linear regression Streamlit app&quot;<br>git branch -M main<br>git remote add origin https://github.com/YOUR_USERNAME/linear-regression-streamlit.git<br>git push -u origin main</pre><p>Replace YOUR_USERNAME with your GitHub username. If Git asks you to authenticate, follow GitHub&#39;s authentication instructions.</p><p>For this introductory project, commit the generated model file as well as the source code. That way, Streamlit Cloud can load the trained model directly.</p><h3>Step 10 Deploy on Streamlit Community Cloud</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U0PWsaNnrZphklmb" /></figure><p><a href="https://medium.com/the-streamlit-teacher/5-steps-to-build-a-data-web-app-mvp-with-python-and-streamlit-5f6abe8332d?utm_source=chatgpt.com">medium.com</a></p><p>Now comes the deployment itself.</p><ol><li>Open <a href="https://share.streamlit.io/?utm_source=chatgpt.com">Streamlit Community Cloud</a>.</li><li>Sign in using your GitHub account and authorize access when prompted.</li><li>Click Create app or the equivalent deployment option.</li><li>Select your linear-regression-streamlit repository.</li><li>Choose the main branch.</li><li>Set the main file path to app.py</li><li>Deploy the app and wait for the environment to install the required packages and start the application.</li></ol><p>If the deployment succeeds, Streamlit will give you a public URL similar in format to:</p><p><a href="https://your-app-name.streamlit.app/">https://your-app-name.streamlit.app</a></p><p>The actual URL will be assigned by the platform. You can share it with other people so they can use your application without installing Python.</p><p>For current deployment instructions, see the official <a href="https://docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app?utm_source=chatgpt.com">Streamlit deployment guide</a>.</p><h3>Step 11 Understand what happens when you deploy</h3><p>It’s important to understand that deployment is not the same as training a model.</p><p>For this project, the model does not retrain whenever someone enters new study hours. It simply uses the parameters learned during training.</p><h3>Step 12 What you should improve next</h3><p>This is a good first deployment exercise, but it is not yet a rigorous machine learning project. Our dataset is tiny and artificially created, and the model’s predictions are only meaningful within the limits of that data.</p><p>Once you’ve deployed it successfully, I’d recommend improving it in this order:</p><ol><li>Model evaluation: split the dataset into training and testing sets and evaluate performance on unseen data.</li><li>Visualization: display the original observations and fitted regression line using a chart.</li><li>Model persistence: keep training and inference separate, and retrain whenever the underlying dataset changes.</li><li>Input validation: prevent misleading predictions outside the model’s supported range.</li><li>Real-world data: replace the sample data with a legitimate dataset relevant to the problem you’re solving.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96f50479d50f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Data Structures and Functions: A Beginner’s Guide with Practical Examples]]></title>
            <link>https://medium.com/@akalumheemmanuel/python-data-structures-and-functions-a-beginners-guide-with-practical-examples-b5f4edcf49e7?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5f4edcf49e7</guid>
            <category><![CDATA[tutorial-python]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 12:59:32 GMT</pubDate>
            <atom:updated>2026-10-21T12:57:29.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9IWGAwQqxrCT7DVVGHCEQ.png" /></figure><p>Learning Python is an important step toward becoming a programmer, data analyst, or data scientist. However, writing effective Python code requires more than understanding variables and data types. You also need to know how to organize information, manipulate collections of data, and write reusable code.</p><p>In this lesson, we will explore four essential Python data structures — <strong>lists, dictionaries, tuples, and sets</strong> — before learning how to create and use functions. We will conclude with a practical mini-project: building a Student Grade Analyzer.</p><p>Whether you are learning Python for data analysis, software development, or automation, these concepts will help you write cleaner, more efficient, and more maintainable code.</p><h3>Learning Objectives</h3><p>By the end of this lesson, you should be able to:</p><ul><li>Understand and use Python’s four core data structures.</li><li>Access, modify, and manipulate collections of data.</li><li>Apply built-in functions to perform common operations.</li><li>Define and call reusable functions with parameters and return values.</li><li>Combine data structures and functions to solve a practical problem.</li></ul><h3>1. Understanding Python Data Structures</h3><p>A data structure is a way of organizing and storing information so that it can be accessed and manipulated efficiently.</p><p>Imagine you are working on a data analysis project. You might need to store daily temperatures, customer records, geographic coordinates, or a collection of unique product categories. Each situation requires a suitable way to organize the data.</p><p>Python provides four particularly useful built-in data structures:</p><ul><li><strong>Lists:</strong> Ordered, changeable collections of items.</li><li><strong>Dictionaries:</strong> Collections of key-value pairs.</li><li><strong>Tuples:</strong> Ordered collections that cannot be changed after creation.</li><li><strong>Sets:</strong> Collections of unique items.</li></ul><p>Understanding when and how to use each structure is fundamental to writing effective Python programs.</p><h3>2. Lists: Ordered and Mutable Collections</h3><p>A list is an ordered collection of items. Think of it as a shopping list, a column in a spreadsheet, or a collection of daily temperatures.</p><p>Lists are <em>mutable</em>, meaning you can add, remove, or modify their elements after creating them. They can also contain duplicate values and different data types.</p><h3>Creating a list</h3><p>Let’s create a list containing daily temperatures:</p><pre>temperatures = [22.1, 24.5, 19.8, 27.3, 25.0]</pre><pre>print(temperatures)</pre><p>Output:</p><pre>[22.1, 24.5, 19.8, 27.3, 25.0]</pre><h3>Accessing list elements with indexing</h3><p>Python uses zero-based indexing, which means the first element is at index 0, the second at index 1, and so on.</p><pre>print(temperatures[0])   # 22.1<br>print(temperatures[2])   # 19.8<br>print(temperatures[-1])  # 25.0</pre><p>Negative indexing allows you to access elements from the end of the list. For example, -1 refers to the last element, while -2 refers to the second-to-last element.</p><h3>Extracting elements with slicing</h3><p>Slicing allows you to retrieve a portion of a list without changing the original list.</p><pre>print(temperatures[1:4])</pre><p>Output:</p><pre>[24.5, 19.8, 27.3]</pre><p>The slice temperatures[1:4] starts at index 1 and stops before index 4. The stopping index is excluded.</p><h3>Modifying a list</h3><p>Python provides several methods for modifying lists.</p><pre>temperatures.append(23.6)<br>temperatures.insert(0, 20.0)<br>temperatures.remove(19.8)<br>temperatures.sort()</pre><pre>print(temperatures)</pre><p>Here is what each operation does:</p><ul><li>append() adds an item to the end of the list.</li><li>insert() adds an item at a specified position.</li><li>remove() removes the first occurrence of a specified value.</li><li>sort() arranges the list in ascending order by default.</li></ul><p>Because these operations modify the original list, the order in which you perform them matters.</p><h3>Useful built-in functions for lists</h3><p>Python also provides built-in functions that make working with numerical data easier.</p><pre>temperatures = [22.1, 24.5, 19.8, 27.3, 25.0]</pre><pre>print(len(temperatures))  # 5<br>print(min(temperatures))  # 19.8<br>print(max(temperatures))  # 27.3<br>print(sum(temperatures))  # 118.7</pre><p>These functions return the number of elements, the smallest value, the largest value, and the sum of the values, respectively.</p><p><strong>When should you use lists?</strong></p><p>Use lists when you need an ordered collection that may change over time, such as sales figures, survey responses, product names, or measurements collected during an experiment.</p><h3>3. Dictionaries: Organizing Data with Key-Value Pairs</h3><p>A dictionary stores information as key-value pairs. Think of it as a real dictionary: you look up a word to find its definition.</p><p>In Python, a key identifies a value. Dictionaries are especially useful for representing structured records, such as customers, students, employees, and products.</p><h3>Creating a dictionary</h3><p>onsider the following customer record:</p><pre>customer = {<br>    &quot;name&quot;: &quot;Emmanuel&quot;,<br>    &quot;age&quot;: 32,<br>    &quot;city&quot;: &quot;Lagos&quot;,<br>    &quot;purchases&quot;: 15,<br>    &quot;vip&quot;: True<br>}</pre><p>Each key describes a particular attribute of the customer, while its associated value stores the information.</p><p>For example, &quot;name&quot; is a key, and &quot;Emmanuel&quot; is its value.</p><h3>Accessing dictionary values</h3><p>You can retrieve a value by specifying its key.</p><pre>print(customer[&quot;name&quot;])  # Emmanuel<br>print(customer[&quot;city&quot;])  # Lagos</pre><p>However, attempting to access a missing key using square brackets raises a KeyError.</p><p>The get() method provides a safer alternative when a key may not exist.</p><pre>print(customer.get(&quot;email&quot;, &quot;N/A&quot;))</pre><p>Output:</p><pre>N/A</pre><p>Since the dictionary does not contain an &quot;email&quot; key, Python returns the default value &quot;N/A&quot; instead of raising a KeyError.</p><h3>Adding and updating information</h3><p>Dictionaries are mutable, so you can add new key-value pairs or update existing values.</p><pre>customer[&quot;email&quot;] = &quot;em@example.com&quot;<br>customer[&quot;purchases&quot;] += 1</pre><pre>print(customer[&quot;email&quot;])<br>print(customer[&quot;purchases&quot;])</pre><p>The first statement adds an email address. The second increases the customer’s purchase count from 15 to 16.</p><h3>Iterating through a dictionary</h3><p>Sometimes, you need to examine every field in a record. The items() method allows you to access both keys and values.</p><pre>for key, value in customer.items():<br>    print(f&quot;{key}: {value}&quot;)</pre><p>This loop prints each field and its corresponding value.</p><h3>Checking whether a key exists</h3><p>You can use the in operator to check whether a key is present in a dictionary.</p><pre>print(&quot;city&quot; in customer)   # True<br>print(&quot;country&quot; in customer)  # False</pre><p>By default, membership checks on dictionaries look for keys, not values.</p><p><strong>When should you use dictionaries?</strong></p><p>Use dictionaries when data has meaningful labels or identifiers. They are ideal for customer profiles, configuration settings, student records, API responses, and other structured information.</p><h3>4. Tuples and Sets: Two More Useful Data Structures</h3><p>Lists and dictionaries are useful in many situations, but Python also provides tuples and sets for more specialized tasks.</p><h3>4.1 Tuples: Ordered Collections That Cannot Be Changed</h3><p>A tuple is an ordered collection similar to a list, but its elements cannot be reassigned, added, or removed after the tuple is created.</p><p>Tuples are useful for storing values that belong together and should remain fixed.</p><p>For example, geographic coordinates can be represented as a tuple:</p><pre>coordinates = (6.5244, 3.3792)</pre><pre>lat, lon = coordinates</pre><pre>print(lat)<br>print(lon)</pre><p>Output:</p><pre>6.5244<br>3.3792</pre><p>The coordinates represent a latitude and longitude pair associated with Lagos.</p><p>The statement lat, lon = coordinates demonstrates <em>tuple unpacking</em>. Python assigns the first value to lat and the second to lon.</p><p>You can access tuple elements using indexing, just as you would with a list:</p><pre>print(coordinates[0])  # 6.5244<br>print(coordinates[1])  # 3.3792</pre><p>However, trying to modify an element will raise a TypeError:</p><pre>coordinates[0] = 7.0  # TypeError</pre><p>Remember that a tuple’s immutability prevents changes to its elements, although a tuple can contain a mutable object whose contents may still change.</p><h3>4.2 Sets: Collections of Unique Values</h3><p>A set is a collection that stores unique elements. Duplicate values are automatically removed.</p><p>Sets are particularly useful when cleaning data, comparing groups, or identifying distinct categories.</p><p>Consider the following example:</p><pre>tags = {&quot;python&quot;, &quot;data&quot;, &quot;python&quot;, &quot;science&quot;}</pre><pre>print(tags)</pre><p>The set contains only three unique values: &quot;python&quot;, &quot;data&quot;, and &quot;science&quot;.</p><p>The order of the elements is not guaranteed, so you should not rely on a particular display order.</p><h3>Set operations</h3><p>One of the most powerful features of sets is their ability to compare collections using mathematical operations.</p><p>Suppose two groups of students attend different training sessions:</p><pre>group_a = {&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;}<br>group_b = {&quot;Bob&quot;, &quot;Diana&quot;, &quot;Alice&quot;}</pre><p><strong>Intersection: Find common elements</strong></p><pre>print(group_a &amp; group_b)</pre><p>Output:</p><pre>{&#39;Alice&#39;, &#39;Bob&#39;}</pre><p>The intersection identifies students who belong to both groups.</p><p><strong>Union: Combine unique elements</strong></p><pre>print(group_a | group_b)</pre><p>The union returns all unique students appearing in either group.</p><p><strong>Difference: Find elements present in one group but not the other</strong></p><pre>print(group_a - group_b)</pre><p>Output:</p><pre>{&#39;Charlie&#39;}</pre><p>This operation identifies students who belong to group_a but not group_b.</p><p>These operations can be useful in data cleaning, comparing customer lists, identifying overlapping survey responses, and finding missing or unique records.</p><h3>5. Python Functions: Writing Reusable Code</h3><p>A function is a named, reusable block of code designed to perform a particular task.</p><p>Imagine following a recipe. Once you understand the steps, you can repeat the process whenever you need it. You can also use different ingredients while following the same instructions.</p><p>Functions work in a similar way. You define the instructions once and call the function whenever you need them.</p><p>Functions help you:</p><ul><li>Reduce repeated code.</li><li>Break large problems into smaller tasks.</li><li>Make programs easier to read and maintain.</li><li>Test individual parts of a program more easily.</li></ul><h3>5.1 Defining a function</h3><p>In Python, you define a function using the def keyword.</p><p>Let’s create a function that calculates Body Mass Index (BMI):</p><pre>def calculate_bmi(weight_kg, height_m):<br>    &quot;&quot;&quot;<br>    Calculate Body Mass Index.<br><br>    Args:<br>        weight_kg: Weight in kilograms.<br>        height_m: Height in metres.<br><br>    Returns:<br>        BMI rounded to one decimal place.<br>    &quot;&quot;&quot;<br>    bmi = weight_kg / (height_m ** 2)<br>    return round(bmi, 1)</pre><p>Let’s examine the main components:</p><ul><li>def tells Python that you are defining a function.</li><li>calculate_bmi is the function&#39;s name.</li><li>weight_kg and height_m are parameters that receive input values.</li><li>The function body contains the instructions to execute.</li><li>return sends the calculated result back to the code that called the function.</li><li>The docstring explains the function’s purpose and its inputs and output.</li></ul><p>The expression height_m ** 2 squares the height, while round(bmi, 1) rounds the result to one decimal place.</p><h3>5.2 Calling a function</h3><p>Defining a function does not execute its body. To run it, you must call it.</p><pre>my_bmi = calculate_bmi(70, 1.75)</pre><pre>print(f&quot;BMI: {my_bmi}&quot;)</pre><p>Output:</p><pre>BMI: 22.9</pre><p>Here, 70 and 1.75 are arguments passed to the function. Python assigns them to weight_kg and height_m, calculates the BMI, and returns the result.</p><p>The returned value is then stored in my_bmi.</p><h3>5.3 Understanding parameters and arguments</h3><p>Although people sometimes use these terms interchangeably, they have different meanings:</p><ul><li><strong>Parameters</strong> are the variable names defined in the function declaration.</li><li><strong>Arguments</strong> are the actual values supplied when calling the function.</li></ul><p>For example:</p><pre>def greet(name):<br>    return f&quot;Hello, {name}!&quot;</pre><pre>print(greet(&quot;Alice&quot;))</pre><p>In this example, name is a parameter, while &quot;Alice&quot; is an argument.</p><h3>5.4 Using default parameters</h3><p>Python allows you to assign default values to parameters. These values are used when the caller does not provide an alternative.</p><pre>def greet(name, language=&quot;English&quot;):<br>    if language == &quot;English&quot;:<br>        return f&quot;Hello, {name}!&quot;<br>    elif language == &quot;French&quot;:<br>        return f&quot;Bonjour, {name}!&quot;<br>    else:<br>        return f&quot;Language not supported: {language}&quot;</pre><p>Now we can call the function in different ways:</p><pre>print(greet(&quot;Alice&quot;))<br>print(greet(&quot;Marie&quot;, &quot;French&quot;))<br>print(greet(&quot;David&quot;, &quot;Spanish&quot;))</pre><p>Output:</p><pre>Hello, Alice!<br>Bonjour, Marie!<br>Language not supported: Spanish</pre><p>The first call uses the default language, English. The second supplies French explicitly, while the third demonstrates how the function handles an unsupported language.</p><p>Default parameters make functions more flexible without requiring callers to supply every argument.</p><h3>5.5 Built-in functions and modules</h3><p>Python includes many built-in functions that you can use without importing anything.</p><p>Some examples include:</p><ul><li>len() — returns the number of items in a collection.</li><li>sum() — calculates the sum of numeric values.</li><li>min() — returns the smallest value.</li><li>max() — returns the largest value.</li><li>round() — rounds a number to a specified precision.</li><li>sorted() — returns a new sorted list from an iterable.</li></ul><p>For example:</p><pre>scores = [85, 92, 76, 88, 95]</pre><pre>print(&quot;Number of students:&quot;, len(scores))<br>print(&quot;Average score:&quot;, sum(scores) / len(scores))<br>print(&quot;Highest score:&quot;, max(scores))<br>print(&quot;Lowest score:&quot;, min(scores))<br>print(&quot;Sorted scores:&quot;, sorted(scores))</pre><p>A <em>module</em> is a Python file containing reusable code, such as functions and variables. Python’s standard library includes modules that provide additional capabilities.</p><p>For example, the statistics module provides functions for calculating statistical measures.</p><pre>import statistics</pre><pre>scores = [85, 92, 76, 88, 95]</pre><pre>print(statistics.mean(scores))<br>print(statistics.median(scores))</pre><p>Output:</p><pre>87.2<br>88</pre><p>Using existing functions and modules allows you to solve problems without implementing every operation from scratch.</p><h3>6. Mini-Project: Building a Student Grade Analyzer</h3><p>Now let’s combine what we have learned to build a practical program.</p><p>Imagine you are a teacher who wants to analyze student performance. You have a collection of student names and their scores, and you need to calculate the class average, identify the highest and lowest scores, compare each student with the class average, and assign letter grades.</p><p>Our program will use a dictionary to store student records and functions to organize the calculations.</p><h3>Project requirements</h3><p>The program should:</p><ol><li>Store students and their scores in a dictionary.</li><li>Calculate the class average.</li><li>Identify the highest and lowest scores.</li><li>Determine which students scored above or below the class average.</li><li>Assign letter grades according to a defined grading scale.</li></ol><p>The grading scale is:</p><p>Score: 90–100 Grade A</p><p>Score: 80–89 Grade B</p><p>Score: 70–79 Grade C</p><p>Score: 60–69 Grade D</p><p>Score: Below 60 Grade F</p><p>For this example, we assume that all scores are numeric, there is at least one student, and each score falls between 0 and 100.</p><h3>Step 1: Store the student data</h3><p>We begin by creating a dictionary in which each student’s name is a key and their score is the corresponding value.</p><pre>students = {<br>    &quot;Alice&quot;: 92,<br>    &quot;Bob&quot;: 74,<br>    &quot;Carol&quot;: 88,<br>    &quot;David&quot;: 61,<br>    &quot;Eve&quot;: 95,<br>    &quot;Frank&quot;: 78<br>}</pre><p>A dictionary is suitable here because each score is associated with a specific student.</p><h3>Step 2: Create a function to assign grades</h3><p>Instead of repeating grading conditions throughout the program, we can place them inside a dedicated function.</p><pre>def assign_grade(score):<br>    if score &gt;= 90:<br>        return &quot;A&quot;<br>    elif score &gt;= 80:<br>        return &quot;B&quot;<br>    elif score &gt;= 70:<br>        return &quot;C&quot;<br>    elif score &gt;= 60:<br>        return &quot;D&quot;<br>    else:<br>        return &quot;F&quot;</pre><p>The function checks the score against each threshold and returns the appropriate letter grade.</p><p>For example:</p><pre>print(assign_grade(92))  # A<br>print(assign_grade(74))  # C<br>print(assign_grade(55))  # F</pre><h3>Step 3: Create a function to analyze the class</h3><p>Next, we create a function that processes the dictionary and prints a summary of the results.</p><pre>def analyze_grades(students):<br>    if not students:<br>        print(&quot;No student records available.&quot;)<br>        return<br><br>    scores = list(students.values())<br>    average = sum(scores) / len(scores)<br><br>    print(f&quot;Class Average: {average:.1f}&quot;)<br>    print(f&quot;Highest Score: {max(scores)}&quot;)<br>    print(f&quot;Lowest Score: {min(scores)}&quot;)<br>    print()<br><br>    for name, score in students.items():<br>        grade = assign_grade(score)<br><br>        if score &gt; average:<br>            status = &quot;Above average&quot;<br>        elif score &lt; average:<br>            status = &quot;Below average&quot;<br>        else:<br>            status = &quot;Equal to average&quot;<br><br>        print(<br>            f&quot;{name:&lt;12} {score:&gt;5}  &quot;<br>            f&quot;Grade: {grade}  ({status})&quot;<br>        )</pre><p>Let’s understand how this function works.</p><p><strong>First, it checks whether the dictionary is empty.</strong></p><p>If no student records are available, the function displays a message and stops. This prevents division by zero when calculating the average.</p><p><strong>Second, it extracts the scores.</strong></p><pre>scores = list(students.values())</pre><p>The values() method retrieves the dictionary&#39;s scores, while list() converts them into a list.</p><p><strong>Third, it calculates the class average.</strong></p><pre>average = sum(scores) / len(scores)</pre><p>The sum of the scores is divided by the number of students.</p><p><strong>Fourth, it identifies the highest and lowest scores.</strong></p><pre>max(scores)<br>min(scores)</pre><p>These built-in functions make it easy to find the maximum and minimum values.</p><p><strong>Finally, it processes each student.</strong></p><pre>for name, score in students.items():</pre><p>The loop retrieves each student’s name and score. It then calls assign_grade() to determine the letter grade and compares the score with the class average.</p><p>The formatted output uses :&lt;12 to left-align student names within a 12-character field and :&gt;5 to right-align scores within a five-character field.</p><h3>Step 4: Run the program</h3><p>Now we can call the function using our student dictionary.</p><pre>students = {<br>    &quot;Alice&quot;: 92,<br>    &quot;Bob&quot;: 74,<br>    &quot;Carol&quot;: 88,<br>    &quot;David&quot;: 61,<br>    &quot;Eve&quot;: 95,<br>    &quot;Frank&quot;: 78<br>}</pre><pre>analyze_grades(students)</pre><p>Expected output:</p><pre>Class Average: 81.3<br>Highest Score: 95<br>Lowest Score: 61</pre><pre>Alice           92  Grade: A  (Above average)<br>Bob             74  Grade: C  (Below average)<br>Carol           88  Grade: B  (Above average)<br>David           61  Grade: D  (Below average)<br>Eve             95  Grade: A  (Above average)<br>Frank           78  Grade: C  (Below average)</pre><h3>What have we accomplished?</h3><p>Our program demonstrates how different Python concepts work together:</p><ul><li>A <strong>dictionary</strong> stores each student’s name and score.</li><li>A <strong>list</strong> holds the scores for numerical calculations.</li><li>Built-in functions calculate the average, maximum, and minimum.</li><li>The assign_grade() function handles the grading logic.</li><li>The analyze_grades() function organizes the analysis and output.</li><li>A for loop processes each student individually.</li><li>Conditional statements determine whether each score is above, below, or equal to the class average.</li></ul><p>This is an example of breaking a larger problem into smaller, reusable tasks. As your programs grow, this approach becomes increasingly important.</p><h3>7. Practice Exercises</h3><p>The best way to understand programming is to write code yourself. Try these exercises before moving on to the next lesson.</p><p><strong>Exercise 1: List manipulation</strong></p><p>Create a list containing five numbers. Then:</p><ul><li>Add a new number to the list.</li><li>Remove one existing number.</li><li>Sort the list in ascending order.</li><li>Print the number of elements, the smallest value, the largest value, and the sum.</li></ul><p><strong>Exercise 2: Dictionary operations</strong></p><p>Create a dictionary representing a product, with keys for its name, price, category, and stock quantity.</p><ul><li>Print the product’s name and price.</li><li>Increase the stock quantity.</li><li>Add a new key called &quot;supplier&quot;.</li><li>Check whether the key &quot;discount&quot; exists.</li></ul><p><strong>Exercise 3: Tuple and set operations</strong></p><p>Create two sets containing the names of students enrolled in two different courses.</p><ul><li>Find the students enrolled in both courses.</li><li>Find all unique students enrolled in either course.</li><li>Identify students enrolled in the first course but not the second.</li></ul><p><strong>Exercise 4: Function practice</strong></p><p>Write a function called calculate_discount(price, discount_percent) that calculates and returns the discounted price.</p><p>For example, a product costing 10,000 with a 15% discount should have a final price of 8,500.</p><p><strong>Exercise 5: Extend the Student Grade Analyzer</strong></p><p>Improve the mini-project by adding the following features:</p><ul><li>Display only students who scored above the class average.</li><li>Count how many students received each letter grade.</li><li>Calculate the percentage of students who passed, assuming a passing score of 60.</li><li>Validate that every score falls between 0 and 100.</li></ul><p>Try implementing these features using functions instead of placing all the logic inside one large block of code.</p><h3>In Summary</h3><p>Python data structures and functions are essential building blocks for writing effective programs.</p><p>Lists help you manage ordered collections of data. Dictionaries organize information into meaningful key-value pairs. Tuples provide ordered collections that cannot be modified, while sets help you work with unique values and compare groups efficiently.</p><p>Functions take these capabilities further by allowing you to package logic into reusable, well-organized blocks of code. Combined with built-in functions and standard library modules, they make it easier to solve problems without unnecessarily repeating instructions.</p><p>The Student Grade Analyzer demonstrates how these concepts can work together in a practical application. More importantly, it shows that even a useful data analysis program can be built by breaking a problem into smaller, manageable steps.</p><p><strong>Your next step:</strong> Complete the practice exercises, experiment with the code, and modify the Student Grade Analyzer to suit your own ideas. The more you practise, the more naturally these Python concepts will become part of your problem-solving toolkit.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5f4edcf49e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python input() Function: From Beginner to Advanced (With Practical Examples)]]></title>
            <link>https://medium.com/@akalumheemmanuel/python-input-function-from-beginner-to-advanced-with-practical-examples-028545d8ff8d?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/028545d8ff8d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 09:00:14 GMT</pubDate>
            <atom:updated>2026-10-14T09:00:14.005Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how a Python program receives information from a user?</p><p>Imagine building a program that asks for a student’s name, calculates examination scores, checks a person’s age, or accepts a customer’s order. Instead of hardcoding every value into your program, you can allow users to provide information while the program is running.</p><p>This is where Python’s input() function becomes useful.</p><p>The input() function is one of the first concepts every Python beginner should learn because it introduces user interaction. It allows your programs to receive information, process it, and respond accordingly.</p><p>In this tutorial, we will explore Python’s input() function from beginner to advanced level. You will learn how to collect user input, convert data types, perform calculations, validate information, handle errors, work with loops and lists, use functions, and build a practical ATM simulator.</p><p>By the end of this lesson, you should be able to create interactive Python programs that accept user input and handle it correctly.</p><p>Let’s get started.</p><h3>1. What Is the input() Function?</h3><p>The input() function pauses program execution and waits for the user to enter information.</p><p>Consider this example:</p><pre>name = input(&quot;What is your name? &quot;)</pre><pre>print(name)</pre><p>When you run the program, Python displays a prompt:</p><pre>What is your name? Rachel<br>Rachel</pre><p>Let’s break it down step by step.</p><p><strong>Step 1: Ask a question</strong></p><pre>input(&quot;What is your name? &quot;)</pre><p>Python displays the message and waits for the user to type a response.</p><p><strong>Step 2: Receive the response</strong></p><p>The user types Rachel and presses Enter.</p><p><strong>Step 3: Store the response</strong></p><pre>name = input(&quot;What is your name? &quot;)</pre><p>The assignment stores the text returned by input() in the variable name.</p><p><strong>Step 4: Display the result</strong></p><pre>print(name)</pre><p>Python displays the stored value.</p><p>One important detail: input() does not automatically store the user&#39;s answer in a variable. You must assign the returned value to a variable if you want to use it later.</p><p>For example:</p><pre>input(&quot;Enter your name: &quot;)</pre><p>This still asks the user for a name, but the program does not retain the returned value for later use.</p><p>The general syntax is:</p><pre>variable = input(&quot;Prompt message: &quot;)</pre><p>Here, the variable stores the response, while the prompt tells the user what information to enter.</p><h3>2. Beginner Level: Using input() with Strings</h3><p>A string is a sequence of characters used to represent text. Names, addresses, usernames, and favourite colours are common examples.</p><p>The most important rule to remember is that <strong>input() always returns a string</strong>, regardless of what the user types.</p><h3>Example 1: Asking for a name</h3><pre>name = input(&quot;Enter your name: &quot;)</pre><pre>print(&quot;Hello&quot;, name)</pre><p>Suppose the user enters Emmanuel.</p><p>Output:</p><pre>Enter your name: Emmanuel<br>Hello Emmanuel</pre><p>Python stores the response in name and displays a greeting.</p><h3>Example 2: Asking for multiple details</h3><p>You can use several input() calls to collect different pieces of information.</p><pre>name = input(&quot;Enter your name: &quot;)<br>city = input(&quot;Which city do you live in? &quot;)<br>hobby = input(&quot;What is your hobby? &quot;)</pre><pre>print(&quot;Name:&quot;, name)<br>print(&quot;City:&quot;, city)<br>print(&quot;Hobby:&quot;, hobby)</pre><p>Suppose the user enters:</p><pre>Enter your name: Emmanuel<br>Which city do you live in? Ibadan<br>What is your hobby? Coding</pre><p>The program displays:</p><pre>Name: Emmanuel<br>City: Ibadan<br>Hobby: Coding</pre><p>Each response is stored in a separate variable, allowing the program to use the information independently.</p><h3>Example 3: Combining input with string concatenation</h3><p>Python allows you to combine strings using the + operator.</p><pre>first_name = input(&quot;Enter your first name: &quot;)<br>last_name = input(&quot;Enter your last name: &quot;)</pre><pre>full_name = first_name + &quot; &quot; + last_name</pre><pre>print(&quot;Your full name is &quot; + full_name)</pre><p>If the user enters Emmanuel and Akalumhe, the output is:</p><pre>Your full name is Emmanuel Akalumh</pre><p>The &quot; &quot; adds a space between the two names.</p><p>You can also use an f-string, which is often easier to read:</p><pre>first_name = input(&quot;First name: &quot;)<br>last_name = input(&quot;Last name: &quot;)</pre><pre>print(f&quot;Your full name is {first_name} {last_name}&quot;)</pre><p>Both approaches work. F-strings become particularly useful when you need to combine variables with descriptive text.</p><h3>3. Understanding the Difference Between input() and print()</h3><p>The input() and print() functions serve different purposes.</p><p>FunctionPurposeExampleinput()Receives information from the username = input(&quot;Name: &quot;)print()Displays information on the screenprint(name)</p><p>Think of it this way:</p><ul><li>input() allows your program to ask questions and receive responses.</li><li>print() allows your program to display information.</li></ul><p>You can use both functions in the same program.</p><pre>food = input(&quot;What is your favourite food? &quot;)</pre><pre>print(&quot;Your favourite food is&quot;, food)<br>print(&quot;That sounds delicious!&quot;)</pre><p>If the user enters Jollof rice, the output is:</p><pre>What is your favourite food? Jollof rice<br>Your favourite food is Jollof rice<br>That sounds delicious!</pre><p>The first print() uses the user&#39;s response, while the second displays a fixed message.</p><p>Together, these functions provide the foundation for interactive command-line applications.</p><h3>4. Beginner Level: Using input() with Numbers</h3><p>This is where many Python beginners encounter their first type-related error.</p><p>Suppose you want to ask a user for their age and add five years to it.</p><p>You might write:</p><pre>age = input(&quot;Enter your age: &quot;)</pre><pre>print(age + 5)</pre><p>If the user enters 20, Python raises a TypeError.</p><p>Why?</p><p>Because input() returns the string &quot;20&quot;, not the integer 20. Python cannot directly add a string to an integer.</p><p>To solve this problem, we need to convert the input into the appropriate numeric type.</p><h3>A. Using int()</h3><p>The int() function converts suitable values into integers, which are whole numbers.</p><pre>age = int(input(&quot;Enter your age: &quot;))</pre><pre>print(age + 5)</pre><p>If the user enters 20, the output is:</p><pre>25</pre><p>Let’s examine the expression:</p><pre>age = int(input(&quot;Enter your age: &quot;))</pre><p>Python processes the expression from the inside out:</p><ol><li>input() asks for the user&#39;s age and receives text such as &quot;20&quot;.</li><li>int() converts the string &quot;20&quot; into the integer 20.</li><li>The assignment stores the resulting integer in age.</li></ol><p>This allows Python to perform mathematical operations on the value.</p><h3>B. Using float()</h3><p>The float() function converts suitable values into floating-point numbers, which can represent decimal values.</p><pre>price = float(input(&quot;Enter the price: &quot;))</pre><pre>print(price)</pre><p>If the user enters 1500.50, Python stores the value as a float.</p><p>You can now perform calculations with it:</p><pre>price = float(input(&quot;Enter the price: &quot;))<br>quantity = int(input(&quot;Enter the quantity: &quot;))</pre><pre>total = price * quantity</pre><pre>print(f&quot;Total cost: ₦{total:,.2f}&quot;)</pre><p>If the price is 1500.50 and the quantity is 3, the output is:</p><pre>Total cost: ₦4,501.50</pre><h3>C. Comparing common conversion functions</h3><p>FunctionInput or argumentResultTypeinput()User enters 25&quot;25&quot;strint()&quot;25&quot;25intfloat()&quot;25.5&quot;25.5floatstr()25&quot;25&quot;str</p><p>You can verify the data type using type().</p><pre>age = input(&quot;Enter your age: &quot;)</pre><pre>print(type(age))</pre><p>Even if the user enters 25, the output is:</p><pre>&lt;class &#39;str&#39;&gt;</pre><p>Now compare that with:</p><pre>age = int(input(&quot;Enter your age: &quot;))</pre><pre>print(type(age))</pre><p>Output:</p><pre>&lt;class &#39;int&#39;&gt;</pre><p><strong>Remember:</strong> input() receives text. Use int() or float() when you need numeric calculations or numeric comparisons.</p><h3>5. Performing Calculations with User Input</h3><p>Once you understand type conversion, you can create programs that perform calculations using values supplied by the user.</p><h3>Example 1: Adding two numbers</h3><pre>num1 = int(input(&quot;Enter the first number: &quot;))<br>num2 = int(input(&quot;Enter the second number: &quot;))</pre><pre>total = num1 + num2</pre><pre>print(&quot;The total is:&quot;, total)</pre><p>Suppose the user enters 10 and 15.</p><p>Output:</p><pre>Enter the first number: 10<br>Enter the second number: 15<br>The total is: 25</pre><p>The program converts both inputs to integers before adding them.</p><h3>Example 2: Building a simple calculator</h3><pre>num1 = float(input(&quot;Enter the first number: &quot;))<br>num2 = float(input(&quot;Enter the second number: &quot;))</pre><pre>print(&quot;Addition:&quot;, num1 + num2)<br>print(&quot;Subtraction:&quot;, num1 - num2)<br>print(&quot;Multiplication:&quot;, num1 * num2)</pre><pre>if num2 != 0:<br>    print(&quot;Division:&quot;, num1 / num2)<br>else:<br>    print(&quot;Cannot divide by zero.&quot;)</pre><p>If the user enters 20 and 4, the output is:</p><pre>Addition: 24.0<br>Subtraction: 16.0<br>Multiplication: 80.0<br>Division: 5.0</pre><p>Notice that the program checks whether the second number is zero before performing division.</p><p>Dividing a number by zero raises a ZeroDivisionError, so this validation prevents that particular error.</p><h3>Example 3: Calculating the average of three scores</h3><pre>score1 = float(input(&quot;Enter score 1: &quot;))<br>score2 = float(input(&quot;Enter score 2: &quot;))<br>score3 = float(input(&quot;Enter score 3: &quot;))</pre><pre>average = (score1 + score2 + score3) / 3</pre><pre>print(&quot;Average score:&quot;, average)</pre><p>The parentheses ensure that Python adds the three scores before dividing the total by three.</p><p>This example assumes the user enters valid numbers. Later, we will learn how to handle invalid input.</p><h3>6. Intermediate Level: Combining input() with Conditionals</h3><p>The input() function becomes especially powerful when combined with conditional statements.</p><p>Instead of using fixed values, your program can ask users for information and make decisions based on their responses.</p><h3>Example 1: Checking age eligibility</h3><pre>age = int(input(&quot;Enter your age: &quot;))</pre><pre>if age &gt;= 18:<br>    print(&quot;You are eligible.&quot;)<br>else:<br>    print(&quot;You are not eligible.&quot;)</pre><p>If the user enters 16, the program prints:</p><pre>You are not eligible.</pre><p>If the user enters 22, it prints:</p><pre>You are eligible.</pre><p>This example combines input, type conversion, comparison operators, and conditional logic.</p><h3>Example 2: Grading a student</h3><pre>score = float(input(&quot;Enter your score: &quot;))</pre><pre>if score &lt; 0 or score &gt; 100:<br>    print(&quot;Invalid score.&quot;)<br>elif score &gt;= 70:<br>    print(&quot;Grade A&quot;)<br>elif score &gt;= 60:<br>    print(&quot;Grade B&quot;)<br>elif score &gt;= 50:<br>    print(&quot;Grade C&quot;)<br>elif score &gt;= 45:<br>    print(&quot;Grade D&quot;)<br>else:<br>    print(&quot;Grade F&quot;)</pre><p>The program performs two tasks:</p><ol><li>It checks whether the score is within the permitted range.</li><li>If the score is valid, it assigns a grade.</li></ol><p>The order of the conditions matters because Python executes the first matching branch.</p><h3>Example 3: Checking a username</h3><pre>username = input(&quot;Enter your username: &quot;)</pre><pre>if username == &quot;admin&quot;:<br>    print(&quot;Welcome, administrator!&quot;)<br>else:<br>    print(&quot;Welcome, user!&quot;)</pre><p>No numeric conversion is needed because usernames are strings.</p><h3>Example 4: Creating a simple men</h3><pre>print(&quot;1. Check balance&quot;)<br>print(&quot;2. Deposit money&quot;)<br>print(&quot;3. Withdraw money&quot;)</pre><pre>choice = input(&quot;Choose an option: &quot;)</pre><pre>if choice == &quot;1&quot;:<br>    print(&quot;Checking balance...&quot;)<br>elif choice == &quot;2&quot;:<br>    print(&quot;Depositing money...&quot;)<br>elif choice == &quot;3&quot;:<br>    print(&quot;Withdrawing money...&quot;)<br>else:<br>    print(&quot;Invalid option.&quot;)</pre><p>The program compares the user’s selection with strings such as &quot;1&quot; and &quot;2&quot;.</p><p>This is correct because input() returns strings.</p><p>You could convert the choice to an integer, but doing so is unnecessary for this example.</p><h3>7. Handling Invalid Input with try and except</h3><p>What happens when a program expects a number but the user enters text?</p><p>Consider this example:</p><pre>age = int(input(&quot;Enter your age: &quot;))</pre><p>If the user enters twenty, Python cannot convert that string into an integer. It raises a ValueError.</p><p>Without error handling, the program terminates with an error message.</p><p>We can make the program more robust using try and except.</p><h3>Example: Handling invalid numeric input</h3><pre>try:<br>    age = int(input(&quot;Enter your age: &quot;))<br>    print(&quot;Your age is:&quot;, age)</pre><pre>except ValueError:<br>    print(&quot;Invalid input. Please enter a whole number.&quot;)</pre><p>If the user enters 25, the program prints:</p><pre>Your age is: 25</pre><p>If the user enters twenty, it prints:</p><pre>Invalid input. Please enter a whole number.</pre><h3>How does it work?</h3><ol><li>Python attempts to execute the statements inside try.</li><li>If the conversion succeeds, the program continues normally.</li><li>If the conversion raises a ValueError, Python skips the remaining statements in the try block and executes the matching except block.</li></ol><p>This allows the program to handle predictable input errors without crashing.</p><h3>A more complete example: Validating a score</h3><pre>try:<br>    score = float(input(&quot;Enter your score: &quot;))</pre><pre>    if not 0 &lt;= score &lt;= 100:<br>        print(&quot;Score must be between 0 and 100.&quot;)<br>    else:<br>        print(&quot;Your score is:&quot;, score)</pre><pre>except ValueError:<br>    print(&quot;Please enter a valid number.&quot;)</pre><p>This program handles two different situations.</p><ul><li>A non-numeric value, such as hello, causes a ValueError.</li><li>A numeric value outside the allowed range, such as 150, fails the validation condition.</li></ul><p>These are different problems and should be handled separately.</p><p><strong>Important:</strong> Exception handling does not replace validation. A value can be a valid number and still be unacceptable for your application.</p><h3>8. Intermediate Level: Validating Input with Loops</h3><p>A try-except block can handle invalid input, but it does not automatically ask the user to try again.</p><p>A while loop allows us to repeat the process until the user enters acceptable information.</p><h3>Example: Keep asking until a valid age is entered</h3><pre>while True:<br>    try:<br>        age = int(input(&quot;Enter your age: &quot;))</pre><pre>        if age &lt; 0:<br>            print(&quot;Age cannot be negative.&quot;)<br>            continue</pre><pre>        print(&quot;Your age is:&quot;, age)<br>        break</pre><pre>    except ValueError:<br>        print(&quot;Please enter a whole number.&quot;)</pre><p>Let’s examine the important parts.</p><ul><li>while True creates a loop that continues until it is interrupted.</li><li>try attempts to convert the input into an integer.</li><li>continue skips the remaining statements in the current iteration and starts another iteration.</li><li>break exits the loop when a valid, non-negative age is supplied.</li><li>except ValueError handles text that cannot be converted into an integer.</li></ul><p>For example:</p><pre>Enter your age: twenty<br>Please enter a whole number.<br>Enter your age: -5<br>Age cannot be negative.<br>Enter your age: 24<br>Your age is: 24</pre><p>The program keeps asking until the user enters a non-negative integer.</p><p>This pattern is valuable when building forms, command-line applications, data-entry tools, and interactive programs.</p><h3>9. Using input() with Loops and Lists</h3><p>Sometimes you need to collect several values from the user rather than just one.</p><p>Python lists allow you to store multiple values in a single collection.</p><h3>Example 1: Collecting three student names</h3><pre>students = []</pre><pre>for i in range(3):<br>    name = input(&quot;Enter a student name: &quot;)<br>    students.append(name)</pre><pre>print(&quot;Students:&quot;, students)</pre><p>If the user enters Rachel, David, and Sarah, the output is:</p><pre>Students: [&#39;Rachel&#39;, &#39;David&#39;, &#39;Sarah&#39;]</pre><p>Here’s what happens:</p><ol><li>students = [] creates an empty list.</li><li>range(3) makes the loop run three times.</li><li>input() collects one name during each iteration.</li><li>append() adds the name to the list.</li><li>print() displays the completed list.</li></ol><h3>Example 2: Collecting scores and calculating an average</h3><pre>scores = []</pre><pre>for i in range(3):<br>    score = float(input(&quot;Enter a score: &quot;))<br>    scores.append(score)</pre><pre>average = sum(scores) / len(scores)</pre><pre>print(&quot;Scores:&quot;, scores)<br>print(&quot;Average:&quot;, average)</pre><p>This example introduces three useful operations:</p><ul><li>append() adds a value to a list.</li><li>sum(scores) adds all the numbers in the list.</li><li>len(scores) counts the number of items.</li></ul><p>The example assumes all three inputs are valid numbers. A production-ready version should also handle invalid entries.</p><h3>Example 3: Collecting an unknown number of values</h3><p>You can let users decide when they have finished entering data.</p><pre>numbers = []</pre><pre>while True:<br>    entry = input(<br>        &quot;Enter a number or type &#39;done&#39; to finish: &quot;<br>    ).strip()</pre><pre>    if entry.lower() == &quot;done&quot;:<br>        break</pre><pre>    try:<br>        number = float(entry)<br>        numbers.append(number)</pre><pre>    except ValueError:<br>        print(&quot;Invalid number. Try again.&quot;)</pre><pre>print(&quot;Numbers:&quot;, numbers)</pre><pre>if numbers:<br>    print(&quot;Total:&quot;, sum(numbers))<br>    print(&quot;Average:&quot;, sum(numbers) / len(numbers))<br>else:<br>    print(&quot;No numbers were entered.&quot;)</pre><p>This program combines several concepts:</p><ul><li>User input.</li><li>String methods.</li><li>Conditional statements.</li><li>Exception handling.</li><li>Lists and loops.</li><li>Mathematical calculations.</li></ul><p>The if numbers: check is particularly important.</p><p>If the user types done immediately, the list remains empty. Calculating an average by dividing by len(numbers) would then cause a division-by-zero error.</p><p>Checking whether the list contains values prevents that problem.</p><h3>10. Advanced Level: Understanding Input and Variable Types</h3><p>Understanding data types becomes increasingly important as your programs grow more complex.</p><p>A value may look numeric to a human but still be represented as text in Python.</p><h3>Example 1: Why does &quot;10&quot; + &quot;20&quot; produce &quot;1020&quot;?</h3><p>Consider this program:</p><pre>number1 = input(&quot;Enter a number: &quot;)<br>number2 = input(&quot;Enter another number: &quot;)</pre><pre>print(number1 + number2)</pre><p>Suppose the user enters 10 and 20.</p><p>Output:</p><pre>1020</pre><p>Why doesn’t Python calculate 30?</p><p>Because both inputs are strings. When + is used with strings, it joins them together rather than performing numerical addition.</p><p>Now convert the inputs to integers:</p><pre>number1 = int(input(&quot;Enter a number: &quot;))<br>number2 = int(input(&quot;Enter another number: &quot;))</pre><pre>print(number1 + number2)</pre><p>Output:</p><pre>30</pre><p>This distinction is fundamental when working with user input.</p><h3>Example 2: Why comparing numeric strings can be misleading</h3><p>Consider this example:</p><pre>age1 = input(&quot;Enter the first age: &quot;)<br>age2 = input(&quot;Enter the second age: &quot;)</pre><pre>print(age1 &gt; age2)</pre><p>Suppose the inputs are &quot;9&quot; and &quot;20&quot;.</p><p>The result is:</p><pre>True</pre><p>This may seem incorrect because nine is less than twenty.</p><p>However, Python is comparing strings lexicographically rather than comparing their numeric values. The first character, &quot;9&quot;, comes after &quot;2&quot; in character ordering.</p><p>To compare the ages numerically, convert them to integers:</p><pre>age1 = int(input(&quot;Enter the first age: &quot;))<br>age2 = int(input(&quot;Enter the second age: &quot;))</pre><pre>print(age1 &gt; age2)</pre><p>Now the result is:</p><pre>False</pre><p><strong>Rule:</strong> If you intend to perform mathematical operations or numeric comparisons, convert user input to the appropriate numeric type first.</p><h3>11. Using input() Inside Functions</h3><p>Functions allow you to organize code into reusable blocks.</p><p>You can place input() inside a function, or collect input outside a function and pass the resulting value into it.</p><p>Both approaches are valid, but they serve slightly different purposes.</p><h3>Example A: Collecting input inside a function</h3><pre>def greet_user():<br>    name = input(&quot;Enter your name: &quot;)<br>    print(f&quot;Hello, {name}!&quot;)</pre><pre>greet_user()</pre><p>When greet_user() is called, the function asks for the user&#39;s name and displays a greeting.</p><p>This is convenient for small interactive programs.</p><h3>Example B: Passing user input into a function</h3><pre>def greet_user(name):<br>    print(f&quot;Hello, {name}!&quot;)</pre><pre>username = input(&quot;Enter your name: &quot;)</pre><pre>greet_user(username)</pre><p>This version separates input collection from the greeting logic.</p><p>The function receives a value through its parameter instead of requesting the input itself.</p><p>This separation is often preferable in larger applications because the function can be reused with different names without requiring additional user interaction.</p><h3>Example C: Returning a calculated value</h3><pre>def calculate_total(price, quantity):<br>    return price * quantity<br></pre><pre>price = float(input(&quot;Enter the price of one item: &quot;))<br>quantity = int(input(&quot;Enter the quantity: &quot;))</pre><pre>total = calculate_total(price, quantity)</pre><pre>print(f&quot;Total cost: ₦{total:,.2f}&quot;)</pre><p>Suppose the user enters a price of 2500 and a quantity of 4.</p><p>Output:</p><pre>Total cost: ₦10,000.00</pre><p>The function receives the values as arguments, calculates the total, and returns the result.</p><p>It does not need to collect input itself.</p><p>This makes the function easier to test, reuse, and maintain.</p><h3>12. Advanced Level: Using String Methods to Clean User Input</h3><p>User input is not always formatted consistently.</p><p>Someone might enter YES instead of yes, or include unnecessary spaces before a name.</p><p>Python provides string methods that help normalize and clean text.</p><h3>A. Using .strip()</h3><p>The .strip() method removes whitespace from the beginning and end of a string.</p><pre>name = input(&quot;Enter your name: &quot;).strip()</pre><pre>print(f&quot;Hello, {name}!&quot;)</pre><p>If the user enters a name with extra spaces around it, .strip() removes those surrounding spaces.</p><p>It does not remove spaces between words.</p><h3>B. Using .lower()</h3><p>The .lower() method converts text to lowercase.</p><pre>answer = input(&quot;Do you want to continue? &quot;).strip().lower()</pre><pre>if answer == &quot;yes&quot;:<br>    print(&quot;Continuing...&quot;)<br>else:<br>    print(&quot;Stopping...&quot;)</pre><p>This accepts responses such as YES, Yes, and yes as equivalent after normalization.</p><p>However, the program treats every response other than yes as a reason to stop. We can make the logic more precise.</p><pre>answer = input(&quot;Do you want to continue? &quot;).strip().lower()</pre><pre>if answer == &quot;yes&quot;:<br>    print(&quot;Continuing...&quot;)<br>elif answer == &quot;no&quot;:<br>    print(&quot;Exiting...&quot;)<br>else:<br>    print(&quot;Please enter yes or no.&quot;)</pre><p>Now the program distinguishes between recognized answers and invalid responses.</p><h3>C. Using .upper()</h3><p>The .upper() method converts text to uppercase.</p><pre>country = input(&quot;Enter your country: &quot;).strip().upper()</pre><pre>print(country)</pre><p>If the user enters nigeria, the result is:</p><pre>NIGERIA</pre><p>This can be useful when standardizing codes or text values.</p><h3>D. Using .title()</h3><p>The .title() method capitalizes the beginning of words.</p><pre>name = input(&quot;Enter your name: &quot;).strip().title()</pre><pre>print(name)</pre><p>For an input such as emmanuel akalumhe, the output is:</p><pre>Emmanuel Akalumhe</pre><p>Be careful when applying .title() automatically to names. It does not preserve every person&#39;s preferred spelling, capitalization, or naming convention.</p><p>The broader lesson is that cleaning input should reflect the needs of your application rather than blindly changing every value.</p><h3>13. Practical Project: Build a Simple ATM Simulator</h3><p>Now let’s combine the concepts we have learned into a practical project.</p><p>We will build a basic ATM simulator that can:</p><ul><li>Ask the user for a PIN.</li><li>Allow up to three authentication attempts.</li><li>Display a menu after successful authentication.</li><li>Check the account balance.</li><li>Process withdrawals.</li><li>Reject invalid withdrawal amounts.</li><li>Handle invalid numeric input.</li></ul><p>This is a learning project, not a real banking system.</p><h3>Complete Python code</h3><pre>balance = 50000.0<br>correct_pin = &quot;1234&quot;<br>attempts = 0<br>authenticated = False</pre><pre># Authentication<br>while attempts &lt; 3:<br>    pin = input(&quot;Enter your PIN: &quot;)</pre><pre>    if pin == correct_pin:<br>        authenticated = True<br>        break</pre><pre>    attempts += 1<br>    print(&quot;Incorrect PIN.&quot;)</pre><pre># Check whether authentication succeeded<br>if not authenticated:<br>    print(&quot;Too many attempts. Access denied.&quot;)</pre><pre>else:<br>    # ATM menu<br>    while True:<br>        print(&quot;\n--- ATM MENU ---&quot;)<br>        print(&quot;1. Check balance&quot;)<br>        print(&quot;2. Withdraw money&quot;)<br>        print(&quot;3. Exit&quot;)</pre><pre>        choice = input(&quot;Choose an option: &quot;).strip()</pre><pre>        if choice == &quot;1&quot;:<br>            print(f&quot;Balance: ₦{balance:,.2f}&quot;)</pre><pre>        elif choice == &quot;2&quot;:<br>            try:<br>                amount = float(<br>                    input(&quot;Enter withdrawal amount: &quot;)<br>                )</pre><pre>                if amount &lt;= 0:<br>                    print(&quot;Amount must be greater than zero.&quot;)</pre><pre>                elif amount &gt; balance:<br>                    print(&quot;Insufficient funds.&quot;)</pre><pre>                else:<br>                    balance -= amount<br>                    print(&quot;Withdrawal successful.&quot;)<br>                    print(f&quot;New balance: ₦{balance:,.2f}&quot;)</pre><pre>            except ValueError:<br>                print(&quot;Enter a valid amount.&quot;)</pre><pre>        elif choice == &quot;3&quot;:<br>            print(&quot;Thank you for using the ATM.&quot;)<br>            break</pre><pre>        else:<br>            print(&quot;Invalid option.&quot;)</pre><h3>How the project works</h3><p><strong>1. Authentication</strong></p><p>The first loop gives the user up to three attempts to enter the correct PIN.</p><p><strong>2. Access control</strong></p><p>If all three attempts fail, the program denies access.</p><p><strong>3. Menu system</strong></p><p>After successful authentication, an inner loop repeatedly displays the ATM menu until the user selects Exit.</p><p><strong>4. Conditional branching</strong></p><p>The if-elif-else structure determines which action corresponds to the selected menu option.</p><p><strong>5. Input validation</strong></p><p>The withdrawal logic rejects amounts that are zero or negative and amounts greater than the available balance.</p><p><strong>6. Exception handling</strong></p><p>The try-except block handles input that cannot be converted into a floating-point number.</p><p>One important detail is that the PIN is stored as a string rather than an integer. This allows a PIN such as &quot;0123&quot; to retain its leading zero.</p><p>For a real financial application, PINs must not be stored in plaintext. Authentication, balances, and transactions must be secured, and financial operations require safeguards against errors, unauthorized access, and concurrent updates.</p><p>The purpose of this project is to practise input handling and program flow, not to implement real banking security.</p><h3>14. Practice Exercises: Test Yourself</h3><p>The best way to learn Python is to write code yourself.</p><p>Try solving the following exercises before checking the suggested solutions.</p><h3>Exercise 1: Create a personal greeting</h3><p>Ask the user for their name and age. Display a greeting that includes both values.</p><p><strong>Hint:</strong> Use two input() calls and an f-string. Remember that the age is initially a string.</p><h3>Exercise 2: Add two numbers</h3><p>Ask the user to enter two whole numbers and print their sum.</p><p><strong>Hint:</strong> Convert each input using int() before adding them.</p><h3>Exercise 3: Build an age checker</h3><p>Ask the user to enter their age.</p><ul><li>Print Minor if the age is below 18.</li><li>Print Adult otherwise.</li><li>Handle non-numeric input.</li><li>Reject negative ages.</li></ul><p><strong>Hint:</strong> Combine int(), conditional statements, and try-except.</p><h3>Exercise 4: Create a shopping calculator</h3><p>Ask the user to enter an item’s price and quantity.</p><p>Calculate the total cost and apply a 10% discount if the total is at least ₦50,000.</p><p><strong>Hint:</strong> Use float() for the price, int() for the quantity, and an if statement to determine whether the discount applies.</p><h3>Exercise 5: Collect numbers repeatedly</h3><p>Keep asking the user to enter numbers until they type done.</p><p>At the end, display the sum of all valid numbers entered. Invalid entries should not crash the program.</p><p><strong>Hint:</strong> Use a list, while True, break, float(), and try-except.</p><h3>15. Suggested Solutions to the Exercises</h3><p>Attempt the exercises independently before reading this section. Comparing your solution with the examples can help you identify alternative approaches.</p><h3>Solution 1: Personal greeting</h3><pre>name = input(&quot;Enter your name: &quot;).strip()<br>age = input(&quot;Enter your age: &quot;).strip()</pre><pre>print(f&quot;Hello, {name}! You are {age} years old.&quot;)</pre><p>This simple version displays the age as entered. To validate the age numerically, you would convert it to an integer and handle invalid input.</p><h3>Solution 2: Adding two numbers</h3><pre>num1 = int(input(&quot;Enter the first number: &quot;))<br>num2 = int(input(&quot;Enter the second number: &quot;))</pre><pre>print(&quot;Sum:&quot;, num1 + num2)</pre><p>The int() conversions ensure that Python performs numerical addition instead of joining two strings.</p><h3>Solution 3: Age checker</h3><pre>try:<br>    age = int(input(&quot;Enter your age: &quot;))</pre><pre>    if age &lt; 0:<br>        print(&quot;Age cannot be negative.&quot;)<br>    elif age &lt; 18:<br>        print(&quot;Minor&quot;)<br>    else:<br>        print(&quot;Adult&quot;)</pre><pre>except ValueError:<br>    print(&quot;Please enter a valid whole number.&quot;)</pre><p>This solution handles both invalid text and negative ages.</p><h3>Solution 4: Shopping calculator</h3><pre>try:<br>    price = float(input(&quot;Enter the item price: ₦&quot;))<br>    quantity = int(input(&quot;Enter the quantity: &quot;))</pre><pre>    if price &lt; 0 or quantity &lt;= 0:<br>        print(&quot;Enter a non-negative price and a positive quantity.&quot;)</pre><pre>    else:<br>        total = price * quantity</pre><pre>        if total &gt;= 50000:<br>            discount = total * 0.10<br>        else:<br>            discount = 0</pre><pre>        final_total = total - discount</pre><pre>        print(f&quot;Original total: ₦{total:,.2f}&quot;)<br>        print(f&quot;Discount: ₦{discount:,.2f}&quot;)<br>        print(f&quot;Final total: ₦{final_total:,.2f}&quot;)</pre><pre>except ValueError:<br>    print(&quot;Please enter a valid price and whole-number quantity.&quot;)</pre><p>The program validates the price and quantity, calculates the original total, and applies the discount when the threshold is reached.</p><p>For a real financial application, monetary calculations are generally better handled with Python’s Decimal type to avoid floating-point rounding issues.</p><h3>Solution 5: Repeated number collection</h3><pre>numbers = []</pre><pre>while True:<br>    entry = input(<br>        &quot;Enter a number or type &#39;done&#39; to finish: &quot;<br>    ).strip()</pre><pre>    if entry.lower() == &quot;done&quot;:<br>        break</pre><pre>    try:<br>        numbers.append(float(entry))</pre><pre>    except ValueError:<br>        print(&quot;Invalid number. Try again.&quot;)</pre><pre>if numbers:<br>    print(&quot;Numbers:&quot;, numbers)<br>    print(&quot;Sum:&quot;, sum(numbers))<br>else:<br>    print(&quot;No valid numbers were entered.&quot;)</pre><p>This program continues collecting numbers until the user enters done. Invalid entries are rejected without terminating the loop.</p><p>If no valid numbers are collected, the program displays an appropriate message rather than attempting an unnecessary calculation.</p><h3>16. Your Python Learning Roadmap</h3><p>Here is a recommended sequence for mastering the input() function.</p><p><strong>Stage 1: Beginner</strong></p><p>Learn how to ask questions, store responses in variables, display results, and understand that input() returns strings.</p><p><strong>Stage 2: Basic calculations</strong></p><p>Practise converting input with int() and float(). Use these values to perform arithmetic and numeric comparisons.</p><p><strong>Stage 3: Intermediate programming</strong></p><p>Combine input with conditional statements, comparison operators, logical operators, and menu systems.</p><p><strong>Stage 4: Building robust programs</strong></p><p>Learn to handle invalid input with try-except, validate values with conditions, and repeat requests using loops.</p><p><strong>Stage 5: Advanced techniques</strong></p><p>Practise collecting lists of data, normalizing strings, writing reusable functions, and separating input collection from program logic.</p><p><strong>Stage 6: Practical projects</strong></p><p>Build a calculator, student grading system, shopping calculator, registration form, or ATM simulator.</p><p>The more you combine these concepts in small projects, the more comfortable you will become with writing interactive programs.</p><h3>Conclusion</h3><p>Python’s input() function may look simple, but it is an essential building block for interactive applications.</p><p>It allows programs to receive information, perform calculations, validate data, make decisions, and respond to users.</p><p>In this lesson, we progressed from basic input collection to more advanced programming techniques.</p><p>We explored:</p><ul><li>Collecting user input with input().</li><li>Understanding strings and converting values with int() and float().</li><li>Performing calculations with user-supplied data.</li><li>Combining input with conditional statements.</li><li>Handling invalid input using try-except.</li><li>Validating data with loops.</li><li>Collecting multiple values in lists.</li><li>Comparing strings and numeric values correctly.</li><li>Using functions to organize interactive programs.</li><li>Cleaning text with string methods.</li><li>Building a practical ATM simulator.</li></ul><p>The most important lesson is this: <strong>Python receives user input as text first. Converting that text into the appropriate data type is a separate step.</strong></p><p>Once you understand this distinction, working with user input becomes much easier.</p><p>Do not stop at reading the examples. Run the code, change the values, deliberately enter invalid information, and observe how your program responds.</p><p>Programming becomes much easier when you learn to experiment, identify errors, and improve your solutions.</p><p><strong>Your next step:</strong> Complete the five exercises, then build a small interactive application of your own. Start simple, add validation, and gradually introduce more advanced features.</p><p>Happy coding!</p><p><em>If you found this tutorial helpful, consider following for more practical Python lessons, beginner-friendly explanations, and hands-on programming projects.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=028545d8ff8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Conditionals]]></title>
            <link>https://medium.com/@akalumheemmanuel/python-conditionals-30ebcbd4608b?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/30ebcbd4608b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 08:31:52 GMT</pubDate>
            <atom:updated>2026-10-14T08:31:52.132Z</atom:updated>
            <content:encoded><![CDATA[<p>Python is more than a language for storing data and performing calculations. It is a language that allows us to build programs capable of making decisions.</p><p>Imagine a banking application that checks whether a customer has enough money before approving a withdrawal. Consider a school management system that determines whether a student has passed an examination. Think about a website that grants access only when a user enters the correct password.</p><p>All these systems rely on conditional logic.</p><p>In Python, <strong>conditional statements allow a program to make decisions based on whether a condition is true or false.</strong></p><p>Here, we will explore Python conditionals from the fundamentals to more advanced concepts, including logical operators, nested conditions, truthy and falsy values, operator precedence, short-circuit evaluation, and guard clauses.</p><p>By the end of this lesson, you should be able to write conditional logic for real-world applications and understand how Python evaluates complex decisions.</p><h3>1. Understanding the Fundamentals of Conditionals</h3><p>Before writing conditional statements, it is important to understand three basic concepts.</p><ul><li><strong>Condition:</strong> A question or test that evaluates to True or False.</li><li><strong>Decision:</strong> The action a program takes depending on the result of a condition.</li><li><strong>Code block:</strong> A group of instructions that execute together when a particular condition is satisfied.</li></ul><p>Consider this example:</p><pre>age = 20<br><br>if age &gt;= 18:<br>    print(&quot;You are an adult.&quot;)<br>Output:<br>You are an adult</pre><p>Let’s break down what happens.</p><p><strong>Step 1: Store a value</strong></p><pre>age = 20</pre><p>Python stores the integer 20 in a variable called age.</p><p><strong>Step 2: Check the condition</strong></p><pre>age &gt;= 18</pre><p>Python checks whether age is greater than or equal to 18.</p><p>Since 20 is greater than 18, the condition evaluates to True.</p><p><strong>Step 3: Execute the code block</strong></p><p>Because the condition is true, Python executes:</p><pre>print(&quot;You are an adult.&quot;)</pre><p>Two important details are worth remembering:</p><ol><li>A colon (:) follows the condition.</li><li>The code inside the conditional block must be indented.</li></ol><p>Python uses indentation to determine which statements belong to a conditional block. Incorrect indentation can cause an IndentationError or change the program&#39;s behavior.</p><h3>2. The if Statement</h3><p>The if statement tells Python to execute a block of code only when a specified condition is true.</p><p>Its basic structure is:</p><pre>if condition:<br>    # Execute this code if the condition is True</pre><h3>Example 1: Checking a student’s score</h3><pre>score = 75</pre><pre>if score &gt;= 50:<br>    print(&quot;You passed!&quot;)</pre><p><strong>Output:</strong></p><pre>You passed!</pre><p>Python checks whether the student’s score is at least 50. Since the score is 75, the condition is true, and the message is printed.</p><p>Now change the score:</p><pre>score = 35</pre><pre>if score &gt;= 50:<br>    print(&quot;You passed!&quot;)</pre><p><strong>Output:</strong></p><p>There is no output.</p><p>Why? Because 35 &gt;= 50 evaluates to False. Python skips the indented block.</p><p>An if statement does not automatically execute an alternative action when its condition is false. To handle both possibilities, we need an else statement.</p><h3>Example 2: Checking eligibility by age</h3><pre>age = 16</pre><pre>if age &gt;= 18:<br>    print(&quot;You are eligible to register.&quot;)</pre><p>Since the age is below 18, Python prints nothing.</p><p>This behavior is useful when an action should happen only under specific circumstances.</p><h3>3. Understanding Comparison Operators</h3><p>Comparison operators compare two values and return a Boolean result: either True or False.</p><p>Python provides six common comparison operators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ksgAOVreQV4g4lUt4Ec1AA.png" /></figure><p>==Equal to5 == 5True!=Not equal to5 != 3True&gt;Greater than8 &gt; 5True&lt;Less than2 &lt; 5True&gt;=Greater than or equal to5 &gt;= 5True&lt;=Less than or equal to3 &lt;= 2False</p><p>Let’s try a few examples:</p><pre>a = 10<br>b = 20<br><br>print(a == b)<br>print(a != b)<br>print(a &lt; b)<br>print(a &gt; b)<br>print(b &gt;= 20)<br>print(a &lt;= 10)</pre><p><strong>Output:</strong></p><pre>False<br>True<br>True<br>False<br>True<br>True</pre><h3>A common beginner mistake: = versus ==</h3><p>These two operators serve different purposes.</p><p>The assignment operator (=) stores a value in a variable:</p><pre>score = 80</pre><p>The equality operator (==) compares two values:</p><pre>print(score == 80)</pre><p><strong>Output:</strong></p><pre>True</pre><p>Remember: use = to assign values and == to compare them.</p><h3>4. The if-else Statement</h3><p>What if you want your program to perform one action when a condition is true and another when it is false?</p><p>Use if-else.</p><p>The structure is:</p><pre>if condition:<br>    # Runs if the condition is True<br>else:<br>    # Runs if the condition is False</pre><h3>Example: Pass or fail</h3><pre>score = 40</pre><pre>if score &gt;= 50:<br>    print(&quot;You passed!&quot;)<br>else:<br>    print(&quot;You failed.&quot;)</pre><p><strong>Output:</strong></p><pre>You failed.</pre><p>Python evaluates score &gt;= 50. Since the result is false, it skips the if block and executes the else block.</p><p>Only one of these two branches executes.</p><h3>Practical example: ATM withdrawal</h3><p>Suppose a customer wants to withdraw money from a bank account.</p><pre>balance = 50000<br>withdrawal = 15000</pre><pre>if withdrawal &lt;= balance:<br>    balance -= withdrawal<br>    print(&quot;Withdrawal successful.&quot;)<br>    print(f&quot;Remaining balance: ₦{balance}&quot;)<br>else:<br>    print(&quot;Insufficient funds.&quot;)</pre><p><strong>Output:</strong></p><pre>Withdrawal successful.<br>Remaining balance: ₦35000</pre><p>The program checks whether the requested withdrawal is affordable before deducting the money.</p><p>However, this example handles only the balance check. A real banking application would also validate the withdrawal amount, authenticate the customer, and apply additional security controls.</p><p>We will revisit validation in later sections.</p><h3>5. The if-elif-else Statement</h3><p>Sometimes a program must choose among more than two possible outcomes.</p><p>For example, a school grading system might assign different grades based on examination scores.</p><p>Python provides elif, which means &quot;else if&quot;, to handle multiple conditions.</p><h3>Example: A grading system</h3><pre>score = 85<br><br>if score &gt;= 70:<br>    print(&quot;Grade A&quot;)<br>elif score &gt;= 60:<br>    print(&quot;Grade B&quot;)<br>elif score &gt;= 50:<br>    print(&quot;Grade C&quot;)<br>elif score &gt;= 45:<br>    print(&quot;Grade D&quot;)<br>else:<br>    print(&quot;Grade F&quot;)</pre><p><strong>Output:</strong></p><pre>Grade A</pre><h3>How Python evaluates the conditions</h3><p>Python evaluates the conditions from top to bottom.</p><ol><li>Is score &gt;= 70? Yes.</li><li>Print Grade A.</li><li>Skip the remaining elif and else branches.</li></ol><p><strong>The key rule is that Python executes the first matching branch in an </strong><strong>if-elif-else chain.</strong></p><h3>Why the order of conditions matters</h3><p>Consider this incorrect grading logic:</p><pre>score = 85</pre><pre>if score &gt;= 50:<br>    print(&quot;Grade C&quot;)<br>elif score &gt;= 70:<br>    print(&quot;Grade A&quot;)<br>else:<br>    print(&quot;Grade F&quot;)</pre><p><strong>Output:</strong></p><pre>Grade C</pre><p>Why does this happen?</p><p>Because 85 &gt;= 50 is already true. Python executes the first branch and never checks whether the score is at least 70.</p><p>The correct approach is to check higher thresholds first:</p><pre>score = 85</pre><pre>if score &gt;= 70:<br>    print(&quot;Grade A&quot;)<br>elif score &gt;= 50:<br>    print(&quot;Grade C&quot;)<br>else:<br>    print(&quot;Grade F&quot;)</pre><p><strong>Lesson:</strong> When conditions overlap, arrange them according to priority so that the most specific or highest-priority conditions are checked first.</p><h3>6. Combining Conditions with and, or, and not</h3><p>Real-world decisions often depend on multiple requirements being satisfied.</p><p>Python provides three logical operators that help us combine conditions.</p><h3>A. The and operator</h3><p>The and operator returns True only when both conditions are true.</p><p>Imagine a student must score at least 50 and maintain at least 75% attendance to qualify for an examination.</p><pre>score = 70<br>attendance = 80</pre><pre>if score &gt;= 50 and attendance &gt;= 75:<br>    print(&quot;You qualify for the examination.&quot;)<br>else:<br>    print(&quot;You do not qualify.&quot;)</pre><p><strong>Output:</strong></p><pre>You qualify for the examination.</pre><p>Both conditions are satisfied.</p><p>Now consider the following truth table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*3-MtMT5m7eoP51372CpD2A.png" /></figure><p>If either condition is false, the combined condition is false.</p><h3>B. The or operator</h3><p>The or operator returns True when at least one condition is true.</p><p>Suppose a student qualifies for a special award if their examination score is at least 90 or their project score is at least 95.</p><pre>exam_score = 75<br>project_score = 98</pre><pre>if exam_score &gt;= 90 or project_score &gt;= 95:<br>    print(&quot;You qualify for the special award.&quot;)<br>else:<br>    print(&quot;You do not qualify.&quot;)</pre><p><strong>Output:</strong></p><pre>You qualify for the special award.</pre><p>The examination score does not meet the requirement, but the project score does. One true condition is sufficient.</p><h3>C. The not operator</h3><p>The not operator reverses a Boolean result.</p><pre>is_raining = False</pre><pre>if not is_raining:<br>    print(&quot;You can go outside.&quot;)<br>else:<br>    print(&quot;Take an umbrella.&quot;)</pre><p><strong>Output:</strong></p><pre>You can go outside.</pre><p>Since is_raining is false, not is_raining evaluates to true.</p><h3>Combining all three operators</h3><p>Suppose a system grants access only when a user is at least 18, has identification, and is not suspended.</p><pre>age = 25<br>has_id = True<br>is_suspended = False</pre><pre>if age &gt;= 18 and has_id and not is_suspended:<br>    print(&quot;Access granted.&quot;)<br>else:<br>    print(&quot;Access denied.&quot;)</pre><p><strong>Output:</strong></p><pre>Access granted.</pre><p>The user satisfies all three requirements.</p><p>These operators are especially useful when building authentication systems, eligibility checks, validation rules, and other decision-making applications.</p><h3>7. Nested Conditionals</h3><p>A nested conditional is an if statement placed inside another if statement.</p><p>It is useful when a decision depends on an earlier decision.</p><h3>Example: Checking loan eligibility</h3><p>Suppose a simplified loan application requires an applicant to be at least 18 years old and earn at least ₦100,000 monthly.</p><pre>age = 25<br>monthly_income = 150000</pre><pre>if age &gt;= 18:<br>    if monthly_income &gt;= 100000:<br>        print(&quot;You are eligible for the loan.&quot;)<br>    else:<br>        print(&quot;Your income is too low.&quot;)<br>else:<br>    print(&quot;You must be at least 18 years old.&quot;)</pre><p><strong>Output:</strong></p><pre>You are eligible for the loan.</pre><h3>Step-by-step execution</h3><ol><li>Python checks whether age &gt;= 18.</li><li>Because the condition is true, it enters the outer block.</li><li>Python checks whether monthly_income &gt;= 100000.</li><li>That condition is also true.</li><li>Python prints the eligibility message.</li></ol><p>If the applicant is 17, Python skips the inner conditional entirely because the outer condition is false.</p><p>This illustrates an important property of nested conditionals: an inner block executes only when the program reaches it.</p><h3>A simpler alternative</h3><p>If the only requirement is to check whether both conditions are satisfied, a combined condition may be easier to read:</p><pre>if age &gt;= 18 and monthly_income &gt;= 100000:<br>    print(&quot;You are eligible for the loan.&quot;)<br>else:<br>    print(&quot;You are not eligible for the loan.&quot;)</pre><p>Use nested conditionals when different stages require different outcomes. Use combined conditions when the decision can be expressed clearly in one logical statement.</p><p>Keep nesting manageable. Excessive nesting makes programs harder to understand, test, and maintain.</p><h3>8. Checking Ranges in Python</h3><p>A range check determines whether a value falls between two limits.</p><p>For example, an examination score should fall between 0 and 100.</p><p>Python allows chained comparisons:</p><pre>score = 75</pre><pre>if 0 &lt;= score &lt;= 100:<br>    print(&quot;Valid score.&quot;)<br>else:<br>    print(&quot;Invalid score.&quot;)</pre><p><strong>Output:</strong></p><pre>Valid score.</pre><p>Python interprets the expression 0 &lt;= score &lt;= 100 as requiring both comparisons to be true.</p><p>It is equivalent to:</p><pre>0 &lt;= score and score &lt;= 100</pre><p>Chained comparisons are often easier to read.</p><h3>Example: Classifying a temperature</h3><pre>temperature = 28</pre><pre>if temperature &lt; 15:<br>    print(&quot;Cold&quot;)<br>elif temperature &lt;= 25:<br>    print(&quot;Mild&quot;)<br>elif temperature &lt;= 35:<br>    print(&quot;Warm&quot;)<br>else:<br>    print(&quot;Hot&quot;)</pre><p><strong>Output:</strong></p><pre>Warm</pre><p>The first condition is false because 28 is not below 15.</p><p>The second condition is also false because 28 is greater than 25.</p><p>The third condition is true because 28 is less than or equal to 35.</p><p>Python prints Warm and stops checking the chain.</p><p>Notice that the lower boundaries are established by the earlier branches. There is no need to write temperature &gt;= 26 in the third condition.</p><h3>9. Using the in and not in Operators</h3><p>Sometimes you need to check whether a value belongs to a collection of permitted values.</p><p>The in operator makes this straightforward.</p><h3>Example: Checking a user’s role</h3><pre>role = &quot;admin&quot;<br>allowed_roles = [&quot;admin&quot;, &quot;editor&quot;, &quot;manager&quot;]</pre><pre>if role in allowed_roles:<br>    print(&quot;You are authorized.&quot;)<br>else:<br>    print(&quot;You are not authorized.&quot;)</pre><p><strong>Output:</strong></p><pre>You are authorized.</pre><p>Python checks whether &quot;admin&quot; appears in the list.</p><h3>Checking strings</h3><p>The in operator also works with strings.</p><pre>email = &quot;student@example.com&quot;</pre><pre>if &quot;@&quot; in email:<br>    print(&quot;The email contains an @ symbol.&quot;)<br>else:<br>    print(&quot;The email is missing an @ symbol.&quot;)</pre><p><strong>Output:</strong></p><pre>The email contains an @ symbol.</pre><p>This is only a basic character check, not complete email validation.</p><h3>The not in operator</h3><p>The not in operator checks whether a value is absent from a collection.</p><pre>username = &quot;new_user&quot;<br>existing_users = [&quot;admin&quot;, &quot;john&quot;, &quot;mary&quot;]</pre><pre>if username not in existing_users:<br>    print(&quot;Username is available.&quot;)<br>else:<br>    print(&quot;Username is already taken.&quot;)</pre><p><strong>Output:</strong></p><pre>Username is available.</pre><p>Membership checks are useful for validating user roles, checking allowed commands, filtering data, and verifying whether a value appears in a list or string.</p><h3>10. Working with User Input</h3><p>Programs become more interactive when they can receive information from users.</p><p>Python’s input() function allows a program to request information through the terminal.</p><p>One important detail is that input() returns a string, even when the user enters a number.</p><h3>Example: Asking for an age</h3><pre>age = int(input(&quot;Enter your age: &quot;))</pre><pre>if age &gt;= 18:<br>    print(&quot;You are an adult.&quot;)<br>else:<br>    print(&quot;You are a minor.&quot;)</pre><p>If the user enters 22, the output is:</p><pre>Enter your age: 22<br>You are an adult.</pre><h3>What does int() do?</h3><p>Consider this expression:</p><pre>age = int(input(&quot;Enter your age: &quot;))</pre><p>It works in two stages:</p><ol><li>input() receives text from the user, such as &quot;22&quot;.</li><li>int() converts that text into the integer 22.</li></ol><p>Without the conversion, comparing the input directly with an integer would raise a TypeError.</p><p>For example:</p><pre>age = input(&quot;Enter your age: &quot;)</pre><pre>if age &gt;= 18:<br>    print(&quot;You are an adult.&quot;)</pre><p>This fails because age is a string while 18 is an integer.</p><h3>Handling invalid input with try and except</h3><p>What happens if a user enters twenty instead of 20?</p><p>The conversion with int() raises a ValueError.</p><p>We can handle this gracefully:</p><pre>try:<br>    age = int(input(&quot;Enter your age: &quot;))</pre><pre>    if age &lt; 0:<br>        print(&quot;Age cannot be negative.&quot;)<br>    elif age &gt;= 18:<br>        print(&quot;You are an adult.&quot;)<br>    else:<br>        print(&quot;You are a minor.&quot;)</pre><pre>except ValueError:<br>    print(&quot;Please enter a valid whole number.&quot;)</pre><p>Now the program handles invalid text without crashing.</p><p>This example introduces exception handling, an important concept for writing robust Python applications.</p><h3>11. Truthy and Falsy Values</h3><p>Not every condition needs a comparison operator such as &gt;, ==, or !=.</p><p>Python can evaluate certain values directly in a conditional statement.</p><p>Values that behave like True are called <strong>truthy</strong>, while values that behave like False are called <strong>falsy</strong>.</p><p>Consider this example:</p><pre>name = &quot;David&quot;</pre><pre>if name:<br>    print(&quot;Name provided.&quot;)<br>else:<br>    print(&quot;Name is missing.&quot;)</pre><p><strong>Output:</strong></p><pre>Name provided.</pre><p>The string &quot;David&quot; is non-empty, so it is truthy.</p><h3>Common truthy and falsy values</h3><p>ValueBoolean interpretationTrueTruthyFalseFalsy0Falsy1Truthy&quot;&quot;Falsy&quot;Hello&quot;Truthy[]Falsy[1, 2]Truthy{}FalsyNoneFalsy</p><p>Empty strings, lists, dictionaries, sets, and tuples are falsy. Non-empty versions of these collections are truthy.</p><h3>Example: Checking an empty string</h3><pre>username = &quot;&quot;</pre><pre>if username:<br>    print(&quot;Welcome!&quot;)<br>else:<br>    print(&quot;Please enter your username.&quot;)</pre><p><strong>Output:</strong></p><pre>Please enter your username.</pre><p>Because the string is empty, Python executes the else block.</p><h3>Checking whether a list contains items</h3><p>Suppose we have a list of students:</p><pre>students = []</pre><pre>if students:<br>    print(&quot;Students are available.&quot;)<br>else:<br>    print(&quot;No students found.&quot;)</pre><p><strong>Output:</strong></p><pre>No students found.</pre><p>This is often cleaner than writing:</p><pre>if len(students) &gt; 0:</pre><p>Both approaches work, but directly checking the list is more idiomatic when you simply want to know whether it contains items.</p><p><strong>Important distinction:</strong> Falsy does not mean invalid.</p><p>For example, zero may be a perfectly valid examination score or account balance. Whether a value is acceptable depends on the rules of your application.</p><h3>12. Conditional Expressions: A Shorter Way to Make Decisions</h3><p>Sometimes you need to choose between two values based on a condition.</p><p>Python provides a conditional expression, often called a ternary expression.</p><p>Its structure is:</p><pre>value_if_true if condition else value_if_false</pre><h3>Example: Pass or fail</h3><p>The traditional approach is:</p><pre>score = 75</pre><pre>if score &gt;= 50:<br>    result = &quot;Pass&quot;<br>else:<br>    result = &quot;Fail&quot;</pre><pre>print(result)</pre><p>The same decision can be expressed in one line:</p><pre>score = 75</pre><pre>result = &quot;Pass&quot; if score &gt;= 50 else &quot;Fail&quot;</pre><pre>print(result)</pre><p><strong>Output:</strong></p><pre>Pass</pre><p>Both versions produce the same result.</p><h3>Example: Finding the larger number</h3><pre>a = 10<br>b = 20</pre><pre>larger = a if a &gt; b else b</pre><pre>print(larger)</pre><p><strong>Output:</strong></p><pre>20</pre><p>Python evaluates a &gt; b. Since the condition is false, it chooses b.</p><p>Conditional expressions are useful for simple decisions. However, if your logic involves multiple branches or complicated calculations, regular if-elif-else statements are usually easier to read.</p><h3>13. Advanced Level: Operator Precedence</h3><p>When you combine multiple operators, Python follows rules that determine which parts of an expression are evaluated first.</p><p>Understanding operator precedence helps prevent logical errors.</p><p>Consider this example:</p><pre>age = 17<br>has_id = True</pre><pre>if age &gt;= 18 and has_id or age &gt;= 25:<br>    print(&quot;Access granted.&quot;)<br>else:<br>    print(&quot;Access denied.&quot;)</pre><p><strong>Output:</strong></p><pre>Access denied.</pre><p>Why?</p><p>Python evaluates and before or.</p><p>The condition is effectively:</p><pre>if (age &gt;= 18 and has_id) or age &gt;= 25:</pre><p>Substituting the values gives:</p><pre>if (False and True) or False:</pre><p>The final result is false.</p><p>Now consider a slightly different expression:</p><pre>age = 17<br>has_id = True</pre><pre>if age &gt;= 18 and (has_id or age &gt;= 25):<br>    print(&quot;Access granted.&quot;)<br>else:<br>    print(&quot;Access denied.&quot;)</pre><p>The output remains:</p><pre>Access denied.</pre><p>However, the logic is different. The user must be at least 18 and must either have identification or be at least 25.</p><p>The parentheses make the intended grouping explicit.</p><h3>A useful precedence order</h3><p>For the operators covered in this tutorial, remember the following order, from higher precedence to lower precedence:</p><ol><li>Parentheses: ()</li><li>Comparisons: ==, !=, &gt;, &lt;, &gt;=, &lt;=, in, not in</li><li>Logical not</li><li>Logical and</li><li>Logical or</li></ol><p>When conditions become complicated, use parentheses to make your intentions clear instead of relying entirely on memory.</p><p>Readable code is easier to debug and maintain.</p><h3>14. Advanced Level: Short-Circuit Evaluation</h3><p>Short-circuit evaluation occurs when Python stops evaluating a logical expression as soon as its final result is already determined.</p><p>This is particularly useful when the remaining part of an expression is expensive to evaluate or cannot safely be evaluated under certain circumstances.</p><h3>Short-circuiting with and</h3><p>With and, if the first condition is false, the entire expression must be false.</p><p>Therefore, Python does not need to evaluate the second condition.</p><pre>def expensive_check():<br>    print(&quot;This function was called.&quot;)<br>    return True</pre><pre>age = 16</pre><pre>if age &gt;= 18 and expensive_check():<br>    print(&quot;Access granted.&quot;)<br>else:<br>    print(&quot;Access denied.&quot;)</pre><p><strong>Output:</strong></p><pre>Access denied.</pre><p>Notice that &quot;This function was called.&quot; is not printed.</p><p>Since age &gt;= 18 is false, Python stops evaluating the expression and never calls expensive_check().</p><h3>Short-circuiting with or</h3><p>With or, if the first condition is true, the entire expression must be true.</p><pre>def expensive_check():<br>    print(&quot;This function was called.&quot;)<br>    return False</pre><pre>is_admin = True</pre><pre>if is_admin or expensive_check():<br>    print(&quot;Access granted.&quot;)<br>else:<br>    print(&quot;Access denied.&quot;)</pre><p><strong>Output:</strong></p><pre>Access granted.</pre><p>The function is not called because is_admin is already true.</p><h3>A practical safety example</h3><p>Short-circuit evaluation can help prevent errors when accessing potentially missing data.</p><pre>user = None</pre><pre>if user is not None and user[&quot;active&quot;]:<br>    print(&quot;User is active.&quot;)<br>else:<br>    print(&quot;User is unavailable or inactive.&quot;)</pre><p><strong>Output:</strong></p><pre>User is unavailable or inactive.</pre><p>The first condition, user is not None, is false. Python therefore does not evaluate user[&quot;active&quot;].</p><p>Without short-circuit evaluation, trying to access an item from None would raise a TypeError.</p><p>This technique is useful when validating data before accessing it.</p><p>However, remember that short-circuiting protects the second expression only when the first condition determines the result. If the first condition is true, Python still evaluates the second expression.</p><h3>15. Advanced Level: Guard Clauses</h3><p>A guard clause checks for an invalid, unexpected, or disqualifying situation early and exits a function before its main logic runs.</p><p>Guard clauses can reduce unnecessary nesting and make programs easier to understand.</p><h3>Example: Processing a payment</h3><p>Consider a payment-processing function that checks whether the amount is valid and whether the customer has enough money.</p><p>One approach is to use deeply nested conditionals:</p><pre>def process_payment(balance, amount):<br>    if amount &gt; 0:<br>        if balance &gt;= amount:<br>            balance -= amount<br>            print(&quot;Payment successful.&quot;)<br>            print(f&quot;Remaining balance: ₦{balance}&quot;)<br>        else:<br>            print(&quot;Insufficient funds.&quot;)<br>    else:<br>        print(&quot;Invalid payment amount.&quot;)<br></pre><pre>process_payment(50000, 15000)</pre><p><strong>Output:</strong></p><pre>Payment successful.<br>Remaining balance: ₦35000</pre><p>The code works, but as more requirements are added, the nesting can become difficult to follow.</p><h3>A cleaner approach using guard clauses</h3><pre>def process_payment(balance, amount):<br>    if amount &lt;= 0:<br>        print(&quot;Invalid payment amount.&quot;)<br>        return</pre><pre>    if balance &lt; amount:<br>        print(&quot;Insufficient funds.&quot;)<br>        return</pre><pre>    balance -= amount</pre><pre>    print(&quot;Payment successful.&quot;)<br>    print(f&quot;Remaining balance: ₦{balance}&quot;)<br></pre><pre>process_payment(50000, 15000)</pre><p><strong>Output:</strong></p><pre>Payment successful.<br>Remaining balance: ₦35000</pre><p>Let’s examine the logic.</p><ol><li>If the payment amount is zero or negative, the function prints an error and exits.</li><li>If the balance is insufficient, the function prints an error and exits.</li><li>If neither condition applies, the payment is processed.</li></ol><p>The return statement immediately exits the function.</p><p>This approach keeps the main logic at the same indentation level and makes the function easier to read.</p><p><strong>When should you use guard clauses?</strong></p><p>Use them when you want to reject invalid inputs, stop processing when a requirement is not satisfied, or prevent deeply nested conditional logic.</p><p>In larger applications, guard clauses are particularly useful in API handlers, authentication functions, payment systems, and data-processing pipelines.</p><p>Note that this example only demonstrates decision-making logic. A real payment system also requires secure transaction handling, persistent records, and safeguards against concurrent updates.</p><h3>16. Practical Project: Build a Simple Login System</h3><p>Now let’s combine several concepts into one practical project.</p><p>We will create a simple login simulation that checks a username and password, then decides whether access should be granted.</p><pre>correct_username = &quot;admin&quot;<br>correct_password = &quot;python123&quot;</pre><pre>username = input(&quot;Enter username: &quot;)<br>password = input(&quot;Enter password: &quot;)</pre><pre>if not username or not password:<br>    print(&quot;Username and password are required.&quot;)</pre><pre>elif username == correct_username and password == correct_password:<br>    print(&quot;Login successful. Welcome!&quot;)</pre><pre>else:<br>    print(&quot;Invalid username or password.&quot;)</pre><h3>Example 1: Correct credentials</h3><p>Input:</p><pre>Enter username: admin<br>Enter password: python123</pre><p>Output:</p><pre>Login successful. Welcome!</pre><h3>Example 2: Missing username</h3><p>Input:</p><pre>Enter username:<br>Enter password: python123</pre><p>Output:</p><pre>Username and password are required.</pre><h3>Example 3: Incorrect password</h3><p>Input:</p><pre>Enter username: admin<br>Enter password: wrongpass</pre><p>Output:</p><pre>Invalid username or password.</pre><h3>Concepts used in this project</h3><p>This small application demonstrates several conditional concepts:</p><ul><li>if checks whether the required fields are present.</li><li>not checks whether a value is empty.</li><li>and combines the username and password requirements.</li><li>elif handles a second decision.</li><li>else handles the remaining case.</li></ul><p>The example is for learning purposes only. Real authentication systems should never store passwords in plain text or rely on a hardcoded password. They should use secure password hashing, appropriate authentication controls, and other security measures.</p><h3>17. Practice Exercises</h3><p>The best way to understand Python conditionals is to write code yourself.</p><p>Try the following exercises before looking up solutions.</p><h3>Exercise 1: Positive, negative, or zero</h3><p>Write a program that accepts a number and determines whether it is positive, negative, or zero.</p><p>Expected behavior:</p><ul><li>If the number is greater than zero, print Positive.</li><li>If the number is less than zero, print Negative.</li><li>Otherwise, print Zero.</li></ul><h3>Exercise 2: Even or odd</h3><p>Write a program that checks whether an integer is even or odd.</p><p><em>Hint:</em> Use the modulo operator (%).</p><p>For example, 10 % 2 produces 0, while 7 % 2 produces 1.</p><h3>Exercise 3: Find the largest of three numbers</h3><p>Ask the user to enter three numbers and print the largest one.</p><p>Try solving the problem using if-elif-else.</p><p>Then consider how you might solve it using Python’s built-in max() function.</p><h3>Exercise 4: Validate an examination score</h3><p>Write a program that accepts a score and checks whether it falls between 0 and 100.</p><p>If the score is outside this range, print Invalid score.</p><p>Otherwise, assign a grade using these thresholds:</p><ul><li>70–100: Grade A</li><li>60–69: Grade B</li><li>50–59: Grade C</li><li>45–49: Grade D</li><li>0–44: Grade F</li></ul><p>Be careful with the order of the conditions.</p><h3>Exercise 5: ATM withdrawal</h3><p>Create a simple ATM withdrawal program.</p><p>Your program should:</p><ol><li>Store an account balance.</li><li>Ask the user to enter a withdrawal amount.</li><li>Reject amounts that are zero or negative.</li><li>Check whether the balance is sufficient.</li><li>Deduct the amount if the withdrawal is valid.</li><li>Display the remaining balance.</li></ol><p>Bonus challenge: Handle invalid numeric input with try and except.</p><h3>Exercise 6: Login validation</h3><p>Improve the login project by adding a maximum of three login attempts.</p><p>If the user enters the wrong credentials three times, display an account-lockout message.</p><p><em>Hint:</em> You will need a loop in addition to conditional statements.</p><h3>Exercise 7: Trading risk validation</h3><p>Imagine you are building a program that evaluates whether a proposed trade satisfies basic risk rules.</p><p>For this exercise, assume a trade is permitted only when:</p><ul><li>The trading account is active.</li><li>The proposed risk percentage is greater than zero.</li><li>The proposed risk percentage does not exceed 1% of the account.</li><li>The trading strategy has produced a valid setup.</li></ul><p>Write a conditional statement that checks all four requirements.</p><p>This is a simplified programming exercise, not a complete trading risk-management system or a recommendation to place a trade.</p><h3>In Summary</h3><p>Python conditionals are among the most important building blocks of programming. They allow applications to evaluate information, enforce rules, validate inputs, and respond differently to different situations.</p><p>In this lesson, we progressed from simple if statements to more advanced techniques.</p><p>We explored:</p><ul><li>if, if-else, and if-elif-else statements.</li><li>Comparison operators and logical operators.</li><li>Nested conditionals and chained comparisons.</li><li>Membership checks using in and not in.</li><li>User input, input validation, and exception handling.</li><li>Truthy and falsy values.</li><li>Conditional expressions.</li><li>Operator precedence and short-circuit evaluation.</li><li>Guard clauses and practical projects.</li></ul><p>As you continue learning Python, focus not only on writing conditional statements but also on making your logic clear, correct, and easy to maintain.</p><p>A good programmer does more than write code that works. A good programmer writes code that other people can understand, test, and improve.</p><p><strong>Your next step:</strong> Work through the exercises, experiment with different values, and observe how the output changes. The more you practise, the more naturally conditional logic will become part of your problem-solving process.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30ebcbd4608b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POLYNOMIAL REGRESSION]]></title>
            <link>https://medium.com/@akalumheemmanuel/polynomial-regression-b207140a4bb5?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b207140a4bb5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[polynomial-regression]]></category>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 19:47:54 GMT</pubDate>
            <atom:updated>2026-10-13T19:47:54.188Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding and Modeling Non-Linear Relationships with Python</p><p>— -</p><p>1. Introduction</p><p>So far, we have studied two important regression techniques:</p><p>## Simple Linear Regression</p><p>We used one independent variable to predict a dependent variable.</p><p>For example:</p><pre><br>Score = b_0 + b_1(Hours\_Studied)<br></pre><p>The model assumes that the relationship between `Hours_Studied` and `Score` can be represented by a straight line.</p><p>Multiple Linear Regression</p><p>We used several independent variables:</p><pre>Final\_Score =<br>b_0 +<br>b_1(Hours\_Studied) +<br>b_2(Attendance) +<br>b_3(Assignments) +<br>b_4(Previous\_Score)</pre><p>Although we now have multiple predictors, the model still assumes a linear relationship between the predictors and the target.</p><p>But what happens when the relationship is curved?</p><p>That is where Polynomial Regression becomes useful.</p><p>— -</p><p>2. The Big Idea</p><p>Consider the following relationship:</p><p>```<br>Hours Studied → Score</p><p>1 hour → 17<br>2 hours → 28<br>3 hours → 43<br>4 hours → 62<br>5 hours → 85<br>6 hours → 112<br>7 hours → 143<br>8 hours → 178<br>9 hours → 217<br>10 hours → 260<br>```</p><p>Look carefully at the increases:</p><p>```<br>17 → 28 = +11<br>28 → 43 = +15<br>43 → 62 = +19<br>62 → 85 = +23<br>85 → 112 = +27<br>112 → 143 = +31<br>…<br>```</p><p>The increase is not constant.</p><p>This suggests that the relationship is **curved rather than straight**.</p><p>A straight-line model would struggle to represent this relationship accurately.</p><p>Polynomial Regression allows us to model that curvature.</p><p>— -</p><p>3. What Is Polynomial Regression?</p><p>Polynomial Regression is a regression technique that adds powers of the predictor variables.</p><p>A simple linear regression model is:</p><pre>y = b_0 + b_1x</pre><p>A second-degree polynomial becomes:</p><pre><br>y = b_0 + b_1x + b_2x²<br></pre><p>A third-degree polynomial becomes:</p><pre>y = b_0 + b_1x + b_2x² + b_3x³</pre><p>A fourth-degree polynomial becomes:</p><pre>y = b_0 + b_1x + b_2x² + b_3x³ + b_4x⁴</pre><p>The important difference is that we are now allowing the model to capture curvature.</p><p>— -</p><p>4. A Real-Life Example</p><p>Imagine a student studying for an examination.</p><p>At first, additional study time may produce increasingly larger improvements.</p><p>For example:</p><p>1 hour → small improvement<br>2 hours → larger improvement<br>3 hours → even larger improvement<br>4 hours → much larger improvement</p><p>The relationship might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*RAK6RTJaSZaTrWMJuzRLmQ.png" /></figure><p>This is not a straight line.</p><p>It is curved.</p><p>Polynomial Regression gives us a mathematical way to represent that curve.</p><p>— -</p><p>5. Our Polynomial Regression Dataset</p><p>For this lesson, we will deliberately create a clean dataset.</p><p>The relationship will be:</p><pre>Score = 10 + 5x + 2x²</pre><p>where:</p><p>x = Hours_Studied</p><p>Therefore:</p><pre>Score =<br>10 +<br>5(Hours\_Studied) +<br>2(Hours\_Studied²)</pre><p>For example, if a student studies for 3 hours:</p><pre>Score = 10 + 5(3) + 2(3²)</pre><pre>= 10 + 15 + 18</pre><pre>= 43</pre><p>So:</p><p>Hours_Studied = 3<br>Score = 43<br> — -</p><p>6. Creating the Dataset</p><p>We will generate 200 observations.</p><pre>import pandas as pd<br>import numpy as np<br><br>np.random.seed(42)<br><br>hours_studied = np.linspace(0.5, 10, 200)<br><br>score = (<br>    10<br>    + 5 * hours_studied<br>    + 2 * (hours_studied ** 2)<br>)<br><br>df = pd.DataFrame({<br>    &quot;Hours_Studied&quot;: hours_studied,<br>    &quot;Score&quot;: score<br>})<br><br>df.head()<br></pre><p>7. Understanding the Code</p><p>This is an important opportunity for you as students how to think about code.</p><p>Do not simply just look and:</p><p>&gt; “Copy this code.”</p><p>Instead ask:</p><p>&gt; “What are we trying to create?”</p><p>Our goal is:</p><p>200 study-hour values<br> ↓<br>apply a mathematical relationship<br> ↓<br>generate scores<br> ↓<br>put both into a DataFrame</p><p>— -</p><pre>## `np.linspace()`<br><br>hours_studied = np.linspace(0.5, 10, 200)<br><br>This means:<br><br>&gt; Generate 200 evenly spaced numbers between 0.5 and 10.<br><br>Why use `linspace()` instead of random integers?<br><br>Because we want the graph to show the mathematical curve clearly.<br><br>---<br>## Creating the score<br><br>```python<br>score = (<br>    10<br>    + 5 * hours_studied<br>    + 2 * (hours_studied ** 2)<br>)<br><br>This is simply the mathematical equation written in Python.<br><br>Mathematics:<br><br>Score = 10 + 5x + 2x^2<br><br>Python:<br><br>score = 10 + 5 * hours_studied + 2 * (hours_studied ** 2)<br><br>This is an important lesson:<br><br>&gt; Good programmers learn to translate mathematical ideas into logical operations.<br><br>---<br>8. Understanding `**`<br><br>Students often confuse:<br><br>x * 2<br><br>with:<br><br>x ** 2<br><br>They are completely different.<br><br>### Multiplication<br><br>x * 2<br><br>means:<br><br>2x<br><br>### Power<br><br>x ** 2<br><br>means:<br><br>x^2<br><br>Therefore:<br><br>2 * (hours_studied ** 2)<br><br>means:<br><br>2x^2<br><br>---</pre><pre># 9. Inspect the Dataset<br><br>df.head()<br><br># Then:<br><br>df.tail()<br><br><br># And:<br><br>df.shape<br><br><br># Expected:<br><br>(200, 2)<br><br># We can also inspect the column names:<br><br>df.columns<br><br># Expected:<br><br>Index([&#39;Hours_Studied&#39;, &#39;Score&#39;], dtype=&#39;object&#39;)<br><br>---</pre><p>10. Understand the Dataset</p><p>Before modeling anything, students should always ask:</p><p>&gt; What data am I working with?</p><pre># Run:<br><br>df.info()<br><br># Then:<br><br>df.describe()<br><br>---</pre><p>11. Check for Missing Values</p><pre>df.isnull().sum()<br><br># Expected:<br><br>Hours_Studied    0<br>Score            0<br><br>There are no missing values.<br><br>This is intentional.<br><br>At this stage, we are teaching Polynomial Regression, not data cleaning.<br></pre><p>12. Check for Duplicates</p><pre><br>df.duplicated().sum()<br><br><br>Expected:<br><br>0<br><br><br>Again, this is intentional.<br><br>We want students to focus on the modeling concept.<br><br>---</pre><p>13. Exploratory Data Analysis</p><p>Before fitting a model, we need to understand the relationship between our variables.</p><p>We have:</p><p>Independent variable:<br>Hours_Studied</p><p>Dependent variable:<br>Score</p><p>The natural question is:</p><p>&gt; Does Score increase linearly with Hours_Studied, or does the relationship appear curved?</p><p>— -</p><p>14. Scatter Plot</p><pre>import matplotlib.pyplot as plt<br><br>plt.figure(figsize=(8, 5))<br><br>plt.scatter(<br>    df[&quot;Hours_Studied&quot;],<br>    df[&quot;Score&quot;]<br>)<br><br>plt.xlabel(&quot;Hours Studied&quot;)<br>plt.ylabel(&quot;Score&quot;)<br>plt.title(&quot;Hours Studied vs Score&quot;)<br><br>plt.show()</pre><p>You should observe the shape of the points.</p><p>The relationship should look curved.</p><p>— -</p><p>15. Why the Shape Matters</p><p>This is one of the most important lessons in regression.</p><p>A machine learning model is not chosen simply because:</p><p>&gt; “Linear Regression is popular.”</p><p>We first need to understand the relationship.</p><p>If the relationship is approximately:</p><pre><br><br>*<br>   *<br>      *<br>         *<br>            *<br><br>a linear model may work.<br><br>But if the relationship looks like:<br><br><br>                 *<br>             *<br>         *<br>      *<br>    *<br>  *<br> *<br><br>we may need a model capable of representing curvature.<br><br>---</pre><p>16. First Attempt: Linear Regression</p><p>Before using Polynomial Regression, we should deliberately make a mistake.</p><p>Why?</p><p>Because students learn better when they can see **why a new technique is necessary**.</p><p>Let’s first use ordinary Linear Regression.</p><p>— --</p><p>17. Define X and y</p><pre><br>X = df[[&quot;Hours_Studied&quot;]]<br><br>y = df[&quot;Score&quot;]<br><br># Remember:<br><br>### `X`<br><br>Contains the predictor variables.<br><br>### `y`<br><br>Contains the target variable.<br><br># Here:<br><br>X = Hours_Studied<br>y = Score<br><br>---</pre><p>18. Split the Dataset</p><pre>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    random_state=42<br>)</pre><pre>We use:<br><br>80% → training<br>20% → testing<br><br>With 200 observations:<br><br>Training = 160<br>Testing  = 40<br><br>---</pre><p>19. Train Linear Regression</p><pre>from sklearn.linear_model import LinearRegression<br><br>linear_model = LinearRegression()<br><br>linear_model.fit(X_train, y_train)</pre><p>20. Make Predictions</p><pre>y_pred_linear = linear_model.predict(X_test)</pre><p>The model has now produced predicted scores.</p><p>21. Evaluate the Linear Model</p><pre>from sklearn.metrics import (<br>    mean_absolute_error,<br>    mean_squared_error,<br>    r2_score<br>)<br><br>mae_linear = mean_absolute_error(y_test, y_pred_linear)<br><br>mse_linear = mean_squared_error(y_test, y_pred_linear)<br><br>rmse_linear = np.sqrt(mse_linear)<br><br>r2_linear = r2_score(y_test, y_pred_linear)<br><br>print(&quot;MAE:&quot;, mae_linear)<br>print(&quot;MSE:&quot;, mse_linear)<br>print(&quot;RMSE:&quot;, rmse_linear)<br>print(&quot;R²:&quot;, r2_linear)</pre><p>22. What Should You Notice?</p><p>The Linear Regression model will not perfectly represent the curved relationship.</p><p>This is an important lesson.</p><p>The problem is not necessarily that:</p><p>&gt; “Linear Regression is a bad algorithm.”</p><p>The problem is:</p><p>&gt; “The model’s mathematical form does not match the shape of the relationship.”</p><p>This distinction is extremely important.</p><p>— -</p><p>23. Visualizing the Linear Model</p><pre>plt.figure(figsize=(8, 5))<br><br>plt.scatter(<br>    df[&quot;Hours_Studied&quot;],<br>    df[&quot;Score&quot;],<br>    label=&quot;Actual Data&quot;<br>)<br><br>plt.plot(<br>    X_test,<br>    y_pred_linear,<br>    label=&quot;Linear Regression&quot;<br>)<br><br>plt.xlabel(&quot;Hours Studied&quot;)<br>plt.ylabel(&quot;Score&quot;)<br>plt.title(&quot;Linear Regression on a Curved Relationship&quot;)<br><br>plt.legend()<br><br>plt.show()</pre><p>The straight line will attempt to pass through a curved relationship.</p><p>This is our motivation for Polynomial Regression.</p><p>— -</p><p>24. The Key Question</p><p>&gt; “What if we could give Linear Regression additional information about the curve?”</p><p>Instead of giving the model only:</p><pre><br>x<br><br>we could give it:<br><br>x<br>x²<br><br>Then the model can learn:<br><br>y = b_0 + b_1x + b_2x^2<br><br>This is the basic idea behind Polynomial Regression.<br><br>---</pre><p>25. Creating Polynomial Features</p><p>Scikit-learn provides:</p><pre><br>PolynomialFeatures<br><br>We import it:</pre><pre>from sklearn.preprocessing import PolynomialFeatures</pre><p>Then create an object:</p><pre>poly = PolynomialFeatures(degree=2)</pre><pre>The important word is:<br><br>degree=2<br><br>This means we want:<br><br>x<br>x²<br><br>---</pre><p>26. Transform the Data</p><pre>X_train_poly = poly.fit_transform(X_train)<br><br>X_test_poly = poly.transform(X_test)</pre><p>Notice something important.</p><p>We use:</p><pre>fit_transform()</pre><p>on the training data.</p><p>But:</p><pre>transform()</pre><p>on the test data.</p><p>Why?</p><p>Because the transformation must be learned from the training data and then applied consistently to the test data.</p><p>This is a general machine learning principle.</p><p>— -</p><p>27. What Did `PolynomialFeatures` Actually Do?</p><p>Suppose:</p><pre>X = [2]</pre><p>With:</p><pre>PolynomialFeatures(degree=2)</pre><p>the transformed data contains:</p><pre>1    2    4</pre><p>These represent:</p><pre>1<br>x<br>x²</pre><p>The `1` allows Linear Regression to learn the intercept.</p><p>For example:</p><pre>y = b_0(1) + b_1x + b_2x^2</pre><p>which simplifies to:</p><p>y = b_0 + b_1x + b_2x²</p><p>— -</p><p>28. Inspect the Polynomial Features</p><p>Try:</p><pre>print(X_train_poly[:5])</pre><p>You should see three columns representing approximately:</p><pre>1    x    x²</pre><p>This is one of the most important things for us to understand.</p><p>Polynomial Regression does not magically draw a curve.</p><p>Instead:</p><p>&gt; We transform the original input into additional mathematical features, and Linear Regression learns coefficients for those features.</p><p>— -</p><p>29. Train the Polynomial Model</p><p>Now we create another Linear Regression model:</p><pre>poly_model = LinearRegression()<br><br>poly_model.fit(<br>    X_train_poly,<br>    y_train<br>)</pre><p>Notice something interesting.</p><p>We are still using:</p><pre>LinearRegression()</pre><p>This often confuses beginners.</p><p>They ask:</p><p>&gt; “If this is Polynomial Regression, why are we using LinearRegression?”</p><p>Because the model is still **linear in its coefficients**.</p><p>The input features are:</p><pre>x<br>x²</pre><p>and the model is:</p><pre>y = b_0 + b_1x + b_2x²</pre><p>It is nonlinear in `x`, but linear in the coefficients.</p><p>That is why ordinary Linear Regression can estimate the coefficients.</p><p>— -</p><p>30. Make Polynomial Predictions</p><pre>y_pred_poly = poly_model.predict(X_test_poly)</pre><p>Now we have predictions from our polynomial model.</p><p>— -</p><p>31. Evaluate the Polynomial Model</p><pre>mae_poly = mean_absolute_error(y_test, y_pred_poly)<br><br>mse_poly = mean_squared_error(y_test, y_pred_poly)<br><br>rmse_poly = np.sqrt(mse_poly)<br><br>r2_poly = r2_score(y_test, y_pred_poly)<br><br>print(&quot;MAE:&quot;, mae_poly)<br>print(&quot;MSE:&quot;, mse_poly)<br>print(&quot;RMSE:&quot;, rmse_poly)<br>print(&quot;R²:&quot;, r2_poly)</pre><p>Because our dataset was deliberately generated using a second-degree polynomial equation, the polynomial model should fit it extremely closely.</p><p>— -</p><p>32. Compare Linear and Polynomial Regression</p><pre>print(&quot;Linear Regression&quot;)<br>print(&quot;MAE:&quot;, mae_linear)<br>print(&quot;RMSE:&quot;, rmse_linear)<br>print(&quot;R²:&quot;, r2_linear)<br><br>print()<br><br>print(&quot;Polynomial Regression&quot;)<br>print(&quot;MAE:&quot;, mae_poly)<br>print(&quot;RMSE:&quot;, rmse_poly)<br>print(&quot;R²:&quot;, r2_poly)</pre><p>Students should notice that Polynomial Regression performs much better on this dataset.</p><p>— -</p><p>33. Understanding Why It Improved</p><p>The Linear Regression model could only learn:</p><pre>y = b_0 + b_1x</pre><p>But the actual relationship was:</p><pre>y = 10 + 5x + 2x^2</pre><p>The Linear model was missing the:</p><pre>x^2</pre><p>term.</p><p>Polynomial Regression added that information.</p><p>Therefore:</p><pre>Linear Regression<br>       ↓<br>x<br><br>Polynomial Regression<br>       ↓<br>x + x²<br><br>The second model has enough information to represent the curvature.<br><br>---</pre><p>34. Visualizing the Polynomial Curve</p><p>To visualize the polynomial model properly, it is useful to create many ordered x-values.</p><pre>X_curve = np.linspace(<br>    df[&quot;Hours_Studied&quot;].min(),<br>    df[&quot;Hours_Studied&quot;].max(),<br>    200<br>).reshape(-1, 1)</pre><p>Then transform them:</p><pre>X_curve_poly = poly.transform(X_curve)</pre><p>Generate predictions:</p><pre>y_curve = poly_model.predict(X_curve_poly)</pre><p>Now plot:</p><pre>plt.figure(figsize=(8, 5))<br><br>plt.scatter(<br>    df[&quot;Hours_Studied&quot;],<br>    df[&quot;Score&quot;],<br>    label=&quot;Actual Data&quot;<br>)<br><br>plt.plot(<br>    X_curve,<br>    y_curve,<br>    label=&quot;Polynomial Regression&quot;<br>)<br><br>plt.xlabel(&quot;Hours Studied&quot;)<br>plt.ylabel(&quot;Score&quot;)<br>plt.title(&quot;Polynomial Regression&quot;)<br><br>plt.legend()<br><br>plt.show()</pre><p>The result should show a smooth curve passing through the observations.</p><p>— -</p><p>35. Why Did We Create `X_curve`?</p><p>A question we might ask:</p><p>&gt; “Why didn’t we simply plot `X_test` and `y_pred_poly`?”</p><p>We could, but the test observations are not necessarily ordered.</p><p>A smooth curve is easier to visualize if we create:</p><pre>0.5<br>0.55<br>0.60<br>0.65<br>...<br>9.95<br>10</pre><p>and ask the model to predict the score at each point.</p><p>This produces a smooth sequence of predictions.</p><p>— -</p><p>36. Understanding Polynomial Degree</p><p>The `degree` controls how complex the polynomial can become.</p><p>Degree 1</p><pre>y = b_0 + b_1x</pre><p>y = b_0 + b_1x</p><p>This is essentially Linear Regression.</p><p>Degree 2</p><pre>y = b_0 + b_1x + b_2x^2</pre><p>y = b_0 + b_1x + b_2x²</p><p>Quadratic curve.</p><p>Degree 3</p><pre>y = b_0 + b_1x + b_2x^2 + b_3x^3</pre><p>y = b_0 + b_1x + b_2x² + b_3x³</p><p>Cubic curve.</p><p>Degree 4</p><pre>y = b_0 + b_1x + b_2x^2 + b_3x^3 + b_4x^4</pre><p>y = b_0 + b_1x + b_2x² + b_3x³ + b_4x⁴</p><p>And so on.</p><p>— -</p><p>37. Degree Does Not Mean “Accuracy”</p><p>Students often make this mistake:</p><p>&gt; “If degree 2 is good, degree 10 must be better.”</p><p>Not necessarily.</p><p>Higher degree means:</p><p>&gt; More flexibility.</p><p>More flexibility can be useful.</p><p>But too much flexibility can cause **overfitting**.</p><p>— -</p><p>38. Understanding Overfitting</p><p>Imagine that we have a small dataset containing some random fluctuations.</p><p>A simple model might look like:</p><pre>       *<br>    *     *<br>  *         *<br> *           *</pre><p>A very high-degree polynomial might create a complicated curve:</p><pre>    *      *<br>  *   \  /   *<br> *     \/     *<br>       /\ <br>      /  \   *<br></pre><p>It may pass extremely close to the training observations.</p><p>But it may perform poorly on new observations.</p><p>That is **overfitting**.</p><p>— -</p><p>39. Testing Different Degrees</p><p>Let’s compare several polynomial degrees.</p><pre>degrees = [1, 2, 3, 4, 5]</pre><p>We can train a model for each degree.</p><pre>results = []<br><br>for degree in degrees:<br><br>    poly = PolynomialFeatures(degree=degree)<br><br>    X_train_poly = poly.fit_transform(X_train)<br>    X_test_poly = poly.transform(X_test)<br><br>    model = LinearRegression()<br><br>    model.fit(X_train_poly, y_train)<br><br>    y_pred = model.predict(X_test_poly)<br><br>    mae = mean_absolute_error(y_test, y_pred)<br>    rmse = np.sqrt(mean_squared_error(y_test, y_pred))<br>    r2 = r2_score(y_test, y_pred)<br><br>    results.append({<br>        &quot;Degree&quot;: degree,<br>        &quot;MAE&quot;: mae,<br>        &quot;RMSE&quot;: rmse,<br>        &quot;R2&quot;: r2<br>    })</pre><p>Convert the results to a DataFrame:</p><pre>results_df = pd.DataFrame(results)<br><br>results_df<br><br></pre><p>— -</p><p>40. Why Are We Using a Loop?</p><p>This is a good programming lesson.</p><p>Instead of writing:</p><pre># Degree 1<br># Degree 2<br># Degree 3<br># Degree 4<br># Degree 5</pre><p>we recognize that the operation is repetitive.</p><p>The only thing changing is:</p><pre>degree</pre><p>Therefore we use a loop:</p><pre>for degree in degrees:</pre><p>This is an important programming principle:</p><p>&gt; When the same operation must be performed repeatedly with different values, consider using a loop.</p><p>— -</p><p>41. Visualizing Model Complexity</p><p>We can plot R² against polynomial degree.</p><pre>plt.figure(figsize=(8, 5))<br><br>plt.plot(<br>    results_df[&quot;Degree&quot;],<br>    results_df[&quot;R2&quot;],<br>    marker=&quot;o&quot;<br>)<br><br>plt.xlabel(&quot;Polynomial Degree&quot;)<br>plt.ylabel(&quot;R²&quot;)<br>plt.title(&quot;R² vs Polynomial Degree&quot;)<br><br>plt.show()</pre><p>On this particular clean dataset, several degrees may perform extremely well because the underlying relationship was deliberately generated from a second-degree polynomial.</p><p>This is important:</p><p>&gt; Do not expect every demonstration of overfitting to appear in a perfectly clean dataset.</p><p>To demonstrate overfitting realistically, we need noise and more complex data.</p><p>— -</p><p>42. The Clean Dataset vs Real-World Data</p><p>Our dataset was intentionally created using:</p><p>Score = 10 + 5x + 2x²</p><p>Therefore, degree 2 is the correct mathematical structure.</p><p>Real-world data is rarely this clean.</p><p>Real data contains:</p><p>- Measurement errors<br>- Human behavior<br>- Missing influences<br>- Random variation<br>- Outliers<br>- Incorrect observations<br>- Unobserved variables</p><p>Therefore, the real challenge is not simply:</p><p>&gt; “Find a curve that fits the data.”</p><p>The challenge is:</p><p>&gt; “Find a model that captures the underlying relationship and performs well on new data.”</p><p>That distinction is central to machine learning.</p><p>— -</p><p>43. Understanding the Polynomial Coefficients</p><p>Our original equation was:</p><p>Score = 10 + 5x + 2x²</p><p>Therefore, we expect approximately:</p><p>Intercept = 10<br>Coefficient of x = 5<br>Coefficient of x² = 2</p><p>We can inspect the trained model.</p><pre>print(&quot;Intercept:&quot;, poly_model.intercept_)<br>print(&quot;Coefficients:&quot;, poly_model.coef_)</pre><p>You should see values very close to:</p><p>Intercept ≈ 10<br>Coefficient for x ≈ 5<br>Coefficient for x² ≈ 2</p><p>The tiny differences, if any, come from floating-point calculations and the train/test process.</p><p>— -</p><p>44. Reconstructing the Equation</p><p>The trained model can therefore be represented approximately as:</p><p>Score =<br>10 +5(Hours\_Studied) +2(Hours\_Studied²)</p><p>This is extremely useful for learning.</p><p>We can see that machine learning is not magic.</p><p>The model is learning numerical parameters that describe a mathematical relationship.</p><p>45. Making a Prediction</p><p>Suppose a new student studies for:</p><p>6.5 hours</p><p>We want to predict the score.</p><p>First:</p><pre>new_student = np.array([[6.5]])</pre><p>Transform it:</p><pre>new_student_poly = poly.transform(new_student)</pre><p>Predict:</p><pre>prediction = poly_model.predict(new_student_poly)<br><br>print(&quot;Predicted Score:&quot;, prediction[0])</pre><p>Mathematically, the model is approximately calculating:</p><p>10 + 5(6.5) + 2(6.5²)</p><p>— -</p><p>46. Why Must We Transform the New Data?</p><p>This is extremely important.</p><p>The model was trained using:</p><pre>x<br>x²</pre><p>Therefore, when a new value arrives, we must provide it in the same feature format.</p><p>We cannot simply give the model:</p><pre>6.5</pre><p>when it learned from:</p><pre>6.5<br>42.25</pre><p>The transformation ensures consistency.</p><p>This principle appears throughout machine learning:</p><p>&gt; New data must go through the same preprocessing steps used during training.</p><p>— -</p><p>47. Polynomial Regression With Multiple Features</p><p>So far, we have used:</p><pre>Hours_Studied</pre><p>But Polynomial Regression can also work with multiple predictors.</p><p>Suppose we have:</p><pre>Hours_Studied<br>Attendance</pre><p>A degree-2 polynomial transformation can generate:</p><p>Hours</p><p>Attendance<br><br>Hours²<br><br>Attendance²</p><p>and interaction terms such as:</p><p>Hours \times Attendance</p><p>This can dramatically increase the number of features.</p><p>— -</p><p>48. Why This Matters</p><p>Suppose we start with:</p><pre>4 features</pre><p>A polynomial transformation can produce many more features.</p><p>For example:</p><pre>X1<br>X2<br>X3<br>X4<br><br>X1²<br>X2²<br>X3²<br>X4²<br><br>X1X2<br>X1X3<br>X1X4<br>X2X3<br>...</pre><p>The model becomes more flexible.</p><p>But this creates a new problem:</p><p>&gt; What happens when we have too many features?</p><p>This is exactly where our next topic becomes important.</p><p>— -</p><p>49. Polynomial Regression and Feature Explosion</p><p>Polynomial features can increase the number of variables very quickly.</p><p>This is sometimes called:</p><p>**Feature Explosion**</p><p>For example, a model with a few original variables can produce a much larger feature space after polynomial transformation.</p><p>More features can mean:</p><p>- More computational work<br>- More difficult interpretation<br>- Greater risk of overfitting<br>- Larger coefficients<br>- Multicollinearity<br>- Redundant information</p><p>This leads naturally to **regularization**.</p><p>— -</p><p>50. The Bridge to Ridge and Lasso</p><p>At this point, students should understand the following problem.</p><p>Suppose we have:</p><pre>Hours_Studied<br>Attendance<br>Previous_Score<br>Assignments<br>Age<br>Internet_Usage<br>Gaming_Hours<br>Social_Media_Hours<br>Random_Feature_1<br>Random_Feature_2<br>Random_Feature_3<br>...</pre><p>And suppose some of these variables are:</p><p>- Strongly related to each other<br>- Weakly useful<br>- Completely irrelevant<br>- Created through polynomial transformations</p><p>Ordinary Linear Regression does not automatically say:</p><p>&gt; “This feature is unnecessary.”</p><p>It will attempt to estimate coefficients for the available variables.</p><p>We therefore need a way to **control the complexity of the model**.</p><p>That is where regularization comes in.</p><p>— -</p><p>51. Preview of Ridge Regression</p><p>Ridge Regression modifies the ordinary least-squares objective by adding a penalty for large coefficients.</p><p>Conceptually:</p><p>Loss =<br>Prediction\ Error<br>+<br>\lambda \sum b_j²</p><p>The important idea is:</p><p>&gt; Ridge discourages very large coefficients.</p><p>It does not normally eliminate features completely.</p><p>Instead, it shrinks their coefficients toward zero.</p><p>— -</p><p>52. Preview of Lasso Regression</p><p>Lasso uses a different penalty:</p><p>Loss =<br>Prediction\ Error<br>+<br>\lambda \sum |b_j|</p><p>Because of the nature of this penalty, some coefficients can become exactly zero.</p><p>That means Lasso can effectively perform:</p><p>&gt; **Feature selection**</p><p>For example:</p><pre>Hours_Studied          4.72<br>Attendance             0.31<br>Previous_Score         0.28<br>Gaming_Hours           0.00<br>Random_Feature_1       0.00</pre><p>Lasso may effectively tell us:</p><pre>Keep:<br>Hours_Studied<br>Attendance<br>Previous_Score<br><br>Discard:<br>Gaming_Hours<br>Random_Feature_1</pre><p>This is why Ridge and Lasso will make the ideas of feature importance and irrelevant variables much more practical.</p><p>— -</p><p>53. Polynomial Regression vs Ridge vs Lasso</p><p>At this point, students should understand the roles of the techniques:</p><pre>| Model | Main Purpose |<br>|---|---|<br>| Linear Regression | Model linear relationships |<br>| Multiple Linear Regression | Model linear relationships using several predictors |<br>| Polynomial Regression | Model curved relationships |<br>| Ridge Regression | Control large coefficients and multicollinearity |<br>| Lasso Regression | Regularize and perform feature selection |<br><br>---</pre><p>54. Important Concept: Polynomial Does Not Automatically Mean “Better”</p><p>Students should never think:</p><p>&gt; “Polynomial Regression is better than Linear Regression.”</p><p>The correct statement is:</p><p>&gt; Polynomial Regression can be more appropriate when the relationship between the predictors and target contains meaningful curvature.</p><p>Likewise:</p><p>&gt; A higher polynomial degree is not automatically better.</p><p>Model choice depends on the data and the problem.</p><p>— -</p><p>55. Important Concept: Complexity vs Simplicity</p><p>Think about models as having different levels of flexibility.</p><p>## Linear Regression</p><p>Very simple:</p><pre>straight line</pre><p>## Degree 2 Polynomial</p><p>More flexible:</p><pre>simple curve</pre><p>## Degree 5 Polynomial</p><p>More flexible:</p><pre>complex curve</pre><p>## Degree 20 Polynomial</p><p>Potentially extremely flexible:</p><pre>very complex curve</pre><p>More flexibility can reduce training error.</p><p>But excessive flexibility can hurt performance on unseen data.</p><p>This is the fundamental idea behind **overfitting**.</p><p>— -</p><p>56. Training Error vs Test Error</p><p>Students should begin thinking about two different questions.</p><p># Training performance</p><p>&gt; How well does my model explain the data it already saw?</p><p># Testing performance</p><p>&gt; How well does my model perform on data it did not see during training?</p><p>A model that memorizes training data may have:</p><pre>Training error → extremely low<br>Testing error  → high</pre><p>That is a warning sign for overfitting.</p><p>— -</p><p>57. The Most Important Machine Learning Lesson</p><p>The goal is not:</p><p>&gt; “Fit the training data perfectly.”</p><p>The goal is:</p><p>&gt; **Learn a useful relationship that generalizes to new observations.**</p><p>This idea will become even more important when we study Ridge and Lasso.</p><p>— -</p><p>58. Complete Polynomial Regression Workflow</p><p>The complete workflow is:</p><p>1. Understand the problem<br> ↓<br>2. Load / create data<br> ↓<br>3. Inspect the data<br> ↓<br>4. Perform EDA<br> ↓<br>5. Visualize the relationship<br> ↓<br>6. Try Linear Regression<br> ↓<br>7. Evaluate the linear model<br> ↓<br>8. Recognize curvature<br> ↓<br>9. Create polynomial features<br> ↓<br>10. Train Polynomial Regression<br> ↓<br>11. Make predictions<br> ↓<br>12. Evaluate the model<br> ↓<br>13. Visualize the fitted curve<br> ↓<br>14. Compare polynomial degrees<br> ↓<br>15. Think about overfitting<br> ↓<br>16. Evaluate generalization</p><p>— -</p><pre>59. Complete Python Implementation<br><br>Here is the complete basic implementation in one place.<br><br>```python<br># ==========================================<br># 1. Import libraries<br># ==========================================<br><br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br>from sklearn.preprocessing import PolynomialFeatures<br><br>from sklearn.metrics import (<br>    mean_absolute_error,<br>    mean_squared_error,<br>    r2_score<br>)<br><br><br># ==========================================<br># 2. Create dataset<br># ==========================================<br><br>np.random.seed(42)<br><br>hours_studied = np.linspace(0.5, 10, 200)<br><br>score = (<br>    10<br>    + 5 * hours_studied<br>    + 2 * (hours_studied ** 2)<br>)<br><br>df = pd.DataFrame({<br>    &quot;Hours_Studied&quot;: hours_studied,<br>    &quot;Score&quot;: score<br>})<br><br><br># ==========================================<br># 3. Inspect data<br># ==========================================<br><br>print(df.head())<br><br>print(df.info())<br><br>print(df.describe())<br><br><br># ==========================================<br># 4. Visualize relationship<br># ==========================================<br><br>plt.figure(figsize=(8, 5))<br><br>plt.scatter(<br>    df[&quot;Hours_Studied&quot;],<br>    df[&quot;Score&quot;]<br>)<br><br>plt.xlabel(&quot;Hours Studied&quot;)<br>plt.ylabel(&quot;Score&quot;)<br>plt.title(&quot;Hours Studied vs Score&quot;)<br><br>plt.show()<br><br><br># ==========================================<br># 5. Define X and y<br># ==========================================<br><br>X = df[[&quot;Hours_Studied&quot;]]<br><br>y = df[&quot;Score&quot;]<br><br><br># ==========================================<br># 6. Train-test split<br># ==========================================<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    random_state=42<br>)<br><br><br># ==========================================<br># 7. Linear Regression baseline<br># ==========================================<br><br>linear_model = LinearRegression()<br><br>linear_model.fit(<br>    X_train,<br>    y_train<br>)<br><br>y_pred_linear = linear_model.predict(X_test)<br><br><br># ==========================================<br># 8. Evaluate Linear Regression<br># ==========================================<br><br>mae_linear = mean_absolute_error(<br>    y_test,<br>    y_pred_linear<br>)<br><br>mse_linear = mean_squared_error(<br>    y_test,<br>    y_pred_linear<br>)<br><br>rmse_linear = np.sqrt(mse_linear)<br><br>r2_linear = r2_score(<br>    y_test,<br>    y_pred_linear<br>)<br><br><br># ==========================================<br># 9. Create polynomial features<br># ==========================================<br><br>poly = PolynomialFeatures(<br>    degree=2<br>)<br><br>X_train_poly = poly.fit_transform(<br>    X_train<br>)<br><br>X_test_poly = poly.transform(<br>    X_test<br>)<br><br><br># ==========================================<br># 10. Train Polynomial Regression<br># ==========================================<br><br>poly_model = LinearRegression()<br><br>poly_model.fit(<br>    X_train_poly,<br>    y_train<br>)<br><br><br># ==========================================<br># 11. Make predictions<br># ==========================================<br><br>y_pred_poly = poly_model.predict(<br>    X_test_poly<br>)<br><br><br># ==========================================<br># 12. Evaluate Polynomial Regression<br># ==========================================<br><br>mae_poly = mean_absolute_error(<br>    y_test,<br>    y_pred_poly<br>)<br><br>mse_poly = mean_squared_error(<br>    y_test,<br>    y_pred_poly<br>)<br><br>rmse_poly = np.sqrt(mse_poly)<br><br>r2_poly = r2_score(<br>    y_test,<br>    y_pred_poly<br>)<br><br><br># ==========================================<br># 13. Display results<br># ==========================================<br><br>print(&quot;Linear Regression&quot;)<br>print(&quot;-------------------------&quot;)<br>print(&quot;MAE:&quot;, mae_linear)<br>print(&quot;MSE:&quot;, mse_linear)<br>print(&quot;RMSE:&quot;, rmse_linear)<br>print(&quot;R²:&quot;, r2_linear)<br><br>print()<br><br>print(&quot;Polynomial Regression&quot;)<br>print(&quot;-------------------------&quot;)<br>print(&quot;MAE:&quot;, mae_poly)<br>print(&quot;MSE:&quot;, mse_poly)<br>print(&quot;RMSE:&quot;, rmse_poly)<br>print(&quot;R²:&quot;, r2_poly)<br><br><br># ==========================================<br># 14. Polynomial coefficients<br># ==========================================<br><br>print(&quot;Intercept:&quot;, poly_model.intercept_)<br>print(&quot;Coefficients:&quot;, poly_model.coef_)<br><br><br># ==========================================<br># 15. Create smooth curve<br># ==========================================<br><br>X_curve = np.linspace(<br>    df[&quot;Hours_Studied&quot;].min(),<br>    df[&quot;Hours_Studied&quot;].max(),<br>    200<br>).reshape(-1, 1)<br><br>X_curve_poly = poly.transform(<br>    X_curve<br>)<br><br>y_curve = poly_model.predict(<br>    X_curve_poly<br>)<br><br><br># ==========================================<br># 16. Plot polynomial curve<br># ==========================================<br><br>plt.figure(figsize=(8, 5))<br><br>plt.scatter(<br>    df[&quot;Hours_Studied&quot;],<br>    df[&quot;Score&quot;],<br>    label=&quot;Actual Data&quot;<br>)<br><br>plt.plot(<br>    X_curve,<br>    y_curve,<br>    label=&quot;Polynomial Regression&quot;<br>)<br><br>plt.xlabel(&quot;Hours Studied&quot;)<br>plt.ylabel(&quot;Score&quot;)<br>plt.title(&quot;Polynomial Regression&quot;)<br><br>plt.legend()<br><br>plt.show()<br>```<br><br>---<br><br># 60. Reading the Code Like a Programmer<br><br>Students should not memorize the complete code.<br><br>Instead, they should learn to identify the purpose of each section.<br><br>When you see:<br><br>PolynomialFeatures(degree=2)<br><br>ask:<br><br>&gt; &quot;Why am I transforming the features?&quot;<br><br>Answer:<br><br>&gt; Because I want to provide the model with polynomial terms such as \(x^2\).<br><br>When you see:<br><br>poly.fit_transform(X_train)<br><br>ask:<br><br>&gt; &quot;What is being transformed?&quot;<br><br>Answer:<br><br>&gt; The training predictor is being expanded into polynomial features.<br><br>When you see:<br><br>poly.transform(X_test)<br><br>ask:<br><br>&gt; &quot;Why don&#39;t we use `fit_transform()`?&quot;<br><br>Answer:<br><br>&gt; Because the transformation was already established using the training data. The test data should receive the same transformation.<br><br>When you see:<br><br>LinearRegression()<br><br>ask:<br><br>&gt; &quot;Why are we still using Linear Regression?&quot;<br><br>Answer:<br><br>&gt; Because the model is linear in its coefficients, even though the features include powers such as \(x^2\).<br><br>---</pre><p>60. Reading the Code Like a Programmer</p><p>You should not memorize the complete code.</p><p>Instead, you should learn to identify the purpose of each section.</p><p>When you see:</p><pre>PolynomialFeatures(degree=2)</pre><p>ask:</p><p>&gt; “Why am I transforming the features?”</p><p>Answer:</p><p>&gt; Because I want to provide the model with polynomial terms such as \(x²\).</p><p>When you see:</p><pre>poly.fit_transform(X_train)</pre><p>ask:</p><p>&gt; “What is being transformed?”</p><p>Answer:</p><p>&gt; The training predictor is being expanded into polynomial features.</p><p>When you see:</p><pre>poly.transform(X_test)</pre><p>ask:</p><p>&gt; “Why don’t we use `fit_transform()`?”</p><p>Answer:</p><p>&gt; Because the transformation was already established using the training data. The test data should receive the same transformation.</p><p>When you see:</p><pre>LinearRegression()</pre><p>ask:</p><p>&gt; “Why are we still using Linear Regression?”</p><p>Answer:</p><p>&gt; Because the model is linear in its coefficients, even though the features include powers such as \(x²\).</p><p>— -</p><p>61. Common Beginner Mistakes</p><p># Mistake 1 — Thinking Polynomial Regression is completely different from Linear Regression</p><p>Polynomial Regression commonly uses:</p><pre>LinearRegression()</pre><p>after transforming the features.</p><p>— -</p><p># Mistake 2 — Using the wrong degree</p><pre>PolynomialFeatures(degree=1)</pre><p>does not introduce curvature.</p><p>It essentially gives:</p><pre>1<br>x</pre><p>Degree 2 introduces:</p><pre>1<br>x<br>x²</pre><p>— -</p><p># Mistake 3 — Forgetting to transform test data</p><p>Incorrect:</p><pre>poly_model.predict(X_test)</pre><p>if the model was trained using polynomial features.</p><p>Correct:</p><pre>X_test_poly = poly.transform(X_test)<br><br>poly_model.predict(X_test_poly)</pre><p># Mistake 4 — Transforming training and test data independently</p><p>Avoid:</p><pre>X_train_poly = poly.fit_transform(X_train)<br><br>X_test_poly = poly.fit_transform(X_test)</pre><p>Instead:</p><pre>X_train_poly = poly.fit_transform(X_train)<br><br>X_test_poly = poly.transform(X_test)</pre><p># Mistake 5 — Assuming higher degree is always better</p><p>A higher degree gives the model more flexibility.</p><p>More flexibility can lead to overfitting.</p><p>— -</p><p># Mistake 6 — Evaluating only training performance</p><p>A model can perform extremely well on training data and poorly on new data.</p><p>Always consider:</p><pre>Training performance<br>+<br>Testing performance</pre><p># 62. Important Vocabulary</p><p>Students should know these terms.</p><p>## Polynomial</p><p>An expression involving powers of variables.</p><p>Example:</p><p>x²</p><p>or:</p><p>3x² + 5x + 2</p><p>## Degree</p><p>The highest power in the polynomial.</p><p>Example:<br>y = 2x³ + 5x² + x + 7</p><p>has degree 3.</p><p>## Polynomial Features</p><p>Additional features created from powers and combinations of existing features.</p><p>## Overfitting</p><p>When a model learns the training data too closely and performs poorly on unseen data.</p><p>## Generalization</p><p>The ability of a model to perform well on new, unseen data.</p><p>## Regularization</p><p>A technique used to control model complexity by penalizing large coefficients.</p><p>— -</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b207140a4bb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[They Love Working Systems , Just Not Enough to Build One in Nigeria]]></title>
            <link>https://medium.com/@akalumheemmanuel/they-love-working-systems-just-not-enough-to-build-one-in-nigeria-07bc77d57e74?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/07bc77d57e74</guid>
            <category><![CDATA[nigeria]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[africa]]></category>
            <category><![CDATA[nigerian-politics]]></category>
            <category><![CDATA[affairs]]></category>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 07:52:30 GMT</pubDate>
            <atom:updated>2026-07-05T07:52:30.855Z</atom:updated>
            <content:encoded><![CDATA[<p>One thing many Nigerians have noticed is this:</p><p>Our political class and many of the country’s wealthy elites have great respect for countries where things work. They enjoy steady electricity, clean streets, quality healthcare, good schools, reliable transport, security, and governments that are accountable to the people.</p><p>When they travel abroad, they obey the rules because they know the system works. They trust the hospitals with their lives, the schools with their children, and the institutions with their future.</p><p>But when they return to Nigeria, that same passion for a working system is often nowhere to be found.</p><p>Instead of fixing our hospitals, they fly abroad for treatment.</p><p>Instead of improving our schools, they send their children overseas.</p><p>Instead of building reliable infrastructure at home, they invest in countries that already have it.</p><p>It raises an important question:</p><p>If a functioning system is good enough for them, why isn’t it good enough for every Nigerian?</p><p>The sad reality is that a broken system rarely hurts those at the top as much as it hurts everyone else.</p><p>When power fails, they have generators.</p><p>When security fails, they hire private guards.</p><p>When public hospitals fail, they board the next flight.</p><p>When public education declines, they can afford foreign tuition.</p><p>For the average Nigerian, these are life-changing problems. For the elite, they are expensive inconveniences.</p><p>There is also something deeper about our society that deserves honest conversation.</p><p>Many Nigerians grow up in a culture where success is measured by how much better you are doing than the next person. We love to show progress. Driving expensive cars, shopping abroad, taking foreign holidays, or posting pictures from countries where everything works has become a way of saying, “Look at me. I have made it.”</p><p>There is nothing wrong with enjoying the rewards of hard work.</p><p>The problem begins when the same people enjoying the benefits of well-run countries show little interest in creating those same opportunities for the people back home.</p><p>Sometimes it even feels as though the gap itself has become part of the reward.</p><p>The wider the difference between the elite and the average Nigerian, the easier it becomes to say, “Look how far I’ve come.”</p><p>A Nigeria with reliable electricity, quality education, affordable healthcare, safe roads, and strong institutions would improve life for everyone. It would also reduce the enormous gap in quality of life that separates the privileged from ordinary citizens.</p><p>That is why many Nigerians have become frustrated. Not because they hate success, but because they see people enjoying the best systems in the world while refusing — or failing — to build even a fraction of those systems at home.</p><p>This is not to say that every wealthy Nigerian or every public official wants Nigerians to suffer. Many have made genuine contributions to the country’s development.</p><p>But after decades of promises and little progress, Nigerians have every right to ask difficult questions.</p><p>Our leaders know what good governance looks like. They experience it every time they leave Nigeria.</p><p>They know what quality healthcare looks like because they use it.</p><p>They know what excellent public education looks like because their children receive it.</p><p>They know what functioning institutions look like because they trust them with their own lives.</p><p>So the problem has never been a lack of knowledge.</p><p>The real question is whether there is enough political will and enough commitment to give ordinary Nigerians the same quality of life they happily enjoy elsewhere.</p><p>Nigeria does not need leaders who only admire working systems abroad.</p><p>Nigeria needs leaders who are determined to build one here.</p><p>Because no Nigerian should have to leave home just to experience the dignity of living in a country that works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07bc77d57e74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Descriptive Sales Data Analysis 1]]></title>
            <link>https://medium.com/@akalumheemmanuel/basic-descriptive-sales-data-analysis-1-ff42a48e23e8?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff42a48e23e8</guid>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 21:17:13 GMT</pubDate>
            <atom:updated>2024-07-25T21:17:13.654Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a step-by-step guide to performing a Basic Descriptive Sales Data Analysis in Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-PYK_v55lIK6vEB84cbQZA.png" /></figure><p>Data analysis is essential for understanding sales patterns and making informed business decisions. In this article, we’ll walk through the steps to perform a basic descriptive sales data analysis using Python and Jupyter Lab. We’ll cover everything from loading and cleaning the data to visualizing key insights with interactive dashboards. Let’s dive in!</p><h3>Step 1: Import Necessary Libraries</h3><p>First, we need to import the essential Python libraries for data analysis and visualization. Here’s the code:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import plotly.express as px<br>import plotly.graph_objects as go<br>import plotly.io as pio<br><br># Set the default renderer to &#39;notebook&#39; for Jupyter Lab<br>pio.renderers.default = &#39;notebook&#39;</pre><h3>Step 2: Load the Dataset</h3><p>We have multiple CSV files for each month, you can merge them into a single DataFrame. Here’s how:</p><pre># Define the path where your CSV files are stored<br>path = r&#39;C:\Users\HP\Documents\Sales Data Analysis\Sales_Data&#39; # Update this to the correct path<br><br># List of CSV files to merge<br>files = [&quot;Sales_January_2019.csv&quot;, &quot;Sales_February_2019.csv&quot;, &quot;Sales_March_2019.csv&quot;, &quot;Sales_April_2019.csv&quot;,&quot;Sales_May_2019.csv&quot;,<br>        &quot;Sales_June_2019.csv&quot;, &quot;Sales_July_2019.csv&quot;, &quot;Sales_August_2019.csv&quot;, &quot;Sales_September_2019.csv&quot;, &quot;Sales_October_2019.csv&quot;,<br>        &quot;Sales_November_2019.csv&quot;, &quot;Sales_December_2019.csv&quot;]<br><br># Initialize an empty list to hold the dataframes<br>dataframes = []<br><br># Read each CSV file into a dataframe and append to the list<br>for file in files:<br>    df = pd.read_csv(os.path.join(path, file))<br>    dataframes.append(df)<br><br># Concatenate all dataframes into a single dataframe<br>MergedSales2019_df = pd.concat(dataframes, ignore_index=True)<br><br># Save the merged dataframe to a new CSV file<br>MergedSales2019_df.to_csv(os.path.join(path, &#39;Merged_Sales_2019.csv&#39;), index=False)<br><br>MergedSales2019_df<br><br>Order ID  Product  Quantity Ordered  Price Each  Order Date  Purchase Address<br>0  141234  iPhone  1  700  01/22/19 21:25  944 Walnut St, Boston, MA 02215<br>1  141235  Lightning Charging Cable  1  14.95  01/28/19 14:15  185 Maple St, Portland, OR 97035<br>2  141236  Wired Headphones  2  11.99  01/17/19 13:33  538 Adams St, San Francisco, CA 94016<br>3  141237  27in FHD Monitor  1  149.99  01/05/19 20:33  738 10th St, Los Angeles, CA 90001<br>4  141238  Wired Headphones  1  11.99  01/25/19 11:59  387 10th St, Austin, TX 73301<br>...  ...  ...  ...  ...  ...  ...<br>186845  319666  Lightning Charging Cable  1  14.95  12/11/19 20:58  14 Madison St, San Francisco, CA 94016<br>186846  319667  AA Batteries (4-pack)  2  3.84  12/01/19 12:01  549 Willow St, Los Angeles, CA 90001<br>186847  319668  Vareebadd Phone  1  400  12/09/19 06:43  273 Wilson St, Seattle, WA 98101<br>186848  319669  Wired Headphones  1  11.99  12/03/19 10:39  778 River St, Dallas, TX 75001<br>186849  319670  Bose SoundSport Headphones  1  99.99  12/21/19 21:45  747 Chestnut St, Los Angeles, CA 90001<br><br>186850 rows × 6 columns</pre><h3>Step 3: Descriptive Statistics</h3><p>Descriptive statistics provide a summary of the data, helping us understand the distribution and key metrics. Use the following code:</p><pre>#Examine the dataset<br>MergedSales2019_df.info()<br><br># Display basic statistics<br>MergedSales2019_df.describe()<br><br># Check for null values<br>MergedSales2019_df.isnull().sum()</pre><pre># Convert &#39;Quantity Ordered&#39; to integer<br>MergedSales2019_df[&#39;Quantity Ordered&#39;] = pd.to_numeric(MergedSales2019_df[&#39;Quantity Ordered&#39;], errors=&#39;coerce&#39;)<br><br># Convert &#39;Price Each&#39; to float<br>MergedSales2019_df[&#39;Price Each&#39;] = pd.to_numeric(MergedSales2019_df[&#39;Price Each&#39;], errors=&#39;coerce&#39;)<br><br># Convert &#39;Order Date&#39; to datetime<br>MergedSales2019_df[&#39;Order Date&#39;] = pd.to_datetime(MergedSales2019_df[&#39;Order Date&#39;], errors=&#39;coerce&#39;)</pre><h3>Handling Missing Values:</h3><pre># Drop rows with missing values<br>cleanedMergedSales2019_df = MergedSales2019_df.dropna()<br><br># Check the cleaned DataFrame<br>cleanedMergedSales2019_df.info()</pre><pre>cleanedMergedSales2019_df.describe()<br><br>  Quantity Ordered  Price Each<br>count  185950.000000  185950.000000<br>mean  1.124383  184.399735<br>std  0.442793  332.731330<br>min  1.000000  2.990000<br>25%  1.000000  11.950000<br>50%  1.000000  14.950000<br>75%  1.000000  150.000000<br>max  9.000000  1700.000000</pre><p>Insights gotten from the above</p><pre>#Quantity Ordered<br><br>- Count: 185,950 entries, indicating the total number of non-null quantities ordered in the dataset.<br>- Mean (Average): 1.124383, indicating that on average, about 1.12 units of a product are ordered.<br>- Standard Deviation (Std): 0.442793, indicating the amount of variation or dispersion in the quantity ordered around the mean.<br>- Min (Minimum): 1, indicating that the smallest quantity ordered is 1 unit.<br>- 25% (1st Quartile): 1, indicating that 25% of orders have a quantity of 1 unit.<br>- 50% (Median/2nd Quartile): 1, indicating that 50% of orders have a quantity of 1 unit (median is also 1).<br>- 75% (3rd Quartile): 1, indicating that 75% of orders have a quantity of 1 unit.<br>- Max (Maximum): 9, indicating that the largest quantity ordered is 9 units.<br><br>Interpretation: The majority of orders are for a quantity of 1 unit, as reflected by the 25th, 50th, and 75th percentiles all being 1. There are few instances where more than 1 unit is ordered, with the maximum being 9 units.<br><br>#Price Each<br><br>- Count: 185,950 entries, indicating the total number of non-null prices in the dataset.<br>- Mean (Average): 184.399735, indicating that on average, the price of a product is 184.40 Dollars.<br>- Standard Deviation (Std): 332.731330, indicating a high amount of variation in prices, suggesting a wide range of product prices.<br>- Min (Minimum): 2.99, indicating that the lowest product price is 2.99 Dollars.<br>- 25% (1st Quartile): 11.95, indicating that 25% of the products are priced at or below 11.95 Dollars.<br>- 50% (Median/2nd Quartile): 14.95, indicating that 50% of the products are priced at or below 14.95 Dollars.<br>- 75% (3rd Quartile): 150.00, indicating that 75% of the products are priced at or below 150.00 Dollars.<br>- Max (Maximum): 1700.00, indicating that the highest product price is 1700.00 Dollars.<br><br>Interpretation: The prices of products vary significantly, as indicated by the high standard deviation and they range from 2.99 Dollars to 1700 Dollars. Most products are relatively inexpensive, with the majority priced under 150 Dollars. The mean is much higher than the median, suggesting the presence of some very high-priced items that skew the average.<br><br>#Insights<br><br>1. Quantity Ordered:<br>   - Most orders are for single units, with very few orders for multiple units.<br>   <br>2. Price Each:<br>   - There is a significant variation in product prices, with many low-cost items and a few very high-cost items.<br>   - The median price is much lower than the mean price, indicating a right-skewed distribution of prices.<br><br>These insights are useful because they help understand customer ordering behavior and product pricing. For instance, we may want to focus marketing efforts on single-unit purchases or consider the impact of high-priced items on the overall sales strategy.</pre><h3>Checking For Duplicate Orders</h3><pre># Check for duplicate Order IDs<br>duplicates = cleanedMergedSales2019_df[cleanedMergedSales2019_df.duplicated(subset=&#39;Order ID&#39;, keep=False)]<br>duplicates<br><br>  Order ID  Product  Quantity Ordered  Price Each  Order Date  Purchase Address<br>41  141275  USB-C Charging Cable  1.0  11.95  2019-01-07 16:06:00  610 Walnut St, Austin, TX 73301<br>42  141275  Wired Headphones  1.0  11.99  2019-01-07 16:06:00  610 Walnut St, Austin, TX 73301<br>57  141290  Apple Airpods Headphones  1.0  150.00  2019-01-02 08:25:00  4 1st St, Los Angeles, CA 90001<br>58  141290  AA Batteries (4-pack)  3.0  3.84  2019-01-02 08:25:00  4 1st St, Los Angeles, CA 90001<br>133  141365  Vareebadd Phone  1.0  400.00  2019-01-10 11:19:00  20 Dogwood St, New York City, NY 10001<br>...  ...  ...  ...  ...  ...  ...<br>186761  319584  Wired Headphones  1.0  11.99  2019-12-11 00:30:00  537 Sunset St, Portland, OR 97035<br>186773  319596  iPhone  1.0  700.00  2019-12-01 08:44:00  436 14th St, New York City, NY 10001<br>186774  319596  Lightning Charging Cable  1.0  14.95  2019-12-01 08:44:00  436 14th St, New York City, NY 10001<br>186809  319631  34in Ultrawide Monitor  1.0  379.99  2019-12-17 22:35:00  363 Highland St, Austin, TX 73301<br>186810  319631  Lightning Charging Cable  1.0  14.95  2019-12-17 22:35:00  363 Highland St, Austin, TX 73301<br><br>14649 rows × 6 columns</pre><pre># # If duplicates are not valid, drop them<br># cleanedMergedSales2019_df = cleanedMergedSales2019_df.drop_duplicates(subset=&#39;Order ID&#39;, keep=&#39;first&#39;)<br><br># # Verify no more duplicates<br># cleanedMergedSales2019_df.duplicated(subset=&#39;Order ID&#39;).sum()</pre><h3>Step 4: Basic Data Analysis</h3><ol><li>Top Selling Products</li></ol><pre># Top Products<br>top_products = cleanedMergedSales2019_df[&#39;Product&#39;].value_counts().head(10)<br>top_products<br><br>USB-C Charging Cable          21903<br>Lightning Charging Cable      21658<br>AAA Batteries (4-pack)        20641<br>AA Batteries (4-pack)         20577<br>Wired Headphones              18882<br>Apple Airpods Headphones      15549<br>Bose SoundSport Headphones    13325<br>27in FHD Monitor               7507<br>iPhone                         6842<br>27in 4K Gaming Monitor         6230<br>Name: Product, dtype: int64</pre><p>2. Sales Trends Over Time</p><pre># Sales Trends Over Time<br>cleanedMergedSales2019_df[&#39;Month&#39;] = cleanedMergedSales2019_df[&#39;Order Date&#39;].dt.month<br>monthly_sales = cleanedMergedSales2019_df.groupby(&#39;Month&#39;).sum()[&#39;Price Each&#39;]<br>print(monthly_sales)<br><br>Month<br>1     1.811768e+06<br>2     2.188885e+06<br>3     2.791208e+06<br>4     3.367671e+06<br>5     3.135125e+06<br>6     2.562026e+06<br>7     2.632540e+06<br>8     2.230345e+06<br>9     2.084992e+06<br>10    3.715555e+06<br>11    3.180601e+06<br>12    4.588415e+06<br>Name: Price Each, dtype: float64</pre><p>3. Address of the Top Customers</p><pre># Customer Insights<br>top_addresses = cleanedMergedSales2019_df[&#39;Purchase Address&#39;].value_counts().head(10)<br>top_addresses<br><br>193 Forest St, San Francisco, CA 94016      9<br>223 Elm St, Los Angeles, CA 90001           8<br>279 Sunset St, San Francisco, CA 94016      8<br>176 North St, San Francisco, CA 94016       7<br>662 Chestnut St, San Francisco, CA 94016    7<br>727 9th St, San Francisco, CA 94016         7<br>550 Cherry St, San Francisco, CA 94016      7<br>640 West St, San Francisco, CA 94016        7<br>197 Center St, San Francisco, CA 94016      7<br>284 Walnut St, San Francisco, CA 94016      7<br>Name: Purchase Address, dtype: int64</pre><h3>Step 5: Exploratory Data Analysis (EDA) with Visualizations</h3><h3>1. Quantity Ordered Distribution</h3><p>Visualize the distribution of quantities ordered using a bar plot:</p><pre>plt.figure(figsize=(15, 10))<br>sns.countplot(data=cleanedMergedSales2019_df, x=&#39;Quantity Ordered&#39;, palette=&#39;viridis&#39;)<br>plt.title(&#39;Distribution of Quantity Ordered&#39;)<br>plt.xlabel(&#39;Quantity Ordered&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*5mTLhAf8w_3tWcIT5IRBjg.png" /></figure><h3>2. Price Each Distribution</h3><p>Visualize the distribution of product prices using a histogram:</p><pre>plt.figure(figsize=(15, 10))<br>sns.histplot(data=cleanedMergedSales2019_df, x=&#39;Price Each&#39;, bins=50, kde=True, color=&#39;blue&#39;)<br>plt.title(&#39;Distribution of Price Each&#39;)<br>plt.xlabel(&#39;Price Each&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*GvuSp2XWBCx6pZXivs50GQ.png" /></figure><h3>3. Top Products Sold</h3><p>Identify and visualize the top 10 most sold products:</p><pre>top_products = cleanedMergedSales2019_df[&#39;Product&#39;].value_counts().head(10)<br>plt.figure(figsize=(15, 10))<br>sns.barplot(x=top_products.values, y=top_products.index, palette=&#39;viridis&#39;)<br>plt.title(&#39;Top 10 Products Sold&#39;)<br>plt.xlabel(&#39;Quantity Sold&#39;)<br>plt.ylabel(&#39;Product&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*o3P2u4NpQOKgfCHI8Upd3w.png" /></figure><h3>4. Monthly Sales Trends</h3><p>Analyze sales trends over the months:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*bEjiMWrShk-Quk4aPH4-Lw.png" /></figure><h3>Step 6: Create a Dashboard</h3><p>Combine multiple plots into a single dashboard:</p><pre>from plotly.subplots import make_subplots<br><br># Create subplots<br>fig = make_subplots(rows=2, cols=2, subplot_titles=(&#39;Quantity Ordered Distribution&#39;, &#39;Price Each Distribution&#39;, <br>                                                    &#39;Top 10 Products Sold&#39;, &#39;Monthly Sales Trends&#39;))<br><br># Quantity Ordered Distribution<br>fig.add_trace(go.Histogram(x=cleanedMergedSales2019_df[&#39;Quantity Ordered&#39;], nbinsx=10, name=&#39;Quantity Ordered&#39;), row=1, col=1)<br><br># Price Each Distribution<br>fig.add_trace(go.Histogram(x=cleanedMergedSales2019_df[&#39;Price Each&#39;], nbinsx=50, name=&#39;Price Each&#39;), row=1, col=2)<br><br># Top 10 Products Sold<br>fig.add_trace(go.Bar(x=top_products.values, y=top_products.index, orientation=&#39;h&#39;, name=&#39;Top 10 Products&#39;), row=2, col=1)<br><br># Monthly Sales Trends<br>fig.add_trace(go.Scatter(x=monthly_sales.index, y=monthly_sales.values, mode=&#39;lines+markers&#39;, name=&#39;Monthly Sales&#39;), row=2, col=2)<br><br># Update layout<br>fig.update_layout(height=800, width=1000, title_text=&quot;Sales Data Analysis Dashboard&quot;, showlegend=False)<br>fig.show() </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-PYK_v55lIK6vEB84cbQZA.png" /><figcaption>This dashboard provides a comprehensive overview of the sales data, highlighting key trends and insights that can inform business decisions and strategies</figcaption></figure><h3>Interpretation of the Dashboard</h3><p>The dashboard provides comprehensive insights into the sales data:</p><ul><li><strong>Quantity Ordered Distribution</strong>: Most orders are for single units.</li><li><strong>Price Each Distribution</strong>: Product prices vary widely, with many lower-priced items and a few high-priced ones.</li><li><strong>Top 10 Products Sold</strong>: Charging cables and batteries are in high demand.</li><li><strong>Monthly Sales Trends</strong>: Sales tend to increase towards the end of the year, with significant spikes in May and November</li></ul><p>By following these steps, you can gain valuable insights from your sales data and make data-driven decisions to drive business growth.</p><p>For the full code and analysis, check out my GitHub repository: <a href="https://github.com/EmmanuelAkalumhe/Basic-Descriptive-Sales-Data-Analysis-1">Basic-Descriptive-Sales-Data-Analysis-1 GitHub Repository</a></p><p>#DataAnalysis #Python #SalesData #Visualization #BusinessIntelligence #DataScience #JupyterLab #Plotly #Pandas #Seaborn #Matplotlib</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff42a48e23e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Data analysis to unmask the thrills of the English Premier League 2021–22 Season]]></title>
            <link>https://medium.com/@akalumheemmanuel/using-data-analysis-to-unmask-the-thrills-of-the-english-premier-league-2021-22-season-f05f771db325?source=rss-47f639a5724c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f05f771db325</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[english-premier-league]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[football]]></category>
            <dc:creator><![CDATA[Emmanuel Akalumhe]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 16:33:49 GMT</pubDate>
            <atom:updated>2024-04-27T16:33:49.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MLc_Km_XwboB-cdtKrwGw.jpeg" /><figcaption>Picture credit unsplash.com</figcaption></figure><p>Over the weekend, I came across this dataset on Kaggle named: “ EPL ⚽ 2021–22 ⭐ English Premier League “. It included three CSV files: “all_match_results.csv,” “all_players_stats.csv,” and “points_table.csv.” You can find the dataset here: “<a href="https://www.kaggle.com/datasets/azminetoushikwasi/epl-21-22-matches-players">https://www.kaggle.com/datasets/azminetoushikwasi/epl-21-22-matches-players</a>.” Curiosity got the best of me, so I decided to dive in and see what I could uncover about the English Premier League 2021–22 season.</p><p>After analyzing the dataset The English Premier League (EPL) 2021–22 season was nothing short of a rollercoaster ride, filled with moments of sheer brilliance and nail-biting excitement. In this analysis, we take a closer look at the season’s standout moments and trends, giving you a glimpse into the captivating world of football.</p><p>With 20 teams and a whopping 613 players in the mix, the EPL truly showcased the best of the best. A total of 1399 goals and 105 penalties added to the drama on the field, keeping fans on the edge of their seats throughout the season.</p><p>One burning question on my mind was which position saw the most action in front of the goal. My Analysis revealed that Attacking midfielders, Wingers and forwards stole the spotlight, notching up a remarkable 491 goals between them. At the forefront of this goal-scoring was Liverpool’s Mohamed Salah, whose 31 goals earned him the title of the league’s top scorer.</p><p>But it wasn’t all about individual brilliance. I also delved into the intriguing relationship between player positions and disciplinary actions. While I found a slight tendency for certain positions to receive fewer yellow cards, the link wasn’t strong. On the other hand, defenders who graced the pitch more frequently found themselves in the referee’s book more often, hinting at the physicality of their role.</p><p>In terms of disciplinary actions, my analysis revealed that the player with the most yellow cards was James Tarkowski, a defender from Burnley. This highlighted the physical nature of defending and the challenges players face in maintaining discipline on the field</p><p>Further examination led us to explore the ratio of goals to appearances, shedding light on the efficiency of players in front of goal. Aston Villa’s Cameron Archer emerged as a standout performer in this regard, boasting a remarkable ratio of 2.0 goals per appearance, underlining his clinical finishing ability.</p><p>My analysis didn’t stop there. I also zoomed in on how individual player contributions shaped their respective clubs’ performances. Manchester City emerged as the powerhouse, racking up an impressive 146 goals. Meanwhile, Liverpool’s Mohamed Salah continued to dazzle, leading his team’s charge with his remarkable goal-scoring ability.</p><p>Here are the top 5 goal scorers of the season along with their team names:</p><ol><li>Mohamed Salah (Liverpool) — 31 goals</li><li>Harry Kane (Tottenham Hotspur) — 27 goals</li><li>Cristiano Ronaldo (Manchester United) — 24 goals</li><li>Riyad Mahrez (Manchester City) — 24 goals</li><li>James Maddison (Leicester City) — 18 goals</li></ol><p>In my analysis I also shed light on the importance of player versatility, with those capable of playing multiple positions making more appearances on average. And let’s not forget about Chelsea, the team awarded the most penalties, showcasing their attackers attacking flair and ability to draw fouls in the opposition penalty box during the season.</p><p>In essence, my analysis paints a vivid picture of the EPL 2021–22 season, offering insights into the magic of football. While individual brilliance certainly shone, it was the collective effort and strategic gameplay of every manager and their backroom staff that truly defined success on the football pitch.</p><p>This is a link to my GitHub profile so you can take a more in-depth look at other aspects of my analysis: “<a href="https://github.com/EmmanuelAkalumhe/epl2021-2022_2.git">https://github.com/EmmanuelAkalumhe/epl2021-2022_2.git</a>”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f05f771db325" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>