<?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 Abdulkabirdauda on Medium]]></title>
        <description><![CDATA[Stories by Abdulkabirdauda on Medium]]></description>
        <link>https://medium.com/@abdulkabirdauda1?source=rss-ab038533369f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pgWTHZgBx4-2XIJE</url>
            <title>Stories by Abdulkabirdauda on Medium</title>
            <link>https://medium.com/@abdulkabirdauda1?source=rss-ab038533369f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:19:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdulkabirdauda1/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[FROM BRUTE FORCE TO SMART THINKING: HOW BIG_O AND HASH MAPS FIXED MY SQL THAT KEPT FAILING.]]></title>
            <link>https://blog.gopenai.com/from-brute-force-to-smart-thinking-how-big-o-and-hash-maps-fixed-my-sql-that-kept-failing-c28f66b54d41?source=rss-ab038533369f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c28f66b54d41</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Abdulkabirdauda]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 00:32:15 GMT</pubDate>
            <atom:updated>2026-11-22T00:32:15.245Z</atom:updated>
            <content:encoded><![CDATA[<p>FROM BRUTE FORCE TO SMART THINKING: HOW BIG_O AND HASH MAPS FIXED MY SQL THAT KEPT FAILING.</p><h3>Table of Contents</h3><p>1. 1. Introduction</p><p>2. 2. Overview of Week 11: Data Structures and Algorithms 1</p><p>3. 3. Understanding Algorithms and Big-O Notation</p><p>4. 4. Working with Arrays, Strings and Two Pointers</p><p>5. 5. Hash Maps and Sets</p><p>6. 6. Understanding Linked Lists</p><p>7. 7. Stacks and Queues</p><p>8. 8. Recursion and Divide-and-Conquer</p><p>9. 9. Searching and Binary Search</p><p>10. 10. Practical DSA Problems Solved During the Week</p><p>11. 11. SQL Practice: Applying Data Analysis Techniques</p><p>12. 12. Challenges Encountered and How I Overcame Them</p><p>13. 13. Key Lessons and Takeaways</p><p>14. 14. Conclusion</p><h3>Introduction</h3><p>This week, my learning journey with DataraFlow took me deeper into an important area of programming and data science: Data Structures and Algorithms (DSA).</p><p>Understanding programming syntax is only one part of becoming a good programmer. It is equally important to understand how data is organised, how algorithms process information, and how to choose an efficient approach when solving a problem.</p><p>Week 11 introduced me to these concepts through Data Structures and Algorithms 1. The materials covered algorithm analysis, Big-O notation, arrays, strings, two pointers, hash maps, sets, linked lists, stacks, queues, recursion, divide-and-conquer, searching, and binary search.</p><p>I also worked on a take-home assignment involving ten Data Structures and Algorithms problems and four additional SQL practice tasks.</p><p>What made this week particularly interesting was that I had to think beyond writing code that produces the correct answer. I needed to understand why a particular approach works, how much time and memory it uses, and whether there is a more efficient way to solve the same problem.</p><h3>2. Overview of Week 11: Data Structures and Algorithms 1</h3><p>Data Structures and Algorithms are fundamental to programming because they help us organise information and solve problems efficiently. A data structure determines how information is stored and accessed, while an algorithm describes the steps used to solve a problem.</p><p>For example, imagine having a list of agricultural commodity prices and wanting to identify the highest price, locate a particular commodity, or calculate the highest average price over a period. The way the data is organised and the algorithm selected can affect how efficiently these operations are performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Fsz8vHkVSgnos_rVSioPmw.png" /></figure><h3>3. Understanding Algorithms and Big-O Notation</h3><h3>3.1 What is an algorithm?</h3><p>An algorithm is a sequence of instructions or steps used to solve a particular problem. In programming, an algorithm explains how a task should be completed before or while writing the actual code.</p><p>For example, consider finding the largest number in a list:</p><p>numbers = [12, 45, 23, 67, 34]</p><p>largest = numbers[0]</p><p>for number in numbers:</p><p>if number &gt; largest:</p><p>largest = number</p><p>print(largest)</p><p>Output: 67</p><p>The algorithm starts with the first number as the largest, compares every other number with it, updates the largest value whenever a bigger number is found, and returns the result after checking all the numbers. This shows that an algorithm is not simply Python syntax; it is a logical process for producing the expected result.</p><h3>3.2 Understanding Big-O notation</h3><p>Big-O notation describes how the running time or memory requirements of an algorithm grow as the input size increases. It helps us compare different approaches to solving the same problem.</p><p><strong>O(1) : It means Constant time e.g Accessing an item by list index</strong></p><p><strong>O(log n) : It means Logarithmic time e.g Binary search</strong></p><p><strong>O(n) : It means Linear time e.g Checking every item in a list</strong></p><p><strong>O(n log n) : It means Linearithmic time e.g Efficient sorting algorithms</strong></p><p><strong>O(n²): It means Quadratic time e.g Comparing every item with every other item using nested loops</strong></p><p>Example of O(1):</p><p>numbers = [10, 20, 30, 40, 50]</p><p>print(numbers[2])</p><p>Output: 30. The program accesses the item at index 2 directly; it does not need to check every other item.</p><p>Example of O(n):</p><p>numbers = [10, 20, 30, 40, 50]</p><p>for number in numbers:</p><p>print(number)</p><p>The program visits every item. If the list grows, the number of operations grows with it.</p><p>Example of O(n²):</p><p>numbers = [1, 2, 3]</p><p>for first in numbers:</p><p>for second in numbers:</p><p>print(first, second)</p><p>The nested loops compare every element with every element. Three elements produce nine combinations, and the number of operations grows quadratically as the input increases.</p><p>3.3 Time complexity and space complexity</p><p>Time complexity describes how the number of operations grows as the input size increases. Space complexity describes how much additional memory an algorithm requires.</p><p>For example, returning the first item from a list takes constant time and constant extra space:</p><p>def find_first(numbers):</p><p>return numbers[0]</p><p>However, copying every item into a new list requires additional memory that grows with the input:</p><p>def copy_numbers(numbers):</p><p>result = []</p><p>for number in numbers:</p><p>result.append(number)</p><p>return result</p><p>Understanding both time and space complexity helped me realise that a good solution should not only produce the correct output but should also use computational resources appropriately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*u1TkfKRM21lkeRsCMPGX8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*XmnYDb0Vqp0GMPHA2-kdEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*L-Y9wzbWGJEfrneqjYCyFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*xjhl62LQ0hFqg6AQ3thuZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*YmEPz8_J4CkmMU2QAryQfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*7CqmCmjICmwPh6IO_ebx9w.png" /></figure><h3>4. Working with Arrays, Strings and Two Pointers</h3><h3>4.1 Arrays and strings</h3><p>Arrays store collections of elements in a sequence. In Python, lists are commonly used for this purpose.</p><p>prices = [250, 300, 280, 350, 400]</p><p>print(prices[0])</p><p>print(prices[2])</p><p>Output: 250 and 280. Each item has an index, starting from zero.</p><p>Strings are sequences of characters:</p><p>commodity = “MAIZE”</p><p>print(commodity[0])</p><p>print(commodity[-1])</p><p>Output: M and E. Understanding arrays and strings is important because many programming problems involve searching, comparing, updating, or processing sequential data.</p><h3>4.2 The two-pointer technique</h3><p>The two-pointer technique uses two positions to process data, often avoiding unnecessary nested loops. Suppose we have a sorted list of prices and want to identify two values that add up to a target:</p><p>def pair_with_sum(sorted_nums, target):</p><p>left = 0</p><p>right = len(sorted_nums) — 1</p><p>while left &lt; right:</p><p>current_sum = sorted_nums[left] + sorted_nums[right]</p><p>if current_sum == target:</p><p>return (left, right)</p><p>elif current_sum &lt; target:</p><p>left += 1</p><p>else:</p><p>right -= 1</p><p>return None</p><p>Example: pair_with_sum([10, 20, 30, 40, 50], 70) returns (1, 4), corresponding to 20 and 50. One pointer starts at the beginning and the other at the end. If the sum is too small, the left pointer moves forward. If it is too large, the right pointer moves backwards. Because the input is sorted, each movement eliminates values that cannot produce the target with the current opposite pointer.</p><p>The time complexity is O(n), with O(1) extra space.</p><h3>4.3 The sliding window technique</h3><p>Sliding window is useful when we need to analyse consecutive elements in a sequence. Suppose daily sales figures are [2, 1, 5, 1, 3, 2], and we want the largest total for any three consecutive days.</p><p>def max_window_sum(nums, k):</p><p>if k &lt;= 0 or k &gt; len(nums):</p><p>return None</p><p>window_sum = 0</p><p>for i in range(k):</p><p>window_sum += nums[i]</p><p>max_sum = window_sum</p><p>for i in range(k, len(nums)):</p><p>window_sum = window_sum — nums[i-k] + nums[i]</p><p>max_sum = max(max_sum, window_sum)</p><p>return max_sum</p><p>Calling max_window_sum([2, 1, 5, 1, 3, 2], 3) returns 9. The window totals are 8, 7, 9, and 6. Instead of adding all three values again for every window, the algorithm subtracts the value leaving the window and adds the new value entering it. This makes the algorithm O(n) in time and O(1) in extra space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*Vb5hJC01ynX1wQe-jgEurA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*6zXiKQov9CPEhDfYRjYiFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*OW9UqEQFle3Q7xVJAm8p3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*VDmXebgruSsGDUFRVSBXTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*-E8ys6eZUWNBgL9pJD1X5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*jv41_4srltaSZ2ui4OQkJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*Tf_A-ZFkUvhQh1TAPeGpAw.png" /></figure><h3>5. Hash Maps and Sets</h3><h3>5.1 Understanding hash maps</h3><p>In Python, a dictionary is an example of a hash map. It stores information using key-value pairs.</p><p>commodity_prices = {</p><p>“Maize”: 450,</p><p>“Rice”: 900,</p><p>“Beans”: 750</p><p>}</p><p>print(commodity_prices[“Maize”])</p><p>Output: 450. The commodity name is the key, while the price is the value. Hash maps are useful when we want to retrieve information using a specific key or group related information.</p><h3>5.2 Understanding sets</h3><p>A set stores unique values. Duplicate values are automatically removed.</p><p>numbers = [1, 2, 2, 3, 4, 4, 5]</p><p>unique_numbers = set(numbers)</p><p>print(unique_numbers)</p><p>The resulting set contains 1, 2, 3, 4, and 5. Sets also provide efficient membership checking on average:</p><p>numbers = {10, 20, 30, 40}</p><p>print(30 in numbers)</p><p>print(50 in numbers)</p><p>Output: True and False.</p><h3>5.3 Practical application: Grouping anagrams</h3><p>The take-home assignment required grouping words that contain the same letters. For example, “eat”, “tea”, and “ate” are anagrams.</p><p>def group_anagrams(words):</p><p>groups = {}</p><p>for word in words:</p><p>key = ‘’.join(sorted(word))</p><p>if key not in groups:</p><p>groups[key] = []</p><p>groups[key].append(word)</p><p>return list(groups.values())</p><p>Sorting the letters produces the same key for words that are anagrams: eat, tea, and ate all become aet. The dictionary stores words with the same key in the same group. The time complexity is O(n × L log L), where n is the number of words and L is the maximum word length.</p><h3>5.4 Practical application: Finding the longest consecutive sequence</h3><p>Another problem required finding the longest sequence of consecutive integers in an unsorted list. For [100, 4, 200, 1, 3, 2], the longest sequence is 1, 2, 3, 4, so the answer is 4.</p><p>def longest_consecutive(nums):</p><p>values = set(nums)</p><p>longest = 0</p><p>for num in values:</p><p>if num — 1 not in values:</p><p>current = num</p><p>streak = 1</p><p>while current + 1 in values:</p><p>current += 1</p><p>streak += 1</p><p>longest = max(longest, streak)</p><p>return longest</p><p>The set removes duplicates and supports fast membership checks on average. The algorithm only starts counting when the previous number is absent, so it starts at the beginning of each sequence. Although there is a while loop inside a for loop, each number is traversed as part of a sequence at most once. Average time complexity is O(n), with O(n) extra space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*bvH9NgwmMGX6MSyrL3_oQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*QNoF53AUGPKMalk40osdBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*m2P-8uWz3xv3NxIh3JU95g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*tBiTSE2GUAJybCL1rBFE8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*IbRqBKiTrqv-_gpVjDmafQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*Ij37hidsP0xBUSiDYM2B7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*iT635McP_kdH3G6dIrO4cA.png" /></figure><h3>6. Understanding Linked Lists</h3><h3>6.1 What is a linked list?</h3><p>A linked list is a data structure made up of individual elements called nodes. Each node contains a value and a reference to the next node. A simple linked list looks like 10 → 20 → 30 → None. Unlike a Python list, its elements are connected through references rather than accessed primarily through positions.</p><h3>6.2 Reversing a linked list</h3><p>One take-home problem required reversing a singly linked list in place. The original list 1 → 2 → 3 → None should become 3 → 2 → 1 → None.</p><p>def reverse_list(head):</p><p>prev = None</p><p>current = head</p><p>while current is not None:</p><p>next_node = current.next</p><p>current.next = prev</p><p>prev = current</p><p>current = next_node</p><p>return prev</p><p>The solution uses three pointers: prev, current, and next_node. The next node must be saved before changing the current node’s reference. Otherwise, the remaining part of the linked list could become inaccessible. At the end, prev points to the new head. The algorithm visits every node once, giving O(n) time and O(1) extra space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*-k3nIBVoqWz0tivJLmKZNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*SPQcaGvcty9xaPA8whVAyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*LnuZO4ijaupIGlauAy2yCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*56QHS7hUBUH4zA-pWCaoPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*wPHswR4Ay2G7LMSFIM3AHA.png" /></figure><h3>7. Stacks and Queues</h3><h3>7.1 Understanding stacks</h3><p>A stack follows Last In, First Out (LIFO). The last element added is the first element removed. A pile of plates is a familiar example: the last plate placed on top is usually the first one removed.</p><p>stack = []</p><p>stack.append(10)</p><p>stack.append(20)</p><p>stack.append(30)</p><p>print(stack.pop())</p><p>Output: 30.</p><h3>7.2 Understanding queues</h3><p>A queue follows First In, First Out (FIFO). The first element added is the first element removed, just like people waiting to be served.</p><p>from collections import deque</p><p>queue = deque()</p><p>queue.append(“First”)</p><p>queue.append(“Second”)</p><p>queue.append(“Third”)</p><p>print(queue.popleft())</p><p>Output: First.</p><h3>7.3 Practical application: Balanced brackets</h3><p>The balanced-brackets problem required checking whether opening and closing brackets were correctly matched. For example, ([]), and ((())) are balanced, while ([)] is not.</p><p>def is_balanced(text):</p><p>stack = []</p><p>matching = {</p><p>‘)’: ‘(‘,</p><p>‘]’: ‘[‘,</p><p>‘}’: ‘{‘</p><p>}</p><p>for char in text:</p><p>if char in “([{“:</p><p>stack.append(char)</p><p>elif char in “)]}”:</p><p>if not stack or stack[-1] != matching[char]:</p><p>return False</p><p>stack.pop()</p><p>return len(stack) == 0</p><p>Opening brackets are added to the stack. Each closing bracket must match the most recently opened bracket. If it does not match, the string is unbalanced. The algorithm takes O(n) time and O(n) extra space in the worst case.</p><h3>7.4 Practical application: Daily temperatures</h3><p>The daily temperatures problem asked how many days someone would wait until a warmer temperature occurred. For [73, 74, 75, 71, 69, 72, 76, 73], the expected output is [1, 1, 4, 2, 1, 1, 0, 0].</p><p>def daily_temperatures(temps):</p><p>answer = [0] * len(temps)</p><p>stack = []</p><p>for i, temp in enumerate(temps):</p><p>while stack and temps[stack[-1]] &lt; temp:</p><p>previous_day = stack.pop()</p><p>answer[previous_day] = i — previous_day</p><p>stack.append(i)</p><p>return answer</p><p>The stack stores indices of days still waiting for a warmer temperature. When a warmer temperature appears, the earlier day’s index is removed and the waiting period is calculated. Each index is pushed once and popped at most once, so the total time complexity is O(n).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*jmn9rkg60RFG30j7Tb9V1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*t7xA_I7UXgQrgY4VwBghLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*yXoIE0ScMvIQVexza9iz7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWPlhIkZ7Qv1zaaoQDzydg.png" /></figure><h3>8. Recursion and Divide-and-Conquer</h3><h3>8.1 Understanding recursion</h3><p>Recursion occurs when a function calls itself to solve a smaller version of the same problem.</p><p>def countdown(n):</p><p>if n == 0:</p><p>return</p><p>print(n)</p><p>countdown(n — 1)</p><p>countdown(3)</p><p>Output: 3, 2, 1. The function calls itself with a smaller number until it reaches zero.</p><h3>8.2 Base cases and recursive cases</h3><p>The base case is the condition that stops recursive calls. The recursive case is the part where the function calls itself with a smaller or simpler input. Without a base case, the function may continue calling itself until Python raises a recursion-depth error.</p><h3>8.3 Understanding divide-and-conquer</h3><p>Divide-and-conquer breaks a large problem into smaller subproblems, solves those smaller problems, and combines the results where necessary. Its general steps are to divide the problem, solve the smaller parts, and combine the results.</p><h3>8.4 Practical application: Flattening nested lists</h3><p>The take-home assignment included converting a nested list into a single flat list. For example, [1, [2, 3], [4, [5, 6]], 7] becomes [1, 2, 3, 4, 5, 6, 7].</p><p>def flatten(nested):</p><p>result = []</p><p>def visit(items):</p><p>for item in items:</p><p>if isinstance(item, list):</p><p>visit(item)</p><p>else:</p><p>result.append(item)</p><p>visit(nested)</p><p>return result</p><p>The function checks whether each item is another list. If it is, the function processes it recursively. Otherwise, it adds the item to the final result. The base case is an item that is not a list; the recursive case is an item that is another list. The time complexity is O(N), where N is the total number of items, and recursion space depends on the maximum nesting depth.</p><h3>8.5 Handling deeply nested lists</h3><p>A deeply nested list may exceed Python’s recursion-depth limit. An iterative approach can use an explicit stack instead of repeated recursive calls.</p><p>def flatten(nested):</p><p>result = []</p><p>stack = [iter(nested)]</p><p>while stack:</p><p>try:</p><p>item = next(stack[-1])</p><p>if isinstance(item, list):</p><p>stack.append(iter(item))</p><p>else:</p><p>result.append(item)</p><p>except StopIteration:</p><p>stack.pop()</p><p>return result</p><p>The explicit stack keeps track of nested lists that still need to be processed and avoids relying on Python’s recursive function-call depth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*oQP2IKYXi09OOg8ilDNxoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*oHVG7JRA-D4La24i_7ihxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*TeKYHZTzfXzsgTaCGurDnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*On9GVepSii55YLMLgM3b1g.png" /></figure><h3>9. Searching and Binary Search</h3><h3>9.1 Linear search</h3><p>Linear search checks elements one after another until the target is found or the collection is exhausted.</p><p>numbers = [10, 20, 30, 40, 50]</p><p>target = 30</p><p>for i, number in enumerate(numbers):</p><p>if number == target:</p><p>print(i)</p><p>break</p><p>Output: 2. Worst-case time complexity is O(n), because the algorithm may need to check every element.</p><h3>9.2 Binary search</h3><p>Binary search works on sorted data. It repeatedly divides the search space into two halves. If the middle value is smaller than the target, the search continues in the right half; if it is larger, the search continues in the left half. This gives O(log n) time complexity.</p><h3>9.3 Finding the first and last position of a target</h3><p>One take-home problem required finding the first and last positions of a target in a sorted list containing duplicates. For [1, 2, 2, 2, 3, 4, 5], the target 2 should return (1, 3).</p><p>import bisect</p><p>def search_range(nums, target):</p><p>left = bisect.bisect_left(nums, target)</p><p>if left == len(nums) or nums[left] != target:</p><p>return (-1, -1)</p><p>right = bisect.bisect_right(nums, target) — 1</p><p>return (left, right)</p><p>bisect_left identifies the insertion position before the first occurrence. bisect_right identifies the insertion position after the last occurrence. Subtracting one from the right position gives the last index. The overall time complexity is O(log n), with O(1) extra space.</p><h3>9.4 Binary search on the answer</h3><p>Binary search can also search through a range of possible answers rather than searching for an existing item in a list. The take-home assignment applied this idea to finding the smallest truck capacity needed to transport parcels in their original order within a given number of days.</p><p>For weights [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and five days, the minimum capacity is 15.</p><p>def ship_capacity(weights, days):</p><p>if not weights:</p><p>return 0</p><p>left = max(weights)</p><p>right = sum(weights)</p><p>while left &lt; right:</p><p>capacity = (left + right) // 2</p><p>used_days = 1</p><p>current_load = 0</p><p>for weight in weights:</p><p>if current_load + weight &gt; capacity:</p><p>used_days += 1</p><p>current_load = 0</p><p>current_load += weight</p><p>if used_days &lt;= days:</p><p>right = capacity</p><p>else:</p><p>left = capacity + 1</p><p>return left</p><p>The minimum possible capacity is the heaviest parcel because every parcel must fit. The maximum possible capacity is the sum of all parcel weights because the truck could carry everything in one day. For each candidate capacity, the algorithm simulates loading parcels in order and counts the days required. If the capacity works, it searches for a smaller one; otherwise, it searches for a larger one.</p><p>The key property is monotonicity: if a capacity works, any larger capacity will also work. The time complexity is O(n log S), where n is the number of parcels and S is the sum of their weights. Extra space is O(1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*p0JYoq0U2qQw0sz_mUCjBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*z32W8Kfx9P2Uc6qWfu_3yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*K1Zeblr2pUHKHf000T3TiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*E8d3q9IR0r_V9XjuVjk-2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*EcnAQGWU6-FDwv51BViC5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*XB5k4AHZFZAe-XdGae87dQ.png" /></figure><h3>10. Practical DSA Problems Solved During the Week</h3><p>After studying the concepts, I applied them to ten practical problems in the Week 11 take-home assignment. The problems tested my ability to identify the appropriate data structure or algorithm for each task.</p><p>The followings are the problems and tecniques i used</p><ol><li>Best k-day sales and the tecniques used is sliding window</li></ol><p><strong>2. </strong>Two prices that hit a total and the tecniques used is two pointers</p><p><strong>3. </strong>Group anagrams and the tecniques used is dictionary and sorting</p><p><strong>4. </strong>Longest run of IDs and the tecniques used is set</p><p><strong>5. </strong>Reverse a linked list and the tecniques used is three pointers</p><p><strong>6. </strong>Balanced brackets and the tecniques used is stack</p><p><strong>7. </strong>Daily temperatures and the tecniques used is monotonic stack</p><p><strong>8. </strong>Flatten nested basket and the tecniques used is recursion and explicit stack</p><p><strong>9. </strong>First and last position and the tecniques used is binary search using bisect</p><p><strong>10. </strong>Smallest truck capacity and the tecniques used is binary search on the answer</p><h3>My approach to solving the problems</h3><p>I did not approach the assignment as a collection of unrelated coding questions. I tried to understand the requirement of each problem and identify the most suitable technique.</p><p>· When the problem involved consecutive elements, I considered sliding window.</p><p>· When the input was sorted and required finding two values, I considered two pointers.</p><p>· When words needed to be grouped by a common property, I used a dictionary.</p><p>· When I needed fast membership checking, I used a set.</p><p>· When the problem involved reversing connections, I used pointers.</p><p>· When the problem required matching opening and closing symbols, I used a stack.</p><p>· When the problem involved nested lists, I used recursion.</p><p>· When the data was sorted, I considered binary search.</p><p>· When the answer was within a possible range and feasibility was monotonic, I used binary search on the answer.</p><p>This helped me understand that selecting the right technique is an important part of problem-solving.</p><h3>11. SQL Practice: Applying Data Analysis Techniques</h3><p>In addition to the DSA problems, Week 11 included four SQL practice tasks. These exercises allowed me to apply SQL concepts to weather and international trade datasets. They involved aggregation, filtering, CTEs, subqueries, window functions, and date-based analysis.</p><h3>11.1 Task 1: Grouping London temperature records</h3><p>The first task involved analysing the London 2014 weather dataset. The objective was to group records by maximum temperature, count the number of days for each temperature, and return only temperature groups that occurred at least 20 times.</p><p>SELECT</p><p>[Max TemperatureC] AS max_temp_c,</p><p>COUNT(*) AS days</p><p>FROM week06.london_2014</p><p>GROUP BY [Max TemperatureC]</p><p>HAVING COUNT(*) &gt;= 20</p><p>ORDER BY days DESC, max_temp_c DESC;</p><p>The query uses SELECT to choose columns, COUNT(*) to count records, GROUP BY to group records by temperature, HAVING to filter groups based on their counts, and ORDER BY to sort the output. An important lesson was the difference between WHERE and HAVING: WHERE filters individual records before grouping, while HAVING filters groups after aggregation.</p><h3>11.2 Task 2: Identifying new UK milk export partners in 2015</h3><p>The second task involved comparing UK milk export records from 2014 and 2015. The objective was to identify partners present in the January–May 2015 records but absent from the 2014 export records. The required calculations were total export value in thousands of US dollars and the number of distinct months with exports.</p><p>The major concepts were CTEs, aggregation, NOT EXISTS, COUNT(DISTINCT …), and filtering by period. The core exclusion condition was:</p><p>AND NOT EXISTS (</p><p>SELECT 1</p><p>FROM week09.countrymilk AS c</p><p>WHERE c.Partner = e.Partner</p><p>AND c.[Trade Flow] = ‘Exports’</p><p>AND c.period &gt;= 201401</p><p>AND c.period &lt;= 201412</p><p>)</p><p>NOT EXISTS checks whether the same partner appears in the 2014 export records. If a matching record exists, the partner is excluded. If no matching record exists, the partner can remain in the 2015 results. COUNT(DISTINCT period) is important because a partner may have several export records in one month, but that month should only be counted once.</p><p>This task demonstrated how SQL can compare datasets across different periods and identify changes in trading relationships.</p><h3>11.3 Task 3: Monthly exports, running totals and three-month totals</h3><p>The third task focused on analysing UK milk exports throughout 2014. The required output included monthly export values in millions of US dollars, running cumulative export totals, and three-month export totals.</p><p>The main SQL concepts were window functions, SUM() OVER(), LAG(), ROW_NUMBER(), and CASE. A running total can be calculated using:</p><p>SUM(exports_musd) OVER (</p><p>ORDER BY period</p><p>ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW</p><p>) AS running_total_musd</p><p>This calculates the cumulative export value from the first month through the current month. For the three-month calculation, LAG retrieves the running total from three rows earlier:</p><p>LAG(running_total_musd, 3, 0) OVER (</p><p>ORDER BY period</p><p>)</p><p>Subtracting that earlier running total from the current running total gives the current month and the two preceding months. January and February were required to return NULL because there were not yet three months of data. This exercise helped me understand how window functions perform calculations across rows while retaining individual monthly records.</p><h3>11.4 Task 4: Finding the warmest seven-day period across six cities</h3><p>The final SQL task involved weather records for Beijing, Brasilia, Cape Town, Delhi, London, and Moscow. The objective was to identify the seven-day period with the highest average mean temperature for each city.</p><p>The major concepts were UNION ALL, Common Table Expressions, date conversion, AVG() OVER(), PARTITION BY, ROWS BETWEEN, COUNT() OVER(), and ROW_NUMBER(). The first step was combining the six city datasets into one dataset using UNION ALL. The next step was calculating a seven-row moving average separately for each city.</p><p>AVG(1.0 * temp) OVER (</p><p>PARTITION BY city</p><p>ORDER BY day</p><p>ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING</p><p>) AS avg_mean_temp_c</p><p>PARTITION BY city separates calculations by city. ORDER BY day arranges records chronologically. ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING selects the current record and the next six records. A count window identifies complete seven-row windows, and ROW_NUMBER ranks the periods. Selecting rank 1 returns the highest-ranked period for each city.</p><p>This calculation assumes the city tables contain one valid daily record per calendar day without missing dates, because a ROWS frame counts records rather than calendar days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*QawfsMJFlbPXTnE-7yeIoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*rqixVlw57zcxwDEdVVbN8Q.png" /></figure><p>12. Challenges Encountered and How I Overcame Them</p><h3>12.1 Understanding time and space complexity</h3><p>One of the first challenges was understanding how to evaluate algorithm efficiency. It was easy to focus on whether a program produced the correct result, but Big-O required me to consider how the number of operations would increase as the input became larger. I addressed this by examining simple examples of O(1), O(log n), O(n), and O(n²), then comparing how different approaches behave as input size increases.</p><h3>12.2 Understanding nested loops and overall complexity</h3><p>Some algorithms contained loops inside other loops or a while loop inside a for loop. This initially made complexity analysis less straightforward. For example, the longest consecutive sequence problem contains a while loop inside a for loop, but it is still O(n) on average because the algorithm starts counting only at the beginning of each sequence and each number is traversed at most once as part of a sequence.</p><h3>12.3 Understanding pointers and linked lists</h3><p>Linked lists required a different way of thinking because their nodes are connected through references. Reversing a linked list was particularly important because changing a reference in the wrong order can cause the remaining nodes to become inaccessible. I worked through the roles of prev, current, and next_node and followed how the references change at each iteration.</p><h3>12.4 Understanding stacks and monotonic stacks</h3><p>Stacks were easier to understand when related to practical examples such as a pile of plates. Applying a stack to daily temperatures required more careful reasoning. The stack stores indices of days waiting for a warmer temperature. When a warmer day appears, the waiting days are removed and their waiting periods are calculated.</p><h3>12.5 Understanding recursion and its limitations</h3><p>Recursion required me to trace how a function enters nested data and returns to the previous level. I addressed this by identifying the base case and recursive case separately. I also learned that deeply nested data may exceed Python’s recursion-depth limit, so an explicit stack can provide an iterative alternative.</p><h3>12.6 Understanding binary search on the answer</h3><p>The smallest truck capacity problem was challenging because it was different from ordinary binary search. Instead of searching for a value in a sorted list, I had to search through a range of possible truck capacities. I understood the minimum and maximum possible capacities and the monotonic relationship between capacity and feasibility.</p><h3>12.7 Combining multiple SQL concepts</h3><p>The SQL exercises required combining several techniques in the same query. The trade analysis involved filtering, grouping, aggregation, and NOT EXISTS. The running-total exercise required multiple CTEs and window functions. The six-city weather exercise required combining datasets before performing calculations separately for each city. Breaking each query into smaller stages made the longer queries easier to understand and organise.</p><h3>13. Key Lessons and Takeaways</h3><p>1. <strong>Choosing the right data structure matters. </strong>A list, dictionary, set, linked list, stack, and queue have different characteristics. Choosing the right one can make a solution more efficient and easier to understand.</p><p>2. <strong>Correctness and efficiency are different. </strong>A program may produce the correct output but still be inefficient. Big-O notation helps evaluate how an algorithm performs as the input grows.</p><p>3. <strong>Avoid unnecessary repeated work. </strong>Techniques such as sliding window and two pointers can reduce repeated calculations and comparisons.</p><p>4. <strong>Sets and dictionaries are powerful tools. </strong>They make it easier to organise information, group related values, remove duplicates, and check whether an item exists.</p><p>5. <strong>Understanding references is important. </strong>Linked lists helped me understand how nodes connect through references and why the order of pointer updates matters.</p><p>6. <strong>Stacks are useful for problems involving order and matching. </strong>Balanced brackets and daily temperatures demonstrated two different applications of stack-based problem-solving.</p><p>7. <strong>Recursion requires a clear stopping condition. </strong>Every recursive solution needs a base case. Deep recursion may also require an iterative alternative.</p><p>8. <strong>Binary search is more than searching sorted lists. </strong>It can also identify the smallest or largest feasible answer when the problem has a monotonic condition.</p><p>9. <strong>SQL window functions support advanced data analysis. </strong>Running totals, moving averages, rankings, and previous-row comparisons can be handled using window functions.</p><p>10. <strong>Breaking complex problems into smaller steps improves understanding. </strong>The DSA and SQL exercises became easier when I separated each problem into its requirements, technique, implementation, and expected result.</p><h3>14. Conclusion</h3><p>Week 11 was an important stage in my DataraFlow learning journey because it helped me move from understanding Python programming concepts to thinking more deeply about algorithm design and efficiency.</p><p>I learned how different data structures work, how to analyse algorithms using Big-O notation, and how techniques such as sliding window, two pointers, hash maps, sets, stacks, recursion, and binary search can be applied to practical problems.</p><p>The ten DSA take-home problems gave me an opportunity to apply these concepts in code, while the four SQL practice tasks strengthened my ability to analyse weather and international trade datasets using aggregation, CTEs, subqueries, and window functions.</p><p>One of my biggest lessons from this week is that solving a programming problem is not just about finding a way to make the code work. It is about understanding the problem, selecting an appropriate technique, evaluating its efficiency, and being able to explain why the solution works.</p><p>I also realised that becoming better at programming requires consistent practice, patience, and the ability to break complex problems into smaller, understandable steps.</p><p>As I continue my learning journey in Data Science, Machine Learning, and Generative AI, I believe these foundations in Data Structures and Algorithms will be valuable in helping me write better code and solve more complex computational problems.</p><p><strong><em>Week 11 taught me to think not only about what my code does, but also about how efficiently and logically it does it.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c28f66b54d41" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/from-brute-force-to-smart-thinking-how-big-o-and-hash-maps-fixed-my-sql-that-kept-failing-c28f66b54d41">FROM BRUTE FORCE TO SMART THINKING: HOW BIG_O AND HASH MAPS FIXED MY SQL THAT KEPT FAILING.</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Surplus to Deficit: How the UK’s £272M Milk Trade Data Exposes Nigeria’s Dairy Dependency and…]]></title>
            <link>https://medium.com/@abdulkabirdauda1/from-surplus-to-deficit-how-the-uks-272m-milk-trade-data-exposes-nigeria-s-dairy-dependency-and-c03da9f30667?source=rss-ab038533369f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c03da9f30667</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[food-security]]></category>
            <category><![CDATA[nigeria]]></category>
            <category><![CDATA[global-trade-data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abdulkabirdauda]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 09:50:31 GMT</pubDate>
            <atom:updated>2026-10-31T09:50:31.747Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>From Surplus to Deficit: How the UK’s £272M Milk Trade Data Exposes Nigeria’s Dairy Dependency and Pathway to Self-Sufficiency”</strong></p><p>I scored 5/5 analyzing UK milk trade data with SQL. What I found explains why Nigeria spends $1.5B importing milk we could produce.</p><p>Table of Contents</p><p>The Problem Nobody Is Graphing (Introduction)</p><p>Untill I Meet Some Dataset</p><p>Understanding the Split-Apply-Combine Pattern</p><p>Working with Heterogeneous Data</p><p>The Visual Proof</p><p>Creating Summary Reports</p><p>Method: 5 SQL Queries That Broke The Story</p><p>Conditional Aggregation</p><p>Grouping Sets and Quarterly Reporting</p><p>Window Functions and Ranking</p><p>Grouping Top Partners and Calculating Shares</p><p>What I Solved: Week 8 Tasks</p><p>Part A: UK Milk Trade Analysis</p><p>SQL Task 1: Trade Flow and Milk Type Summary</p><p>SQL Task 2: Monthly Trade Balance</p><p>SQL Task 3: Quarterly and Annual Summary</p><p>SQL Task 4: Top Three Trade Partners</p><p>SQL Task 5: Top Five Export Partners and “Other”</p><p>Challenges I Faced</p><p>How I Overcame the Challenges</p><p>What I Would Do Differently</p><p>Key Takeaways and Advice for Other Learners</p><p>Conclusion</p><p><strong>The Problem Nobody Is Graphing (Introduction)</strong></p><p>Nigeria is one of the largest milk importer in West Africa. We spend over $1.5 billion annually importing dairy, yet our local production meets less than 10% of demand.For my Dataflow Week 8 project, I analyzed the UK-Nigeria milk trade from 2015 to 2024. The UK dataset alone contains over £272M worth of trade. The question I asked was simple: what does this data say about our dependency, and can SQL help us find a way out?</p><p>I worked with data more effectively through analysis, grouping, visualization, and summary reporting. This week helped me understand how to transform a dataset containing different categories of information into meaningful reports that answer specific questions.</p><p>One of the major concepts I explored was the Split-Apply-Combine pattern. This approach involves splitting a dataset into meaningful groups, applying an operation to each group, and combining the results into a summary.</p><p>I also worked on a practical trade analysis involving UK milk imports and exports. The dataset contained information about trade flows, partner countries, commodity codes, periods, and trade values. Rather than examining every individual record, I learned how to group the data and calculate summaries that could help explain trade patterns.</p><p>I also worked on visualizing the trade analysis involving UK imports and exports. This explains how i can make use of visualization tools such as bar ,pie ,histogram,heatmap and so on.</p><p>The SQL practice tasks further strengthened my understanding of aggregation, conditional calculations, common table expressions (CTEs), grouping sets, window functions, ranking, and percentage shares.</p><p>In this article, I will share what I learned, the tasks I worked on, the challenges I encountered, and the approaches that helped me complete the assignment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*1Tk_cruyrzCyUQ3dzqH0yw.png" /></figure><p><strong>Untill I Meet Some Dataset</strong></p><p>Understanding the Split-Apply-Combine Pattern</p><p>The Split-Apply-Combine pattern is a useful approach to data analysis. It consists of three stages:</p><p>- Split: Divide the dataset into groups based on one or more categories.<br>- Apply: Perform a calculation or operation on each group.<br>- Combine: Bring the results together into a summary table.</p><p>This approach is especially useful when a dataset contains multiple categories and I need to compare them.</p><p>For example, imagine a dataset containing the trade values of different countries. If I want to know the total trade value for each trade flow, I can group the records by trade flow, calculate the sum for each group, and combine the results.</p><p>In Python, using pandas, this can be represented as:</p><p>summary = df.groupby(“Trade Flow”)[“Trade Value (US$)”].sum()</p><p>Here, “groupby()” performs the splitting, “sum()” applies the calculation, and the resulting series contains the combined summary.</p><p>Example: If the dataset contains both imports and exports, this operation produces a total trade value for Imports and another total for Exports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*5o70Hk5X8otTIotbOxyOcQ.png" /></figure><p><strong>Working with Heterogeneous Data</strong></p><p>A heterogeneous dataset contains different types of information or categories within the same dataset.</p><p>For example, the trade dataset contained both import and export records. These records could not always be analyzed together when the question focused on only one trade flow.</p><p>If I wanted to identify the countries with the highest export values, I first needed to isolate export records. The same approach applied when analyzing imports.</p><p>In pandas, I could filter the dataset like this:</p><p>exports = df[df[“Trade Flow”] == “Exports”]</p><p>To work with imports:</p><p>imports = df[df[“Trade Flow”] == “Imports”]</p><p>These examples show why filtering is important before performing a group-level calculation. Without filtering or grouping appropriately, I could accidentally combine information that should be analyzed separately.</p><p>Example: Ranking the largest export partners requires comparing export values with other export values, rather than mixing import and export records in the same ranking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwApGIdFzGErHphP8oRwNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vkjx5TXKn6_o8_bskW31g.png" /></figure><p><strong>Creating Summary Reports</strong></p><p>A summary report helps convert a large dataset into a smaller and more understandable table.</p><p>Instead of reviewing every row, I can group the records by relevant categories and calculate totals, counts, averages, or other statistics.</p><p>For example, I may want to calculate the total trade value for each partner country:</p><p>partner_summary = (<br> df.groupby(“Partner”)[“Trade Value (US$)”]<br> .sum()<br> .reset_index()<br>)</p><p>This groups records by partner and calculates the total trade value for each one.</p><p>The result can be used to compare countries and identify those contributing the largest values.</p><p>Summary reports are useful because they:</p><p>- Reduce the complexity of large datasets.<br>- Make comparisons easier.<br>- Help identify important patterns.<br>- Provide a foundation for visualizations.<br>- Support more focused analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ehxkBMXLhGisHaUSvJ7kg.png" /></figure><p><strong>The Visual Proof</strong></p><p>After working with the UK milk trade data and creating summary reports, I moved on to data visualization.</p><p>Data visualization is an important part of data analysis because it helps communicate patterns and relationships that may not be immediately obvious from a table of numbers.</p><p>Visualization also depends on the tool you want to use.Some of the used tools include bar chat, histogram and more. More can be found in the image below.</p><p>A summary table can show the total trade value for each category, but a visualization can make it easier to compare categories, identify trends, and understand how values change over time.</p><p>In this part of the assignment, I worked with visual representations of the trade data. The visualizations helped me explore the differences between imports and exports and understand how the trade values varied across the available categories and periods.</p><p>Why Visualization Matters</p><p>Visualization helps transform numerical results into a form that is easier to interpret.</p><p>For example, if I have monthly import and export values, a table can show the exact figures for each month. A line chart, however, can make it easier to observe whether the values are increasing, decreasing, or fluctuating over time.</p><p>Similarly, a bar chart can help compare the trade values of different partners or product categories.</p><p>The choice of visualization depends on the question being answered.</p><p>- A line chart is useful for showing changes over time.<br>- A bar chart is useful for comparing categories.<br>- A grouped chart can help compare imports and exports across the same periods.<br>- A visualization of grouped data can make the results of the Split-Apply-Combine process easier to communicate.</p><p>Example: If I want to compare imports and exports across several months, I can use a line chart with the period on the horizontal axis and trade value on the vertical axis. Separate lines can represent imports and exports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S18YDXd5Vya83h18tS5mhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TyXkM2AHhLrVYP8SKphpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*3f1Dx8vo1rL7qslfFUgwNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*ux_JzCP1Af49aXci-FY2EA.png" /></figure><p><strong>Using Seaborn for Visualization</strong></p><p>The assignment also involved working with data visualization tools, including Seaborn.</p><p>Seaborn is a Python visualization library built on top of Matplotlib. It provides a convenient way to create statistical graphics and explore relationships in datasets.</p><p>For example, a bar plot can be created using Seaborn:</p><p>import seaborn as sns<br>import matplotlib.pyplot as plt</p><p>sns.barplot(<br> data=df,<br> x=”Trade Flow”,<br> y=”Trade Value (US$)”<br>)</p><p>plt.title(“Trade Value by Trade Flow”)<br>plt.xlabel(“Trade Flow”)<br>plt.ylabel(“Trade Value (US$)”)<br>plt.show()</p><p>This example compares trade values by trade flow. The specific chart used in an analysis should depend on whether the data has already been aggregated and what comparison is intended.</p><p>Example: A chart comparing Imports and Exports can help communicate the difference between the two categories more clearly than a long list of individual records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*ZVB_Ep7hMzi1zK6WUWj0cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiWKGirU2N4nM5sBCwQ2TA.png" /></figure><p>The distribution shows the milk trade values on a log scale. It shows most trades fall between 10⁴ to 10⁸ (10kto100MUS), with the peak around $10⁶ ($1M), indicating a typical log_normal distribution for trade data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*PqqyyNO9VFdzQdI1ZDwPbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*3qRATOCyl-YumFM9JaO7pw.png" /></figure><p>This KDE plot shows the probability of density of trade values on a log_scale. It comfirms a right_skewed,log_normal distribution with most trade values concentrated between $10⁴ and $10⁸, peaking around $10⁶ ($1M). The smooth curve shows the most frequent trade value is approximately $1 million, with fewer very small and very large transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*z8rKypACi_qGMvVRMQjWuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*M66nRO6nfvdETqggZIGMRw.png" /></figure><p>This boxplot shows distribution of FOB trade values on a log_scale. The median (middle line) is about $10⁶ ($1M). The box shows 50% of trades fall between $10⁵ and $10⁷ ($100k-$100M). The dots at the top are outliers- a few very high value trades up to $10¹⁰ ($10B).The long whisker at the bottom shows some vry small trades down to $10⁰ ($1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*uUmhXfzuwI_ymqQ14gyw_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*VSyWQW4LeXgM432fiSwSVQ.png" /></figure><p>The data was aggregated by month and trade flow (Import and Export) using groupby ([‘refMonth’, ‘flowCode]).sum(). The regression shows a weak positive relationship between monthly imports and exports. As monthly import increases, export values also show a slight increase, but the wide confidence interval(shaded area)and the scattered point indicate the relationship is not strong.Most monthly trade values cluster between $6B and $11B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*AEzvRQpRTabSZcGZfU-mDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*PAsXCiih9akyjWY7_8eX-Q.png" /></figure><p>This heatmap was created after aggregating the data by month (period) and trade flow (flowDesc) using groupby().sum(). The aggregation sums total FOB value per month for each flow. Darker blue indicates higehr trade value. Exports peaked in November and December2023 ($1.56<em>*10¹⁰) while impoerts peaked in May 2023 ($1.15*</em>10¹⁰). Tarde was consistently high throughout 2023, ranging between $5.6B and $15.6B per month for both flows, showing active two-way milk trade.</p><p><strong>Interpreting Visualizations</strong></p><p>Creating a chart is only one part of visualization. The other important part is interpreting what the chart communicates.</p><p>When examining a visualization, I need to consider:</p><p>- What categories or periods are being compared?<br>- Which category has the largest or smallest value?<br>- Are there visible changes over time?<br>- Are there any unusual patterns?<br>- Does the chart support the question being investigated?</p><p>For example, a monthly trade chart may show that imports and exports fluctuate over time. A grouped bar chart may reveal differences between processed and unprocessed milk products.</p><p>However, I should avoid making conclusions that are not supported by the data. A chart can show a pattern, but additional analysis may be required to explain why that pattern occurred.</p><p>This helped me understand that visualization is not simply about making charts look attractive. It is about using visual evidence to communicate information accurately.</p><p>What I Learnt from Visualization</p><p>The visualization part of the assignment helped me understand the relationship between data preparation, analysis, and communication.</p><p>Before creating a visualization, I need to ensure that the data is organized correctly. If the question is about monthly totals, the data should be summarized by month. If the question is about comparing trade flows, the categories should be clearly represented.</p><p>I also learned that different charts serve different purposes. A chart that works well for comparing categories may not be the best choice for showing a trend over time.</p><p>The key lesson was that visualizations should be selected based on the analytical question, not simply because a particular chart is available.</p><p><strong>Method: 5 SQL Queries That Broke The Story</strong></p><p>Another important part of Week 8 was applying SQL to answer questions about the trade datasets.</p><p>SQL allows me to retrieve, filter, group, and summarize data directly from a database. This is especially useful when the dataset is stored in a database rather than in a local CSV file.</p><p>For example:</p><p>SELECT<br> Partner,<br> SUM([Trade Value (US$)]) AS total_trade_value<br>FROM week09.countrymilk<br>GROUP BY Partner<br>ORDER BY total_trade_value DESC;</p><p>This query groups the records by partner, calculates the total trade value for each partner, and orders the results from the largest to the smallest.</p><p>The main concepts I practiced included:</p><p>- “SELECT” for choosing columns.<br>- “WHERE” for filtering records.<br>- “GROUP BY” for creating groups.<br>- “SUM()” and “COUNT()” for calculations.<br>- “ORDER BY” for sorting results.<br>- CTEs for organizing complex queries.<br>- Window functions for ranking and calculating shares.</p><p>Example: If I need to identify the largest trade partners, I can use “GROUP BY” to calculate each partner’s total and “ORDER BY” to arrange the results in descending order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*v8fqaHqf855j5IowLj8oRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*b7xtNFWVvllJx_3_WVQhjQ.png" /></figure><p>Conditional Aggregation</p><p>Conditional aggregation allows me to calculate values for different categories within the same query.</p><p>For example, I can calculate monthly imports and exports in separate columns using “SUM()” with “CASE”.</p><p>SELECT<br> Period,<br> SUM(<br> CASE<br> WHEN [Trade Flow] = ‘Imports’<br> THEN [Trade Value (US$)]<br> ELSE 0<br> END<br> ) AS imports_value,<br> SUM(<br> CASE<br> WHEN [Trade Flow] = ‘Exports’<br> THEN [Trade Value (US$)]<br> ELSE 0<br> END<br> ) AS exports_value<br>FROM week09.countrymilk<br>GROUP BY Period<br>ORDER BY Period;</p><p>The “CASE” expression checks each row. If the row represents imports, its value contributes to the imports column. If it represents exports, its value contributes to the exports column.</p><p>The “ELSE 0” ensures that records belonging to the other category contribute zero to that calculation.</p><p>Example: For a particular month, the query returns one row containing the total import value and total export value in separate columns.</p><p>This is useful when I want to compare two or more categories without generating separate queries for each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*sSSru8WdBKqlvPFMzrY3OA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*dUqneSX7HNfLwzvOa5uXRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*9FzkpTvwDMGd0RpL02Ih5Q.png" /></figure><p>Grouping Sets and Quarterly Reporting</p><p>I also worked with quarterly and annual summaries.</p><p>A quarter contains three months:</p><p>- Q1: January to March<br>- Q2: April to June<br>- Q3: July to September<br>- Q4: October to December</p><p>In the SQL practice, I used the “Period” value to derive the quarter. For a period represented as a year and month, the month can be extracted using the remainder operation.</p><p>For example:</p><p>(Period % 100 + 2) / 3</p><p>This expression calculates the quarter number from the month component of the period.</p><p>I also used “GROUPING SETS” to calculate quarterly totals and annual totals in one query.</p><p>GROUP BY GROUPING SETS (<br> (trade_flow, quarter_num),<br> (trade_flow)<br>)</p><p>The first grouping produces a result for each trade flow and quarter. The second produces a yearly total for each trade flow.</p><p>Example: Instead of running one query for quarterly totals and another for yearly totals, I can use grouping sets to generate both levels of summary in one result.</p><p>This makes the query more efficient to organize and reduces repetition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*LWiXJpdm0ddk54dm1Umvow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*DLklyE1xTW46ktbth_5rMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*TLQ6ZoqQ6RYQAvGdD1aq9Q.png" /></figure><p>Window Functions and Ranking</p><p>Window functions are useful when I need to calculate values across a group of rows while keeping the individual rows in the result.</p><p>One example is ranking trade partners within each trade flow.</p><p>ROW_NUMBER() OVER (<br> PARTITION BY trade_flow<br> ORDER BY total_value DESC<br>) AS partner_rank</p><p>This expression assigns a rank to each partner based on its total trade value.</p><p>The “PARTITION BY” clause separates the ranking into groups. In this example, imports and exports are ranked independently.</p><p>The “ORDER BY” clause determines the ranking order. Since the total value is sorted in descending order, the partner with the largest value receives rank 1.</p><p>Example: The top three import partners receive ranks 1, 2, and 3 within Imports. The export partners are ranked separately within Exports.</p><p>I also used a window function to calculate the total value for each trade flow:</p><p>SUM(total_value) OVER (<br> PARTITION BY trade_flow<br>) AS flow_total</p><p>This allows me to calculate each partner’s contribution to the overall trade flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*x0nZuNdnok2B053FOrMbUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*ren0js1JagTJUTz1N2G_8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*DCKUaExceQikX3NadvFsow.png" /></figure><p>Grouping Top Partners and Calculating Shares</p><p>Another useful technique was grouping smaller categories into a single category called “Other.”</p><p>This is helpful when a report needs to focus on the most important partners without displaying every partner separately.</p><p>The approach involved:</p><p>1. Calculating the total export value for each partner.<br>2. Identifying the top five partners.<br>3. Keeping those five partners as individual categories.<br>4. Grouping all remaining partners under “Other.”<br>5. Calculating the monthly total for each group.<br>6. Calculating each group’s percentage share of the monthly export value.</p><p>For example, if a particular month has a total export value of $10 million and one partner accounts for $2 million, its share is:</p><p>[<br>\text{Share} = \frac{2,000,000}{10,000,000}\times100 = 20%<br>]</p><p>The percentage share helps explain how much each partner contributes to the total.</p><p>Example: The top five partners can be displayed individually, while the remaining partners are combined into “Other.” This creates a more readable report while still accounting for the full export value.</p><p>Image placement: Add a screenshot of the monthly export summary showing the top five partners and the “Other” category, including percentage shares.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*5-bjHtWOT36lj756OZa-uA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*C0ARSbKf88aUTrFhC9qNYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*ZfjuTHxytlTNFnBwAd7w_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*okkWOpcLvzD9OIIyLz7Zmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*OScDbV4UkiDTAbP0qLJ-jg.png" /></figure><p>What I Solved: Week 8 Tasks</p><p>The practical assignment involved analyzing UK milk trade data and completing SQL practice tasks. The work helped me apply the concepts from the learning materials to actual datasets.</p><p><strong>Part A: UK Milk Trade Analysis</strong></p><p>The first part involved working with UK milk import and export data.</p><p>The dataset contained information such as:</p><p>- Trade flow<br>- Partner country<br>- Commodity code<br>- Period<br>- Trade value in US dollars</p><p>The commodity codes were used to distinguish between two types of milk products:</p><p>- “0401”: Unprocessed milk<br>- “0402”: Processed milk</p><p>The analysis required me to work with these categories and examine the trade data in a structured way.</p><p>One important step was understanding that imports and exports needed to be analyzed separately when the question focused on a specific trade flow.</p><p>For example, to identify the largest export partner, I would first select export records and then aggregate the trade values by partner.</p><p>This approach helped me avoid mixing import and export values during the analysis.</p><p>SQL Task 1: Trade Flow and Milk Type Summary</p><p>The first SQL task required a summary of the trade data by trade flow and milk type.</p><p>The query grouped the records using:</p><p>- Trade flow: Imports or Exports<br>- Milk type: Unprocessed or Processed</p><p>It also calculated the number of distinct partner countries and the total trade value in millions of US dollars.</p><p>The main logic was:</p><p>SELECT<br> [Trade Flow] AS trade_flow,<br> CASE<br> WHEN [Commodity Code] = ‘0401’ THEN ‘unprocessed’<br> WHEN [Commodity Code] = ‘0402’ THEN ‘processed’<br> END AS milk_type,<br> COUNT(DISTINCT Partner) AS partners,<br> ROUND(<br> SUM([Trade Value (US$)]) / 1000000.0,<br> 2<br> ) AS total_musd<br>FROM week09.comtrade_milk_uk_jan_jul_15<br>WHERE Partner &lt;&gt; ‘World’<br>GROUP BY<br> [Trade Flow],<br> CASE<br> WHEN [Commodity Code] = ‘0401’ THEN ‘unprocessed’<br> WHEN [Commodity Code] = ‘0402’ THEN ‘processed’<br> END<br>ORDER BY trade_flow, milk_type;</p><p>The “CASE” expression converted commodity codes into readable milk type labels.</p><p>The “COUNT(DISTINCT Partner)” counted unique partner countries, while the “SUM()” calculated the total trade value.</p><p>I also excluded the “World” aggregate row so that it would not be counted as an individual partner.</p><p>Example: The query creates separate summaries for imports of unprocessed milk, imports of processed milk, exports of unprocessed milk, and exports of processed milk.</p><p>SQL Task 2: Monthly Trade Balance</p><p>The second task focused on monthly imports, exports, and trade balance.</p><p>The trade balance was calculated as:</p><p>[<br>\text{Trade Balance} = \text{Exports} — \text{Imports}<br>]</p><p>A positive balance means exports are greater than imports. A negative balance means imports are greater than exports.</p><p>I used conditional aggregation to calculate imports and exports in separate columns, then calculated the balance.</p><p>SELECT<br> Period AS period,<br> ROUND(<br> SUM(<br> CASE<br> WHEN [Trade Flow] = ‘Imports’<br> THEN [Trade Value (US$)]<br> ELSE 0<br> END<br> ) / 1000000.0,<br> 2<br> ) AS imports_musd,<br> ROUND(<br> SUM(<br> CASE<br> WHEN [Trade Flow] = ‘Exports’<br> THEN [Trade Value (US$)]<br> ELSE 0<br> END<br> ) / 1000000.0,<br> 2<br> ) AS exports_musd,<br> ROUND((<br> SUM(<br> CASE<br> WHEN [Trade Flow] = ‘Exports’<br> THEN [Trade Value (US$)]<br> ELSE 0<br> END<br> )<br> -<br> SUM(<br> CASE<br> WHEN [Trade Flow] = ‘Imports’<br> THEN [Trade Value (US$)]<br> ELSE 0<br> END<br> )<br> ) / 1000000.0, 2) AS balance_musd<br>FROM week09.countrymilk<br>GROUP BY Period<br>ORDER BY Period;</p><p>The query grouped the data by month and returned imports, exports, and the trade balance in millions of US dollars.</p><p>Example: If exports are $8 million and imports are $10 million in a month, the trade balance is:</p><p>[<br>8–10 = -2 \text{ million US dollars}<br>]</p><p>This indicates a trade deficit of $2 million for that month.</p><p>SQL Task 3: Quarterly and Annual Summary</p><p>The third task required quarterly totals and annual totals for each trade flow.</p><p>I used a common table expression (CTE) to calculate the quarter number from the period. I then used “GROUPING SETS” to obtain both quarterly and yearly summaries.</p><p>WITH TradeQuarter AS (<br> SELECT<br> [Trade Flow] AS trade_flow,<br> (Period % 100 + 2) / 3 AS quarter_num,<br> [Trade Value (US$)] AS trade_value<br> FROM week09.countrymilk<br>)<br>SELECT<br> trade_flow,<br> CASE<br> WHEN GROUPING(quarter_num) = 1 THEN ‘Year’<br> ELSE ‘Q’ + CAST(quarter_num AS VARCHAR(1))<br> END AS quarter,<br> ROUND(<br> SUM(trade_value) / 1000000.0,<br> 2<br> ) AS total_musd<br>FROM TradeQuarter<br>GROUP BY GROUPING SETS (<br> (trade_flow, quarter_num),<br> (trade_flow)<br>)<br>ORDER BY<br> trade_flow,<br> CASE<br> WHEN GROUPING(quarter_num) = 1 THEN 5<br> ELSE quarter_num<br> END;</p><p>The CTE made the query easier to understand by separating the quarter calculation from the final summary.</p><p>The “GROUPING()” function helped identify the annual total rows. When the quarter was not part of the grouping, the query labelled the row as “Year”.</p><p>Example: The result contains Q1, Q2, Q3, and Q4 totals, followed by a yearly total for Imports and another yearly total for Exports.</p><p>SQL Task 4: Top Three Trade Partners</p><p>The fourth task involved identifying the top three trade partners for each trade flow.</p><p>I approached this by first calculating the total trade value for each partner and trade flow. I then ranked the partners using a window function.</p><p>WITH PartnerTotals AS (<br> SELECT<br> [Trade Flow] AS trade_flow,<br> Partner AS partner,<br> SUM([Trade Value (US$)]) AS total_value<br> FROM week09.countrymilk<br> GROUP BY [Trade Flow], Partner<br>),<br>RankedPartners AS (<br> SELECT<br> trade_flow,<br> partner,<br> total_value,<br> ROW_NUMBER() OVER (<br> PARTITION BY trade_flow<br> ORDER BY total_value DESC, partner ASC<br> ) AS partner_rank,<br> SUM(total_value) OVER (<br> PARTITION BY trade_flow<br> ) AS flow_total<br> FROM PartnerTotals<br>)<br>SELECT<br> trade_flow,<br> partner_rank AS [rank],<br> partner,<br> ROUND(<br> total_value / 1000000.0,<br> 2<br> ) AS total_musd,<br> ROUND(<br> total_value * 100.0 / flow_total,<br> 1<br> ) AS share_pct<br>FROM RankedPartners<br>WHERE partner_rank &lt;= 3<br>ORDER BY trade_flow, partner_rank;</p><p>The first CTE calculated the total trade value for each partner.</p><p>The second CTE ranked the partners within each trade flow and calculated the total value for that flow.</p><p>The final query selected only the first three partners from each ranking.</p><p>Example: The query returns the three largest import partners and the three largest export partners, with each partner’s total value and percentage share.</p><p>SQL Task 5: Top Five Export Partners and “Other”</p><p>The fifth task required a monthly export summary that displayed the top five export partners separately and grouped the remaining partners into “Other.”</p><p>The top five partners were identified based on their total export value across the dataset, rather than separately for each month.</p><p>The query then grouped each monthly export record into either one of the top five partners or the “Other” category.</p><p>WITH ExportRows AS (<br> SELECT<br> Period AS period,<br> Partner AS partner,<br> [Trade Value (US$)] AS trade_value<br> FROM week09.comtrade_milk_uk_jan_jul_15<br> WHERE [Trade Flow] = ‘Exports’<br> AND Partner &lt;&gt; ‘World’<br>),<br>Top5 AS (<br> SELECT TOP 5 partner<br> FROM ExportRows<br> GROUP BY partner<br> ORDER BY SUM(trade_value) DESC, partner ASC<br>),<br>MonthlyGroups AS (<br> SELECT<br> e.period,<br> CASE<br> WHEN t.partner IS NOT NULL THEN e.partner<br> ELSE ‘Other’<br> END AS partner_group,<br> SUM(e.trade_value) AS group_value<br> FROM ExportRows AS e<br> LEFT JOIN Top5 AS t<br> ON e.partner = t.partner<br> GROUP BY<br> e.period,<br> CASE<br> WHEN t.partner IS NOT NULL THEN e.partner<br> ELSE ‘Other’<br> END<br>)<br>SELECT<br> period,<br> partner_group,<br> ROUND(<br> group_value / 1000000.0,<br> 2<br> ) AS exports_musd,<br> ROUND(<br> group_value * 100.0 /<br> SUM(group_value) OVER (PARTITION BY period),<br> 1<br> ) AS share_pct<br>FROM MonthlyGroups<br>ORDER BY<br> period,<br> CASE<br> WHEN partner_group = ‘Other’ THEN 1<br> ELSE 0<br> END,<br> partner_group;</p><p>This task brought together several SQL concepts:<br>CTEs<br>Filtering<br>Aggregation<br>TOP<br>LEFT JOIN<br>CASE<br>Window functions<br>Percentage calculations<br>The LEFT JOIN helped retain all export records. If a partner was among the top five, it remained as an individual partner. Otherwise, it was grouped under Other.<br>The percentage share was calculated within each month.<br>Example: If the top five partners account for some of the monthly export value, the remaining export value is represented by Other. The percentage shares show how much each group contributes to that month’s total exports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*kVeegrLCa1kmjbwmoqY8GQ.png" /><figcaption>All the images of the tasks can be view at the section previous to the tasks.</figcaption></figure><p><strong>Challenges I Faced</strong><br>One of the challenges I faced was understanding how to analyze a dataset containing different categories of information.<br>When imports and exports are stored in the same dataset, it is important to know when to analyze them together and when to separate them. I had to pay attention to the trade flow column to ensure that the calculations answered the intended question.<br>Another challenge was understanding how to create summary reports using SQL. At first, it was not always obvious how to move from individual records to a grouped result.<br>The use of CASE inside aggregate functions was another concept that required careful attention. I needed to understand how conditional aggregation could calculate imports and exports in separate columns.<br>I also found the more advanced SQL tasks challenging because they involved several concepts in one query. For example, the top-three partner task required aggregation, ranking, partitioning, and filtering. The top-five export task required identifying the largest partners, joining them back to the dataset, grouping the remaining partners, and calculating percentage shares.<br>Finally, I had to be careful with the different datasets and table names used across the tasks. Using the correct source table was important because the tasks did not all refer to the same dataset.</p><p><strong>How I Overcame the Challenges</strong></p><p>I approached the assignment by breaking each task into smaller steps. Instead of trying to understand a long SQL query all at once, I focused on the purpose of each part.<br>For example, when working on the top-three partner task, I separated the logic into:<br>Calculate the total value for each partner.<br>Rank partners within each trade flow.<br>Calculate the total value for each trade flow.<br>Select the top three partners.<br>Calculate their percentage shares.<br>This made the query easier to understand and helped me see how the different parts worked together.<br>I also paid closer attention to the role of GROUP BY, CASE, and window functions.<br>For conditional aggregation, I learned to think of CASE as a way to decide which rows contribute to a particular calculation.<br>For ranking, I learned that PARTITION BY separates the groups, while ORDER BY determines the ranking order.<br>For the top-five export task, I learned that the top five partners needed to be identified first before grouping the remaining partners into Other.<br>I also used the expected structure of the output to check whether my approach made sense. For instance, the top-three task should return three partners for Imports and three for Exports, while the top-five export task should produce monthly groups for the five selected partners and Other where applicable.<br>Breaking the tasks down helped me understand the logic rather than simply copying SQL code.</p><p><strong>What I Would Do Differently</strong><br>If I were to repeat this assignment, I would spend more time planning the analysis before writing the complete query.<br>I would first identify:<br>The question the task is asking.<br>The table containing the required data.<br>The columns needed.<br>The grouping categories.<br>The calculations required.<br>The expected output structure.<br>I would also test complex queries in smaller sections. For example, I would first check whether the partner totals are correct before adding the ranking function. For the top-five export task, I would first identify the top five partners, then proceed to the monthly grouping and percentage calculations.<br>This approach would make it easier to identify mistakes and understand why a query works.<br>I would also continue practicing SQL with real datasets because practical exercises help me understand how individual concepts fit together.</p><p><strong>Key Takeaways and Advice for Other Learners</strong></p><p>Week 8 helped me understand that data analysis is not only about writing code. It is also about asking the right questions and choosing the right method to answer them.<br>The Split-Apply-Combine pattern provided a useful way to think about grouping and summary reporting.<br>The UK milk trade analysis showed how data can be organized into meaningful categories such as trade flow, milk type, partner country, and period.<br>The SQL tasks helped me strengthen my understanding of aggregation, conditional calculations, CTEs, grouping sets, ranking, and window functions.<br>My main advice to other learners is to avoid rushing through complex queries. Start with the question, identify the relevant columns, and build the query step by step.<br>For example, if a task asks for the top three partners, first calculate the total value for each partner. Once that result is clear, add the ranking function and filter the top three.<br>It is also important to understand the difference between a grouped calculation and a window calculation. GROUP BY produces a summary for each group, while a window function can calculate values across a group while keeping the individual rows in the result.<br>Finally, I encourage learners to use real datasets and practice explaining their code. Being able to explain what a query does is an important part of becoming confident in data analysis.</p><p><strong>Conclusion</strong><br>Week 8 was an important learning experience in my DataraFlow internship. It helped me strengthen my understanding of data grouping, summary reporting, and SQL-based analysis.<br>Through the Split-Apply-Combine pattern, I learned how to organize data into groups and apply calculations to produce meaningful summaries.<br>The UK milk trade analysis gave me an opportunity to work with import and export data, while the SQL practice tasks helped me apply concepts such as conditional aggregation, grouping sets, CTEs, ranking, and percentage shares.<br>The experience also taught me the importance of breaking complex tasks into smaller steps and checking whether the results match the purpose of the analysis.<br>As I continue my journey in data science and analytics, I look forward to applying these techniques to more datasets and developing a stronger understanding of how data can be transformed into useful insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c03da9f30667" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Dirty CSVs to Clean Insights: My Data Cleaning Playbook in Python and SQL]]></title>
            <link>https://blog.gopenai.com/from-dirty-csvs-to-clean-insights-my-data-cleaning-playbook-in-python-and-sql-c2267a5912ed?source=rss-ab038533369f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2267a5912ed</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Abdulkabirdauda]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 21:35:51 GMT</pubDate>
            <atom:updated>2026-10-27T10:27:03.454Z</atom:updated>
            <content:encoded><![CDATA[<p>How I turned 4 messy London bike datasets into one powerful analysis using Python, SQL, and Pandas</p><p><strong>Table of Contents</strong></p><p>Introduction</p><p>What I Learnt This Week</p><p>Accessing Data with SQL and Python</p><p>Data Cleaning with Pandas</p><p>Working with Dates and Datetime Indexing</p><p>Filtering and Selecting Data</p><p>Handling Missing Values</p><p>Data Visualisation</p><p>Transforming and Combining Data</p><p>Correlation Analysis with Spearman’s Rank Correlation</p><p>World Bank Indicators and Data Analysis</p><p>What I Solved: Week 7 Tasks and Projects</p><p>Part A: Cleaning and Visualising Data</p><p>Project A: Holiday Weather</p><p>Part B: Transforming and Combining Data</p><p>Project B: GDP and Life Expectancy</p><p>Independent World Bank Indicators Project</p><p>SQL Practice Tasks</p><p>Challenges I Faced</p><p>How I Overcame the Challenges</p><p>Key Lessons and Insights</p><p>Advice for Other Learners</p><p>Conclusion</p><p><strong>Introduction</strong></p><p>Everyone talks about machine learning. No one talks about the 80% of time we spend just cleaning the data. This week, I learned why that 80% matters. Week 7 of the DataraFlow internship focused on two important areas of data analysis: Cleaning and Visualising Data and Transforming and Combining Data. These topics helped me understand how to work with raw datasets, prepare them for analysis, identify useful patterns, combine information from different sources, and communicate findings through visualisations.</p><p>Throughout the week, I worked with Python, Pandas, SQL, and data visualisation techniques. I also explored weather data from London and World Bank indicators relating to gross domestic product (GDP), life expectancy, and population.</p><p>The activities involved more than writing code. They required me to understand the structure of datasets, identify data quality issues, select appropriate methods for cleaning and transformation, and interpret the results of my analysis.</p><p>In this article, I share the key concepts I learnt, the tasks and projects I completed, the challenges I encountered, and the approaches that helped me overcome them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-igVvlmfV483jDZpSCh5g.png" /></figure><p><strong>What I Learnt This Week</strong></p><p>Accessing Data with SQL and Python</p><p>One of the key lessons from this week was how to access data stored in a database and bring it into Python for analysis.</p><p>SQL allows us to retrieve specific information from database tables, while Python provides tools for further cleaning, transformation, analysis, and visualisation.</p><p>In the DataraFlow environment, I used the run_query function from the database helper module to retrieve datasets. For example, the following code loads the London weather dataset from the database:</p><p>from db.dataraflow_db import run_query</p><p>london = run_query(</p><p>“SELECT * FROM week07.london_2014”</p><p>)</p><p>london.head()</p><p>The SELECT * statement retrieves all columns and rows from the specified table, while head() displays the first five rows by default.</p><p>I also worked with the World Bank datasets stored under the week08 schema, including tables containing GDP, life expectancy, and population data for 2013.</p><p>For example:</p><p>gdpReset = run_query(</p><p>“SELECT * FROM week08.wb_gdp_2013”</p><p>)</p><p>gdpReset.head()</p><p>This helped me understand the relationship between SQL-based data retrieval and Python-based data analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R5YWA-aQ67761LuZhVaKWA.png" /></figure><p>Data Cleaning with Pandas</p><p>Raw data does not always arrive in a format suitable for analysis. Column names may contain unwanted characters, values may be stored as text rather than numbers, and missing values may affect calculations. I learnt how Pandas can help identify and correct these issues.</p><p>For example, the London weather dataset contained a wind direction column with the unusual name WindDirDegrees&lt;br /&gt;, and some values contained the literal text &lt;br /&gt;. I cleaned the column name and converted the wind direction values to integers using:</p><p>london.columns = london.columns.str.strip()</p><p>london = london.rename(</p><p>columns={</p><p>“WindDirDegrees&lt;br /&gt;”: “WindDirDegrees”</p><p>}</p><p>)</p><p>london[“WindDirDegrees”] = (</p><p>london[“WindDirDegrees”]</p><p>.astype(str)</p><p>.str.replace(“&lt;br /&gt;”, “”, regex=False)</p><p>.astype(“int64”)</p><p>)</p><p>The code performs three operations:</p><p>Removes unnecessary spaces around column names.</p><p>Renames the wind direction column to a cleaner name.</p><p>Removes the unwanted text from its values and converts the cleaned values into integers.</p><p>This is important because numerical analysis and comparisons require values to have the appropriate data type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4CHkfDnTAc93_MSWETzDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqywNnl3QP4G87Lyb5wl3Q.png" /></figure><p><strong>Working with Dates and Datetime Indexing</strong></p><p>Another important topic was working with dates in datasets. Dates are essential in time-based analysis because they allow us to examine trends, select specific periods, compare seasons, and identify changes over time. I used Pandas to convert the GMT column into a datetime format:</p><p>import pandas as pd</p><p>london[“GMT”] = pd.to_datetime(</p><p>london[“GMT”]</p><p>)</p><p>Converting the column to datetime makes it easier to filter records by date and perform time-based operations.</p><p>For example, to select weather records from 1 April to 11 April 2014:</p><p>from datetime import datetime</p><p>start = datetime(2014, 4, 1)</p><p>end = datetime(2014, 4, 11)</p><p>april_weather = london[</p><p>(london[“GMT”] &gt;= start)</p><p>&amp; (london[“GMT”] &lt;= end)</p><p>]</p><p>I also learnt how to set a date column as the DataFrame index:</p><p>london.index = london[“GMT”]</p><p>london = london.sort_index()</p><p>Once the datetime index is established, selecting a date range becomes more convenient.</p><p>For example:</p><p>december_weather = london.loc[</p><p>datetime(2014, 12, 8):</p><p>datetime(2014, 12, 12)</p><p>]</p><p>This selects records within the specified date range when the index is correctly configured.</p><p><strong>Filtering and Selecting Data</strong></p><p>Data filtering allows us to focus on records that meet specific conditions instead of analysing an entire dataset at once.</p><p>I used conditional expressions to select weather observations based on wind direction, dates, and other variables.</p><p>For example, to identify days when the wind direction was greater than 350 degrees:</p><p>strong_northward_direction = london[</p><p>london[“WindDirDegrees”] &gt; 350</p><p>]</p><p>To identify wind directions within the range of 350 degrees and 10 degrees, including values on either side of zero:</p><p>northerly_winds = london[</p><p>(london[“WindDirDegrees”] &gt;= 350)</p><p>| (london[“WindDirDegrees”] &lt;= 10)</p><p>]</p><p>The | operator represents OR, while &amp; represents AND in Pandas conditions. Each condition should be enclosed in parentheses when combining them.</p><p>I also learnt to select particular columns when only a subset of a dataset is required.</p><p>For example:</p><p>temperature_data = london[</p><p>[</p><p>“GMT”,</p><p>“Min TemperatureC”,</p><p>“Mean TemperatureC”,</p><p>“Max TemperatureC”</p><p>]</p><p>]</p><p>This produces a smaller DataFrame containing the date and three temperature measurements.</p><p><strong>Handling Missing Values</strong></p><p>Missing values are another common data quality issue. If they are not handled appropriately, they may reduce the number of usable observations or affect calculations and comparisons.</p><p>I learnt to identify missing values using Pandas methods such as isnull() and to fill missing values where an appropriate treatment is justified.</p><p>For example, to identify weather records with missing maximum gust speed:</p><p>missing_gust_speed = london[</p><p>london[“Max Gust SpeedKm/h”].isnull()</p><p>]</p><p>To replace missing values in the Events column with empty strings:</p><p>london[“Events”] = london[“Events”].fillna(“”)</p><p>These examples illustrate two different approaches. The first identifies incomplete records, while the second replaces missing entries in a particular text column.</p><p>I also worked with World Bank data, where some countries had missing values for GDP or life expectancy. Before comparing the indicators, I removed records without the required values.</p><p>For example:</p><p>gdpCountries = gdpReset[34:].dropna()</p><p>This takes the rows after the first 34 entries and removes rows containing missing values in the remaining columns. The same approach was used for the life expectancy dataset.</p><p>However, missing values should be handled according to the purpose of the analysis. Replacing missing information with an empty string may be suitable for a text column, but it would not be an appropriate general solution for numerical data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2gktc57z8urWhhb6AcHBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxBiNz9O963jgQvRt4_rwQ.png" /></figure><p>Data Visualisation</p><p>Data visualisation makes it easier to understand patterns and communicate findings from a dataset. I worked with plots to explore weather conditions and relationships between economic and social indicators.</p><p>For example, I plotted minimum, mean, and maximum temperatures from the London weather dataset:</p><p>london[</p><p>[</p><p>“Min TemperatureC”,</p><p>“Mean TemperatureC”,</p><p>“Max TemperatureC”</p><p>]</p><p>].plot(</p><p>grid=True,</p><p>figsize=(10, 5)</p><p>)</p><p>This allows the three temperature series to be viewed together, making their changes over time easier to compare.</p><p>I also explored plotting mean humidity during spring, defined here as March through May:</p><p>from datetime import datetime</p><p>spring_start = datetime(2014, 3, 1)</p><p>spring_end = datetime(2014, 5, 31)</p><p>spring = london.loc[</p><p>spring_start:spring_end</p><p>]</p><p>spring[“Mean Humidity”].plot(</p><p>grid=True,</p><p>figsize=(10, 5)</p><p>)</p><p>For relationships between GDP and life expectancy, I used a scatter plot. The horizontal axis represents GDP, while the vertical axis represents life expectancy. A logarithmic horizontal axis helps display countries whose GDP values differ substantially in scale.</p><p>Practical example: A line plot can show how temperature changes from one day to another, while a scatter plot can help investigate whether countries with higher GDP also tend to have higher life expectancy.</p><p>Visualisations are most useful when the variables, units, and axes are clearly labelled and the chart type suits the question being investigated.</p><p><strong>Transforming and Combining Data</strong></p><p>Data transformation involves changing data into a more useful form for analysis. Combining data involves bringing together information from different tables or datasets. I worked with World Bank indicators that were stored in separate tables. To investigate relationships between GDP and life expectancy, I first prepared each dataset and then combined them using the country column.</p><p>For example:</p><p>gdpVsLife = pd.merge(</p><p>gdpClean,</p><p>lifeClean,</p><p>on=”country”,</p><p>how=”inner”</p><p>)</p><p>An inner join retains records with matching country values in both datasets.</p><p>I also learnt that the type of join affects which records are retained:</p><p>An inner join keeps matching records from both datasets.</p><p>A left join keeps all records from the left dataset and includes matching records from the right dataset where available.</p><p>For example, when examining GDP records and life expectancy data, a left join can help identify GDP records that have no corresponding life expectancy value.</p><p>gdpWithLife = pd.merge(</p><p>gdpClean,</p><p>lifeClean,</p><p>on=”country”,</p><p>how=”left”</p><p>)</p><p>Another transformation involved converting GDP from US dollars into millions of pounds using the exchange-rate value provided in the lesson.</p><p>def roundToMillions(value):</p><p>return round(value / 1_000_000)</p><p>def usdToGBP(usd):</p><p>return usd / 1.564768</p><p>The GDP values were then converted and rounded:</p><p>GDP = “GDP (£m)”</p><p>gdpCountries[GDP] = (</p><p>gdpCountries[“NY.GDP.MKTP.CD”]</p><p>.apply(usdToGBP)</p><p>.apply(roundToMillions)</p><p>)</p><p>This produces a more manageable GDP measure expressed in millions of pounds, using the conversion specified in the lesson.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KE2V7_IA749pfWGsjp4UNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiRNwxQn0-_AuMbcRJG5MQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Wxv_JrgsSowrkMw9cbS3g.png" /></figure><p><strong>Correlation Analysis with Spearman’s Rank Correlation</strong></p><p>Correlation analysis helps investigate whether two variables tend to change together. In the GDP and life expectancy project, I used Spearman’s rank correlation to examine the relationship between GDP and life expectancy across countries.</p><p>Spearman’s rank correlation measures the strength and direction of a monotonic relationship between two variables using their ranks. Its coefficient ranges from -1 to +1.</p><p>A value close to +1 indicates a strong positive monotonic relationship.</p><p>A value close to -1 indicates a strong negative monotonic relationship.</p><p>A value close to 0 indicates little or no monotonic association.</p><p>The coefficient should be interpreted in context. Correlation alone does not establish that one variable causes a change in another.</p><p>For example, the lesson’s GDP and life expectancy analysis produced a Spearman correlation of approximately 0.501, with a statistically significant p-value below 0.05. This indicates a positive association in the analysed data: countries with higher GDP values tended, in general, to have higher life expectancy values. It does not mean that GDP alone determines life expectancy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gW9K4C0AP46HJP9y8DRiVg.png" /></figure><p><strong>World Bank Indicators and Data Analysis</strong></p><p>The World Bank datasets provided an opportunity to work with country-level economic and social indicators.</p><p>The three indicators used in the main project were:</p><p>Indicator</p><p>World Bank code</p><p>Meaning</p><p>GDP</p><p>NY.GDP.MKTP.CD</p><p>Gross domestic product in current US dollars</p><p>Life expectancy</p><p>SP.DYN.LE00.IN</p><p>Life expectancy at birth, in years</p><p>Population</p><p>SP.POP.TOTL</p><p>Total population</p><p>The data used for the main GDP and life expectancy analysis related to 2013.</p><p>I learnt that datasets from the same source can still require cleaning before they can be combined. In this exercise, the first 34 rows represented regional aggregates that were excluded from the country-level analysis, and missing indicator values were removed from the relevant datasets.</p><p>For example:</p><p>gdpCountries = gdpReset[34:].dropna()</p><p>lifeCountries = lifeReset[34:].dropna()</p><p>I also learnt how to select only the columns needed for the final analysis:</p><p>gdpClean = gdpCountries[</p><p>[“country”, “GDP (£m)”]</p><p>]</p><p>lifeClean = lifeCountries[</p><p>[“country”, “Life expectancy (years)”]</p><p>]</p><p>Keeping only the necessary columns helps make the final merged dataset easier to understand.</p><p>Some Interesting Parts:</p><p>Cleaning and Visualising Data</p><p>Part A focused on the London weather dataset, week07.london_2014.</p><p>I worked through the cleaning and visualisation tasks by first loading the data, inspecting its structure, correcting the inconsistent wind direction column, converting dates into datetime values, and selecting records based on specific conditions.</p><p>The tasks included:</p><p>Cleaning the wind direction column.</p><p>Identifying wind directions above 350 degrees and northerly directions around zero degrees.</p><p>Selecting weather observations within a specified date range.</p><p>Identifying records with missing maximum gust speed.</p><p>Plotting minimum, mean, and maximum temperatures.</p><p>Setting the date column as the DataFrame index.</p><p>Selecting a date range through datetime indexing.</p><p>Plotting mean humidity during the spring months.</p><p>Saving the cleaned weather data as a CSV file.</p><p>After cleaning, I saved the data using:</p><p>london.to_csv(</p><p>“london_2014_clean.csv”,</p><p>index=False</p><p>)</p><p>Saving the cleaned dataset as a CSV file makes it possible to reuse the prepared data without repeating every cleaning operation, provided the saved file is available in the relevant working directory.</p><p>Project A: Holiday Weather</p><p>Project A involved examining historical weather data for London Heathrow Airport (LHR) during 2023 to identify suitable summer holiday weeks.</p><p>The project focused on the summer months of June, July, and August. The main idea was to compare weather conditions across different periods and identify weeks that offered favourable conditions based on the available weather measurements. I loaded the data directly from worldbank database month by month and i combined in in escel worksheet and saved it to csv then it was uploaded to vscode.</p><p>The workflow involved:</p><p>Collecting the monthly historical weather data from Weather Underground for London Heathrow Airport.</p><p>Combining the monthly data into a CSV file.</p><p>Loading the CSV file into Pandas.</p><p>Cleaning the data and preparing the date column for analysis.</p><p>Selecting observations from June, July, and August.</p><p>Comparing precipitation and temperature patterns across summer weeks.</p><p>Identifying two potentially suitable seven-day holiday periods based on the weather data.</p><p>The CSV-loading step can be illustrated with:</p><p>import pandas as pd</p><p>london_heathrow_2023 = pd.read_csv(</p><p>“london_heathrow_2023.csv”,</p><p>skipinitialspace=True</p><p>)</p><p>london_heathrow_2023.head()</p><p>The skipinitialspace=True argument helps remove leading spaces after delimiters when reading the CSV file.</p><p>After converting the date column to datetime, the summer observations can be selected using:</p><p>london_heathrow_2023[“Date”] = pd.to_datetime(</p><p>london_heathrow_2023[“Date”]</p><p>)</p><p>summer = london_heathrow_2023[</p><p>london_heathrow_2023[“Date”].dt.month.isin([6, 7, 8])</p><p>].copy()</p><p>A seven-day comparison can then be performed using a rolling window, provided the records have been sorted by date and the dataset contains the expected daily observations.</p><p>For example, if the precipitation column is named Precipitation:</p><p>summer = summer.sort_values(“Date”)</p><p>summer[“Rainfall_7d”] = (</p><p>summer[“Precipitation”]</p><p>.rolling(window=7, min_periods=7)</p><p>.sum()</p><p>)</p><p>This calculates the total precipitation across each seven-row window. The actual column names must match those in the collected CSV file.</p><p>The results can help compare candidate holiday periods. However, a low rainfall total alone does not guarantee ideal holiday weather, so temperature and other available weather measurements should also be considered.</p><p>Part B: Transforming and Combining Data</p><p>Part B focused on transforming datasets and combining related information to answer analytical questions.</p><p>The main datasets were the World Bank GDP, life expectancy, and population tables for 2013:</p><p>week08.wb_gdp_2013</p><p>week08.wb_le_2013</p><p>week08.wb_pop_2013</p><p>The tables contained a country identifier and a year, alongside their respective indicators.</p><p>I worked through the exercises by retrieving the tables, preparing the country-level records, handling missing indicator values, transforming GDP values, rounding life expectancy, and merging datasets using the country column.</p><p>The main transformation and combination tasks included:</p><p>Executing the notebook exercises on data transformation and combination.</p><p>Selecting the relevant columns from each dataset.</p><p>Converting GDP values into millions of pounds using the exchange rate provided in the lesson.</p><p>Rounding life expectancy to whole years for the main cleaned dataset.</p><p>Combining GDP and life expectancy using an inner join.</p><p>Working with population data as an additional indicator.</p><p>Exploring how joins affect the records retained in a combined dataset.</p><p>The following example illustrates how to select the country and life expectancy columns after cleaning:</p><p>LIFE = “Life expectancy (years)”</p><p>lifeCountries[LIFE] = (</p><p>lifeCountries[“SP.DYN.LE00.IN”]</p><p>.apply(round)</p><p>)</p><p>lifeClean = lifeCountries[</p><p>[“country”, LIFE]</p><p>]</p><p>This creates a simplified dataset containing the country and rounded life expectancy.</p><p>Project B: GDP and Life Expectancy</p><p>Project B investigated the relationship between GDP and life expectancy across countries using the 2013 World Bank datasets.</p><p>The first step was to retrieve the GDP and life expectancy tables. Next, I excluded the first 34 rows representing regional aggregates in the supplied exercise and removed missing values from the relevant datasets.</p><p>I then transformed the GDP values into millions of pounds using the conversion specified in the lesson and rounded life expectancy to whole years for the cleaned dataset.</p><p>After cleaning both datasets, I combined them using an inner join:</p><p>gdpVsLife = pd.merge(</p><p>gdpClean,</p><p>lifeClean,</p><p>on=”country”,</p><p>how=”inner”</p><p>)</p><p>This produced a dataset containing countries with matching records in both tables.</p><p>I then used Spearman’s rank correlation to investigate the association between GDP and life expectancy. The lesson’s sample analysis reported a correlation coefficient of approximately 0.501, with a p-value below 0.05.</p><p>The positive coefficient suggests that higher GDP was associated with higher life expectancy in the analysed country-level data. Nevertheless, the relationship should not be interpreted as proof that higher GDP directly causes longer life expectancy.</p><p>I also explored scatter plotting and the importance of a logarithmic GDP axis when displaying values that vary considerably in magnitude.</p><p>Another part of the analysis involved identifying countries at the lower end of the GDP and life expectancy distributions. Sorting the data made it easier to inspect the ten lowest GDP values and the ten lowest life expectancy values.</p><p>For example:</p><p>lowest_gdp = gdpVsLife.sort_values(</p><p>“GDP (£m)”,</p><p>ascending=True</p><p>).head(10)</p><p>This returns the ten countries with the lowest GDP values in the merged dataset. A similar approach can be used to rank life expectancy in ascending order.</p><p>[IMAGE 18: Insert the final merged GDP and life expectancy DataFrame. Caption: “Combining GDP and life expectancy into a country-level dataset.”]</p><p>Independent World Bank Indicators Project</p><p>The final project extended the analysis beyond GDP and life expectancy by examining two additional World Bank indicators.</p><p>For this project, I considered agricultural employment and cereal yield:</p><p>Indicator</p><p>World Bank code</p><p>Description</p><p>Employment in agriculture</p><p>SL.AGR.EMPL.ZS</p><p>Employment in agriculture as a percentage of total employment</p><p>Cereal yield</p><p>AG.YLD.CREL.KG</p><p>Cereal yield measured in kilograms per hectare</p><p>The aim was to investigate whether there was an association between the proportion of employment in agriculture and cereal yield across countries.</p><p>The analysis followed a workflow similar to the GDP and life expectancy project:</p><p>Obtain the two indicators for the same year.</p><p>Prepare the country-level datasets.</p><p>Remove missing values required for the comparison.</p><p>Merge the datasets using a common country identifier.</p><p>Calculate Spearman’s rank correlation.</p><p>Visualise the relationship using a scatter plot.</p><p>Interpret the coefficient and p-value in the context of the data.</p><p>For example, once the two cleaned datasets are available, they can be combined as follows:</p><p>agricultureVsYield = pd.merge(</p><p>agricultureEmployment,</p><p>cerealYield,</p><p>on=”country”,</p><p>how=”inner”</p><p>)</p><p>The actual DataFrame and column names should match those used in the completed notebook.</p><p>This project helped me apply the same data preparation and correlation techniques to a question more closely related to agriculture.</p><p>It is important not to assume in advance that a higher percentage of agricultural employment necessarily corresponds to higher cereal yield. The relationship must be established from the analysed data, and correlation alone cannot identify the underlying causes.</p><p><strong>What I Solved: Week 7 Tasks and Projects</strong></p><p>SQL Practice Tasks</p><p>The SQL exercises helped me practise retrieving, filtering, transforming, joining, and summarising data directly in the database. I approached each task by identifying the required output, the relevant tables and columns, the conditions that needed to be applied, and the appropriate SQL operation.</p><p>Cleaning wind direction values and counting observations</p><p>The first task involved cleaning the wind direction values in week07.london_2014 and counting the days when the direction was greater than 350 degrees.</p><p>The key technique was using REPLACE() to remove the unwanted text and TRY_CAST() to convert the result into an integer.</p><p>SELECT COUNT(*) AS days_over_350</p><p>FROM week07.london_2014</p><p>WHERE TRY_CAST(</p><p>REPLACE(</p><p>[WindDirDegrees&lt;br /&gt;],</p><p>‘&lt;br /&gt;’,</p><p>‘’</p><p>) AS int</p><p>) &gt; 350;</p><p>This query demonstrates how data cleaning can be performed within SQL before counting the records that meet a condition.</p><p>Selecting weather observations by date</p><p>The second task involved retrieving weather observations from 8 December to 12 December 2014, including the date and maximum and minimum temperatures.</p><p>SELECT</p><p>TRY_CONVERT(date, GMT) AS day,</p><p>[Max TemperatureC],</p><p>[Min TemperatureC]</p><p>FROM week07.london_2014</p><p>WHERE TRY_CONVERT(date, GMT)</p><p>BETWEEN ‘2014–12–08’ AND ‘2014–12–12’</p><p>ORDER BY day;</p><p>The query converts the date text into a date value, filters the required period, and sorts the output chronologically.</p><p>Comparing GDP and life expectancy</p><p>The third task combined GDP and life expectancy data using the country identifier. It selected countries with GDP below US$10 billion and ranked them by life expectancy.</p><p>SELECT TOP 10</p><p>g.country,</p><p>ROUND(</p><p>g.[NY.GDP.MKTP.CD] / 1000000000.0,</p><p>2</p><p>) AS gdp_bn_usd,</p><p>ROUND(</p><p>l.[SP.DYN.LE00.IN],</p><p>1</p><p>) AS life_expectancy</p><p>FROM week08.wb_gdp_2013 AS g</p><p>INNER JOIN week08.wb_le_2013 AS l</p><p>ON g.country = l.country</p><p>WHERE g.[NY.GDP.MKTP.CD] &lt; 10000000000</p><p>AND l.[SP.DYN.LE00.IN] IS NOT NULL</p><p>ORDER BY</p><p>l.[SP.DYN.LE00.IN] DESC,</p><p>g.country ASC;</p><p>This exercise combined filtering, joining, rounding, sorting, and limiting the results to the ten highest-ranked records.</p><p>Identifying missing information after a join</p><p>The fourth task involved counting GDP records for which GDP was missing or life expectancy was unavailable after matching the datasets.</p><p>SELECT COUNT(*) AS rows_lost</p><p>FROM week08.wb_gdp_2013 AS g</p><p>LEFT JOIN week08.wb_le_2013 AS l</p><p>ON g.country = l.country</p><p>WHERE g.[NY.GDP.MKTP.CD] IS NULL</p><p>OR l.[SP.DYN.LE00.IN] IS NULL;</p><p>The left join preserves the GDP table’s records, allowing missing values in either dataset to be identified.</p><p>Task 5: Finding the driest seven-day period</p><p>The fifth task focused on identifying the seven-day period with the lowest total precipitation during the London summer of June to August 2014.</p><p>The main technique was a SQL window function that calculated precipitation totals over seven consecutive rows.</p><p>WITH summer_weather AS (</p><p>SELECT</p><p>TRY_CONVERT(date, GMT) AS day,</p><p>TRY_CAST(</p><p>[Precipitationmm] AS float</p><p>) AS rain_mm</p><p>FROM week07.london_2014</p><p>WHERE TRY_CONVERT(date, GMT)</p><p>BETWEEN ‘2014–06–01’ AND ‘2014–08–31’</p><p>),</p><p>rolling_rain AS (</p><p>SELECT</p><p>day,</p><p>SUM(rain_mm) OVER (</p><p>ORDER BY day</p><p>ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING</p><p>) AS rain_mm_7d,</p><p>COUNT(*) OVER (</p><p>ORDER BY day</p><p>ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING</p><p>) AS days_in_window,</p><p>COUNT(rain_mm) OVER (</p><p>ORDER BY day</p><p>ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING</p><p>) AS rainfall_days</p><p>FROM summer_weather</p><p>)</p><p>SELECT TOP 1</p><p>day AS start_day,</p><p>ROUND(rain_mm_7d, 2) AS rain_mm_7d</p><p>FROM rolling_rain</p><p>WHERE days_in_window = 7</p><p>AND rainfall_days = 7</p><p>ORDER BY</p><p>rain_mm_7d ASC,</p><p>start_day ASC;</p><p>The rolling calculation sums precipitation across seven consecutive rows. The counts ensure that the selected window contains seven records and that all seven precipitation values are present. The final sorting selects the lowest total, using the earliest start date to break a tie.</p><p>This task demonstrated how SQL window functions can answer time-based questions without manually calculating each seven-day total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2SL1XRMkvgg1Hhk9E8yHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*XnXMPsL9yv6SFdgFCk9pAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*RbctJ_qEy9Q11OkNgCh5Ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*6MNPDJSLVt09TvjATj3Y0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*wZZV_icd4BbjnZo7xAYe4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*L1qOpsqM74MrdsdZ31IwiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*L1qOpsqM74MrdsdZ31IwiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*Se4cLLZITbXczl4odQKhZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*at3lWJE5YwX5KrsCao1tKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*FX_F4WcSQ6kPBKl1Z7vByg.png" /></figure><p><strong>Challenges I Faced</strong></p><p>Week 7 provided several opportunities to understand the practical difficulties involved in data analysis.</p><p>Inconsistent Data Formats</p><p>One challenge was working with a weather dataset containing an unusual wind direction column name and values that included the literal text &lt;br /&gt;.</p><p>These values could not be treated as clean integers until the unwanted text was removed.</p><p>This reinforced the importance of inspecting raw data before performing calculations.</p><p>Working with Date Columns</p><p>Date columns can be difficult to filter when they are stored as text rather than as datetime values. Converting the GMT column into datetime format was necessary before using date comparisons and datetime indexing effectively.</p><p>Missing Values</p><p>Missing values required careful treatment in both the weather and World Bank datasets.</p><p>For example, a missing gust speed is not necessarily equivalent to zero gust speed. Similarly, missing GDP or life expectancy values can affect a comparison between countries.</p><p>Combining Different Datasets</p><p>The GDP, life expectancy, and population indicators were stored in separate tables. Combining them required a common identifier and an understanding of how inner and left joins differ.</p><p>I learnt that the choice of join determines which records remain in the final dataset.</p><p>Interpreting Correlation</p><p>Another important challenge was understanding what a correlation coefficient actually means.</p><p>A positive correlation indicates an association, but it does not establish causation. The result also needs to be interpreted in relation to the variables, data coverage, and period being studied.</p><p>Selecting Appropriate Visualisations</p><p>Creating a chart is only part of data analysis. The visualisation must make the relevant patterns understandable.</p><p>For example, GDP values can differ considerably across countries, making a logarithmic horizontal axis useful when plotting GDP against life expectancy.</p><p>Evaluating Seven-Day Weather Periods</p><p>The holiday weather project required more than examining individual days. Comparing seven-day periods meant considering consecutive observations, rainfall totals, and other available weather measurements.</p><p>This helped me appreciate the difference between inspecting individual records and analysing a time window.</p><p><strong>How I Overcame the Challenges</strong></p><p>I approached these challenges by breaking the work into smaller, manageable steps.</p><p>First, I inspected the datasets and their columns before attempting more complicated operations. This helped me identify inconsistent values and determine which columns needed cleaning.</p><p>Second, I used appropriate Pandas operations to convert data types, filter records, handle missing values, and select the columns needed for each task.</p><p>Third, I used SQL to retrieve and transform data directly from the database. Conditional filters, joins, aggregate functions, and window functions helped me solve specific analytical problems.</p><p>Fourth, I treated data transformation as a separate step from analysis. For example, I converted GDP values and prepared life expectancy values before merging the datasets and calculating correlation.</p><p>Fifth, I used visualisations alongside numerical results. A correlation coefficient provides a summary of an association, while a scatter plot helps show how the observations are distributed.</p><p>Finally, I considered the meaning and limitations of the results rather than relying only on the output of a calculation.</p><p>If I were to approach similar tasks again, I would begin by documenting the structure of each dataset, checking data types and missing values, and confirming that date records were correctly ordered before carrying out rolling calculations. I would also keep the cleaning steps organised so that the process would be easier to repeat.</p><p><strong>Key Lessons and Insights</strong></p><p>Week 7 strengthened my understanding of the relationship between data preparation, analysis, and interpretation.</p><p>The major lessons I took away include the following:</p><p>Data quality comes first. Cleaning inconsistent values and checking missing data are necessary steps before reliable analysis.</p><p>SQL and Python complement each other. SQL is useful for retrieving, filtering, joining, and summarising database records, while Python and Pandas support further transformation, analysis, and visualisation.</p><p>Dates provide analytical structure. Converting date columns into datetime values makes it easier to select periods, study seasonal patterns, and perform rolling calculations.</p><p>Joins influence analytical results. An inner join and a left join retain different records, so the choice must match the research question.</p><p>Visualisations improve interpretation. Line plots and scatter plots help communicate trends and relationships that may be harder to recognise from tables alone.</p><p>Correlation requires careful interpretation. A positive relationship between two variables does not prove that one causes the other.</p><p>Data analysis can support agricultural research. The techniques used with weather and World Bank indicators can also be applied to agricultural questions, provided the relevant data are available and properly prepared.</p><p>Advice for Other Learners</p><p>For anyone learning data analysis through DataraFlow or from anywhere, I would recommend the following:</p><p>Inspect the dataset before writing extensive code.</p><p>Check column names and data types early.</p><p>Understand the difference between missing values and genuine zero values.</p><p>Practise filtering records with multiple conditions.</p><p>Learn how to convert date columns and set datetime indexes.</p><p>Understand how inner and left joins affect the results.</p><p>Use SQL window functions when a problem involves consecutive periods or rolling calculations.</p><p>Select visualisations that suit the question being investigated.</p><p>Interpret statistical results carefully instead of treating them as proof of causation.</p><p>Keep your code organised and save both your notebooks and the cleaned datasets you need.</p><p>Most importantly, approach each assignment as a series of smaller problems. Understanding why a particular operation is needed is more valuable than simply copying code that produces an output.</p><p><strong>Conclusion</strong></p><p>Week 7 of the DataraFlow internship helped me develop a more practical understanding of data cleaning, visualisation, transformation, and combination.</p><p>Through the London weather exercises, I practised cleaning inconsistent values, working with dates, filtering records, handling missing values, and visualising temperature and humidity patterns. The holiday weather project extended these skills to historical weather observations and the comparison of summer holiday periods.</p><p>The SQL exercises strengthened my ability to retrieve and manipulate data, join related tables, identify missing information, and calculate rolling totals over consecutive days.</p><p>Through the GDP and life expectancy project, I learnt how to prepare World Bank indicators, transform values, combine country-level datasets, calculate Spearman’s rank correlation, and interpret the resulting relationship. The independent agricultural indicators project provided an opportunity to apply similar techniques to an agricultural question.</p><p>The most important lesson from this week is that meaningful data analysis depends on more than producing code or charts. It requires clean data, suitable analytical methods, careful interpretation, and clear communication of findings.</p><p>As I continue developing my skills in Python, SQL, and data analysis, I intend to apply these techniques to agricultural economics, agricultural research, and data-driven decision-making.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2267a5912ed" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/from-dirty-csvs-to-clean-insights-my-data-cleaning-playbook-in-python-and-sql-c2267a5912ed">From Dirty CSVs to Clean Insights: My Data Cleaning Playbook in Python and SQL</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Week 6 : From NumPy and Pandas to Real-World Weather Data-Cleaning, Joining, and Questioning Data.]]></title>
            <link>https://blog.gopenai.com/week-6-from-numpy-and-pandas-to-real-world-weather-data-cleaning-joining-and-questioning-data-6992624b8d15?source=rss-ab038533369f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6992624b8d15</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Abdulkabirdauda]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 09:58:48 GMT</pubDate>
            <atom:updated>2026-10-20T13:13:19.994Z</atom:updated>
            <content:encoded><![CDATA[<p>Subtitle: Building practical data analysis skills through numerical computing, data manipulation, database querying, and real-world datasets.</p><p><strong>Table of Contents</strong></p><p>Introduction</p><p>What I Learned This Week</p><p>Part One: Working with NumPy</p><p>Part Two: Data Analysis with Pandas</p><p>Part Three: Intermediate SQL</p><p>Part Four: Analysing Real-World Weather Data</p><p>The Challenges I Faced</p><p>How I Overcame the Challenges</p><p>Key Lessons and Insights</p><p>Tools and Technologies Used</p><p>Conclusion</p><p><strong>Introduction</strong></p><p>Week 6 of my DataraFlow Data Science Internship was an important step in developing my practical data analysis skills. This week, I worked with three essential tools in data science: NumPy, Pandas, and SQL. I also applied my knowledge to exercises involving real-world weather data and datasets from different domains.My focus was not just on learning individual functions or writing queries, but also on understanding how these tools can be used to manipulate data, identify patterns, answer questions, and support decision-making.</p><p>Through the week’s lectures and take-home assignments, I practised numerical operations, array manipulation, data filtering, statistical calculations, database querying, joins, aggregations, and window functions. This experience helped me understand how different tools work together in a data analysis workflow, from exploring raw data to extracting meaningful information.</p><p><strong>What I Learned This Week</strong></p><p>My Week 6 learning activities covered three major areas:</p><p>NumPy: Numerical computing, arrays, data types, indexing, slicing, and mathematical operations.</p><p>Pandas: Data manipulation, Series, filtering, sorting, calculations, and handling different data types.</p><p>Intermediate SQL: Database exploration, conditional aggregation, joins, common table expressions, and window functions.</p><p><strong>Part One: Working with NumPy</strong></p><p>NumPy is a Python library that makes numerical computing more efficient. During this week’s work, I explored how NumPy arrays are created, accessed, modified, and used in mathematical calculations.</p><p>Understanding Array Dimensions</p><p>One of the concepts I studied was the difference between zero-dimensional, one-dimensional, two-dimensional, and three-dimensional arrays.</p><p>A zero-dimensional array contains a single value, while a one-dimensional array contains a sequence of values. A two-dimensional array is arranged in rows and columns, while a three-dimensional array can represent a collection of two-dimensional arrays.</p><p>I also learnt how to inspect an array’s dimensions using .ndim and how to check its structure using .shape. Understanding dimensions is important because the structure of an array affects how its values can be accessed and manipulated.</p><p>Data Types and Type Conversion</p><p>I practised converting array elements from one data type to another using .astype(). For example, converting floating-point values to integers removes the decimal portion rather than rounding to the nearest whole number. I also explored how values can be converted to Boolean types.</p><p>This helped me understand why checking data types is important before performing calculations. Incorrect data types can affect the accuracy and reliability of an analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*vqJ3G6XY4-vPru8KoZHN0A.png" /></figure><p>Copying and Viewing Arrays</p><p>Another important concept was the difference between a copy and a view.</p><p>A copy creates a separate array, so changes to the original generally do not affect the copy. A view provides access to the same underlying data, meaning that changes can affect the original array.</p><p>I investigated this relationship using the .base attribute. This distinction is useful when manipulating large datasets because it helps me understand whether an operation creates new data or references existing data.</p><p>Array Manipulation</p><p>I also explored different ways to combine and reshape arrays.</p><p>Some of the functions I practised included:</p><p>np.concatenate() for joining arrays along an existing axis.</p><p>np.stack() for combining arrays along a new axis.</p><p>np.hstack() for horizontal stacking.</p><p>np.vstack() for vertical stacking.</p><p>np.reshape() for changing an array’s shape without changing its total number of elements.</p><p>np.sort() for sorting array elements.</p><p>Reshaping an array requires the total number of elements to remain consistent. For example, an array containing 12 elements can be reshaped into a 3-by-4 array because both structures contain 12 elements.</p><p>I also practised creating arrays using functions such as np.arange(), np.zeros(), np.ones(), and np.asarray().</p><p>Indexing, Slicing, and Mathematical Operations</p><p>Indexing and slicing helped me retrieve particular values or sections of an array.</p><p>I practised accessing elements by their positions, selecting ranges of values, and using step sizes to control which elements are returned. I also explored how to access values in two-dimensional arrays using row and column positions.</p><p>For mathematical operations, I worked with addition, subtraction, multiplication, and division. I also explored comparison functions such as np.greater(), np.less(), np.equal(), and np.isclose().</p><p>These exercises showed me how NumPy can perform operations across entire arrays rather than requiring me to process each element individually.</p><p>Checking Values and Memory Usage</p><p>I practised using functions such as np.isnan() to identify missing numerical values, np.iscomplex() to identify complex numbers with non-zero imaginary components, and np.isreal() to check whether values are real. I also learnt how to use np.isclose() when comparing floating-point numbers that may differ slightly because of numerical precision.</p><p>Finally, I explored the .nbytes attribute to determine how much memory an array’s elements occupy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*uEVQLfBi6nTeAw18jfjNeQ.png" /></figure><p>Overall, these exercises strengthened my understanding of numerical data and the importance of choosing appropriate operations for different data structures.</p><p><strong>Part Two: Data Analysis with Pandas</strong></p><p>Pandas was another major focus of Week 6. It provides tools for working with structured data, especially tables containing rows and columns.</p><p>Understanding Series and DataFrames</p><p>I learnt about two important Pandas data structures:</p><p>Series: A one-dimensional labelled data structure.</p><p>DataFrame: A two-dimensional tabular data structure with rows and columns.</p><p>I practised creating Series from lists, dictionaries, and NumPy arrays. I also learnt how to convert a Series back into a Python list and how to extract a column from a DataFrame. Understanding the difference between a Series and a DataFrame helped me become more comfortable working with structured datasets.</p><p>Selecting Rows and Columns</p><p>I practised selecting specific rows and columns from DataFrames. For example, .head() allows me to inspect the first few rows, while .iloc[] provides position-based selection. I also learnt how to select individual columns or multiple columns by their names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*jkfvLWMfwbxUDdpx9YvXxg.png" /></figure><p>These operations are useful when exploring a dataset before beginning a more detailed analysis. Instead of examining an entire dataset at once, I can focus on the information relevant to a particular question.</p><p>Filtering and Sorting Data</p><p>Filtering was one of the most useful techniques I practised.</p><p>I learnt how to select rows based on conditions such as population thresholds or tuberculosis death counts. I also practised combining multiple conditions using the logical operators &amp; and |.</p><p>An important lesson was that each condition should be enclosed in parentheses when combining conditions in Pandas. I also explored sorting values in ascending or descending order using .sort_values(). These techniques make it easier to identify records that meet specific criteria and arrange information in a useful order.</p><p>Performing Calculations with Series</p><p>I practised performing arithmetic operations between Series, including addition, subtraction, multiplication, division, and floor division.</p><p>I also explored statistical methods such as .sum(), .min(), .max(), .mean(), and .median().</p><p>One practical application involved calculating tuberculosis death rates relative to population. This demonstrated how numerical calculations can transform raw counts into more meaningful measures for comparison.</p><p>I learnt that the units of the original data matter. For example, when population is recorded in thousands, the formula must account for that unit when calculating a rate per 100,000 people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*RUHviRaFUVnw54XXQD-KIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*lNwNKu8iMTN91huVTS2IDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*vcj5dG_Yqb0Jo4dsMkA-8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*SK2w23XVhslzndp20xs5vA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*icuqUk_Bgob-dLgM7cpu1g.png" /></figure><p>Handling Mixed Data Types</p><p>Some datasets contain values of different types, including numbers, text, and missing values.</p><p>I practised using pd.to_numeric() with errors=’coerce’ to convert values into numeric form while representing values that cannot be converted as missing values.</p><p>I also explored converting Series into NumPy arrays, sorting data, and using .explode() to transform a Series containing lists into individual rows.</p><p>These exercises helped me understand that data preparation is not simply about changing values. It also requires preserving useful information and understanding what happens to values that cannot be processed as expected.</p><p><strong>Part Three: Intermediate SQL</strong></p><p>SQL was another important component of Week 6. I worked with more advanced querying techniques to retrieve, organise, combine, and analyse data stored in relational databases.</p><p>Exploring Database Schemas</p><p>I practised exploring database metadata to identify tables and their columns. This included using the INFORMATION_SCHEMA.COLUMNS view to examine tables in a particular schema and count the number of columns in each table.</p><p>I learnt that understanding a database’s structure before writing complex queries can save time and help prevent errors.</p><p>Filtering and Handling Missing Values</p><p>I practised filtering records using conditions and checking for missing values with IS NULL.</p><p>I also worked with pattern matching using LIKE, including searches for weather events containing particular words.</p><p>One important lesson was that missing values require special treatment in SQL. Using = NULL does not correctly identify missing values; instead, I must use IS NULL or IS NOT NULL.</p><p>Grouping, Aggregation, and Conditional Logic</p><p>I explored how GROUP BY can summarise records into categories and how aggregate functions can calculate totals and counts. I also practised using CASE expressions to apply conditional logic within SQL queries. These techniques were useful for analysing customer churn, calculating approval rates, and summarising international trade data.</p><p>I also learnt how HAVING can filter grouped results after aggregation, while WHERE filters individual records before grouping.</p><p>Joins and Anti-Joins</p><p>I practised combining datasets using joins.</p><p>For example, I explored how tuberculosis statistics could be combined with population data to calculate rates that account for population size.</p><p>I also worked with an anti-join approach to identify country records in one dataset that did not have a corresponding match in another dataset.This helped me understand that joining datasets requires more than finding columns with similar names. The values used as join keys must also be sufficiently consistent. Differences in country naming, formatting, and coverage can lead to unmatched records, even when the underlying countries are the same.</p><p>UNION ALL and Common Table Expressions</p><p>I learnt how UNION ALL combines the results of multiple queries while retaining duplicate rows. This was particularly useful when working with weather data from different cities that shared a similar table structure.</p><p>I also practised using common table expressions (CTEs) to organise complex queries into clearer, more manageable steps.</p><p>CTEs helped me separate intermediate calculations from the final result, making the overall logic easier to follow.</p><p>Window Functions and Running Totals</p><p>Window functions were another important area of learning. I practised using functions such as SUM() and ROW_NUMBER() with OVER() clauses. Window functions allow calculations to be performed across related rows without collapsing those rows into a single grouped result.</p><p>For example, a running total can show how exports accumulate over successive months. Similarly, ROW_NUMBER() can rank records within groups, making it useful for identifying the highest-temperature day in each month.</p><p>These exercises helped me understand how SQL can answer more complex analytical questions while keeping much of the processing inside the database.</p><p><strong>Part Four: Analysing Real-World Weather Data</strong></p><p>One of the practical components of Week 6 involved exploring weather datasets for six cities: Beijing, Brasilia, Cape Town, Delhi, London, and Moscow. The datasets contained weather observations that could be combined and analysed to investigate temperature patterns and weather conditions. I practised using SQL to retrieve information from individual city tables and combining the datasets with UNION ALL.</p><p>I also worked with techniques for calculating average mean temperatures by city, examining weather events, and identifying monthly temperature patterns. For London, one of the tasks involved identifying the hottest recorded day in each month using maximum temperature values. This required organising records by month and ranking the observations appropriately.</p><p>Another exercise involved distinguishing between days with no recorded weather event, days with rain-related events, and days with precipitation but no recorded event. These tasks demonstrated how SQL can transform raw observations into summaries that answer specific questions.</p><p>Working with weather data also reinforced the importance of checking data types, handling dates correctly, and ensuring that calculations use appropriate numerical precision.</p><p>The experience helped me see how data analysis can be applied to real-world information rather than being limited to simple examples.</p><p><strong>The Challenges I Faced</strong></p><p>Week 6 introduced several concepts that required careful attention and practice.</p><p>The first and the most challenge i faced during my week 6 work was the set-up. I need to set_up my notebook to connect to dataraflow database. This is the most problem i faced. After pting evrything and run, the problem was error “No module found” after taking almost a day to create my folder at my notebook successfully. Then followed by whitlisting my IP address. The address kept changing after turning off my data.</p><p>After passed through all these challenges, particulary on my VScode, gettting to colab, everything changed. I discovered that a new IP address is prompted and another issue that took another alomost a day.</p><p>In addition, understanding array dimensions and manipulation in NumPy required me to think carefully about the structure of an array. Combining arrays and reshaping them meant paying attention to their dimensions and the number of elements they contained.</p><p>Working with Pandas conditions and data types required precision. Combining multiple filtering conditions, converting mixed values into numeric data, and understanding the difference between a Series and a DataFrame were areas where I needed to pay attention to the details.</p><p>Writing complex SQL queries required me to think through the order of operations. Joins, grouped calculations, CTEs, and window functions each serve different purposes, and using them correctly depends on understanding the question being asked.</p><p>These challenges reminded me that data analysis requires both technical knowledge and careful reasoning.</p><p><strong>How I Overcame the Challenges</strong></p><p>I approached these challenges by breaking problems into smaller steps and focusing on understanding the logic behind each operation.</p><p>For the entire set-up, i needed to first ask my team mates, how to create the file correctly on my notebook and i used chat gbt as my second intern. After i created the files and i entered the neccessary , I tried to get my Ip address range so that even if it changes, it will still fall withing the range. For the google colab to submit the given take-home, i tried all my best but the Ip addres kept chnaging and it diffrent from my previous notebook that dataraflow had already helped me whitelisted. I needed to create an ipynb file at my vscode and did all my sql assignement and then uploaded the file to my colab. it was unsuccessful before because the file was heavy, but i uploaded it using a code. Thus;</p><p>from google.colab import files</p><p>uploaded=files.upload()</p><p>which force the file to upload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdLfqpngpN6BKImfSsPkpg.png" /></figure><p>For NumPy, I paid attention to array shapes, dimensions, indexing, and data types before attempting more complicated manipulations.</p><p>For Pandas, I practised selecting small portions of datasets, checking column names, applying conditions, and inspecting the results. This made it easier to understand how individual operations affected the data.</p><p>For SQL, I approached complex queries by identifying the required output first and then determining which tables, filters, joins, and calculations were necessary. Where appropriate, I used intermediate query steps to make the logic easier to follow.</p><p>I also learnt to pay closer attention to missing values, data types, and the difference between raw counts and calculated rates.</p><p>The main lesson from this process was that complex analytical problems become more manageable when they are broken down into smaller, understandable steps. In future projects, I intend to continue validating intermediate results rather than focusing only on whether a query or script executes successfully.</p><p><strong>Key Lessons and Insights</strong></p><p>Week 6 reinforced several important lessons for me.</p><p>1. Data structures matter. Understanding how NumPy arrays, Pandas Series, and DataFrames are organised makes it easier to select the right operations for a task.</p><p>2. Data cleaning and preparation are essential. Missing values, inconsistent data types, and differences in naming can affect the quality of analytical results.</p><p>3. SQL is more than a tool for retrieving records. With joins, aggregations, CTEs, and window functions, it can support detailed analysis and answer practical business questions.</p><p>4. Context matters when interpreting data. A raw number may not provide a meaningful comparison until it is considered alongside population size, time, or another relevant measure.</p><p>5. Writing correct code is only part of the process. Understanding the result, checking assumptions, and communicating findings are equally important parts of data analysis.</p><p>Most importantly, I am learning to approach data problems with greater structure and curiosity. Instead of focusing only on how to use a function, I am becoming more interested in understanding which problem it solves and when it should be used.</p><p><strong>Conclusion</strong></p><p>Week 6 of my DataraFlow internship strengthened my understanding of NumPy, Pandas, and intermediate SQL. Through lectures and practical assignments, I gained experience with numerical computing, structured data manipulation, database querying, and the analysis of real-world datasets.</p><p>The experience also helped me appreciate the importance of data quality, careful calculations, and clear problem-solving methods.</p><p>As I continue my data science journey, I want to build on these foundations by improving my ability to work with larger datasets, write more efficient queries, and communicate analytical findings clearly.</p><p>I recognise that becoming proficient in data science takes consistent practice, patience, and a willingness to learn from mistakes. Each week provides an opportunity to strengthen my skills and apply them to increasingly practical problems.</p><p>I look forward to applying these lessons in future projects and continuing to grow through the DataraFlow internship.</p><p><strong>Acknowledgement</strong></p><p>I am grateful to DataraFlow for providing a structured learning environment that encourages practical application, consistent improvement, and collaboration. This week’s activities have further motivated me to keep developing my technical skills and exploring how data can be used to solve real-world problems.</p><p>#DataraFlow #DataScience #Python #NumPy #Pandas #SQL #DataAnalytics #LearningJourney</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6992624b8d15" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/week-6-from-numpy-and-pandas-to-real-world-weather-data-cleaning-joining-and-questioning-data-6992624b8d15">Week 6 : From NumPy and Pandas to Real-World Weather Data-Cleaning, Joining, and Questioning Data.</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Numbers: Using Machine Learning to Understand Agricultural Commodity Prices in Nigeria.]]></title>
            <link>https://medium.com/@abdulkabirdauda1/beyond-the-numbers-using-machine-learning-to-understand-agricultural-commodity-prices-in-nigeria-95e75efdde64?source=rss-ab038533369f------2</link>
            <guid isPermaLink="false">https://medium.com/p/95e75efdde64</guid>
            <category><![CDATA[agriculture]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[agricultural-economics]]></category>
            <category><![CDATA[nigeria]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abdulkabirdauda]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 06:53:26 GMT</pubDate>
            <atom:updated>2026-10-10T07:12:30.839Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Beyond the Numbers: Using Machine Learning to Understand Agricultural Commodity Prices in Nigeria.</strong></p><p>Exploring how data science and agricultural economics can work together to improve agricultural market analysis.</p><p><strong>Table of Contents</strong></p><p>• Introduction: Why Agricultural Prices Matter</p><p>• The Problem I Want to Investigate</p><p>• Why I Chose This Research Topic</p><p>• What Agricultural Economics Has to Do with Machine Learning</p><p>• What I Intend to Investigate</p><p>• My Proposed Research Approach</p><p>• The Data Behind the Research</p><p>• Models I Plan to Explore</p><p>• How I Will Evaluate the Models</p><p>• Looking Beyond Prediction Accuracy</p><p>• Challenges I Anticipate</p><p>• What I Hope to Achieve</p><p>• Connecting Agriculture with Data Science</p><ul><li>Conclusion</li></ul><p>Introduction: Why Agricultural Prices Matter</p><p>Imagine a farmer preparing to sell a harvest of maize. The farmer needs to decide whether to sell immediately, store the produce for a while, or transport it to another market. Each option comes with its own costs and risks. The decision becomes more difficult when the farmer does not know how prices might change in the coming weeks or months.</p><p>A similar problem faces traders deciding when to purchase commodities, processors planning their raw-material requirements, and agribusinesses managing their finances. Consumers and policymakers are also affected when food prices rise or fluctuate unexpectedly.</p><p>In Nigeria, agricultural commodity prices can change because of several interacting factors, including seasonal production patterns, supply and demand, transportation costs, inflation, exchange-rate movements, and changing market conditions. Although nobody can predict every market movement with certainty, historical data may contain useful patterns that help us understand price behaviour and estimate what could happen next.</p><p>This is where my proposed research comes in.</p><p>My research topic is: Machine Learning for Predicting Agricultural Commodity Prices in Nigeria: An Agricultural Economics Approach.</p><p>The central idea is to investigate whether machine learning can help us use historical agricultural market data to make better predictions about commodity prices and understand what those predictions mean for agricultural decision-making.</p><p>The Problem I Want to Investigate</p><p>Agricultural price uncertainty is not simply a matter of numbers increasing or decreasing. It can affect the decisions people make throughout the agricultural value chain. For example, a farmer who sells produce when prices are unusually low may receive less income than expected. A trader who purchases a commodity without understanding its recent price movements may face financial losses. A processor may also struggle to plan purchases when raw-material prices change considerably. These situations illustrate the importance of reliable market information.</p><p>Historical price records can help us understand what has happened, but the challenge is determining how useful those records are for predicting future prices. Can previous price movements help us anticipate subsequent changes? Do agricultural commodity prices follow seasonal patterns? Can information about inflation or exchange rates improve predictions? Do different machine-learning models perform differently when applied to agricultural prices?</p><p>These are some of the questions I want to investigate. Rather than assuming that machine learning will solve every problem, I want to test its usefulness using actual data and evaluate the results objectively.</p><p><strong>Why I Chose This Research Topic</strong></p><p>My academic background is in Agricultural Technology, and I am interested in the relationship between agriculture, economics, research, and technology. Agriculture is not limited to crop production. It also involves markets, financial decisions, resource allocation, business planning, and the movement of agricultural products from producers to consumers.</p><p>My interest in Agricultural Economics, particularly Agricultural Business and Financial Management, has made me increasingly interested in how data can support decisions within the agricultural sector. At the same time, my participation in the DataraFlow programme is helping me develop practical skills in Python, data analysis, data cleaning, visualization, and machine learning.</p><p>I see this research as an opportunity to bring these interests together. Instead of working on a machine-learning project that is disconnected from my academic background, I want to apply the skills I am developing to a problem that matters to agriculture and agricultural businesses in Nigeria.</p><p>For me, this is more than learning how to build a predictive model. It is about understanding how data science can contribute to a field I already know and want to develop further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5t1oI7eghDCdxWDpbyvahw.png" /></figure><p><strong>What Agricultural Economics Has to Do with Machine Learning</strong></p><p>At first glance, agricultural economics and machine learning may appear to be separate fields. Agricultural economics examines issues such as agricultural markets, prices, production decisions, costs, income, demand, supply, and resource allocation. Machine learning, on the other hand, involves computational methods that learn patterns from data and use those patterns to make predictions.</p><p>The two fields can complement each other. Consider a dataset containing monthly prices of rice across several Nigerian markets. By analysing the data, we may discover that prices change over time, that some months consistently differ from others, or that price movements vary across locations. Machine-learning models can use information from previous periods to estimate prices in later periods. However, obtaining a prediction is only one part of the process.</p><p>An agricultural economics perspective also asks what the findings mean. If historical prices provide most of the predictive information, what does that tell us about the usefulness of market-price records? If adding exchange-rate or inflation information improves prediction, how might that inform our understanding of agricultural markets? These questions help connect computational results with economic interpretation.</p><p>The goal is not simply to build a model that predicts prices. It is to investigate whether the model can provide useful information for understanding agricultural markets and supporting decisions.</p><p><strong>What I Intend to Investigate</strong></p><p>The research will focus on selected agricultural commodities in Nigeria, with the final selection depending on the availability and quality of historical data.</p><p>The study will investigate several related questions.</p><p>First, what patterns can be found in historical commodity prices? I want to examine how prices have changed over time, whether seasonal patterns exist, and whether prices differ across markets.</p><p>Second, how accurately can machine-learning models predict commodity prices? Different models will be trained and tested to determine how well they estimate prices.</p><p>Third, can economic variables improve predictions? Where reliable and compatible data are available, I plan to investigate whether variables such as inflation and exchange rates provide additional predictive value beyond historical prices.</p><p>Finally, what can the results tell us about agricultural markets? I want to examine which variables contribute most to the predictions and discuss their relevance to agricultural economic decision-making.</p><p>These questions will guide the project from data collection through modelling and interpretation.</p><p><strong>My Proposed Research Approach</strong></p><p>I intend to approach the project in stages, beginning with understanding the data before moving into more advanced modelling.</p><p>Understanding the Data</p><p>The first step will be to identify suitable agricultural commodity price datasets and examine their structure. I will investigate the available commodities, markets, observation periods, price variables, and missing information. This stage will help determine the final scope of the study.</p><p>Cleaning and Preparing the Data</p><p>Real-world datasets are not always ready for analysis. Some may contain missing values, duplicate observations, inconsistent names, or variables recorded in different formats. These issues must be investigated and handled appropriately before the data can be used for modelling. I will use Python to inspect, clean, and prepare the selected data.</p><p>Exploring Price Patterns</p><p>Before building predictive models, I want to understand what the data reveal. I plan to use tables, statistical summaries, and visualizations to examine price trends, seasonal patterns, differences between markets, and relationships between selected variables. This stage is important because it will help me understand the data rather than treating the modelling process as a black box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtO4qbkBu-nlt9HeGASWkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*wFLlvVYJ2gJu_tmtE2tv5Q.png" /></figure><p>Developing Predictive Features</p><p>Machine-learning models require suitable input variables. I plan to investigate features such as previous commodity prices, moving averages, and calendar information. Where suitable economic data are available, I will also examine how they can be incorporated.</p><p>For example, the price recorded in an earlier month may provide useful information when estimating the price in a later month. All features will be constructed carefully to ensure that information from the future does not unintentionally enter a prediction for an earlier period.</p><p>Training and Testing the Models</p><p>After preparing the data, I will develop a baseline model and compare it with selected machine-learning approaches. The purpose is to determine whether more complex models offer a meaningful improvement over simpler alternatives.</p><p>I will also use a validation approach that respects the chronological order of observations, so that earlier data are used to predict later data. This is particularly important in price forecasting because a model should not be evaluated using information it would not have known at the time of prediction.</p><p><strong>The Data Behind the Research</strong></p><p>The quality of the research will depend partly on the quality and suitability of the data. One promising source is the World Bank’s Nigeria — Monthly Food Price Estimates by Product and Market dataset. It provides historical food-price information across Nigerian markets and includes observations extending back to 2007.</p><p>Another potential source is the National Bureau of Statistics (NBS), particularly its Selected Food Price Watch publications and related commodity-price materials.</p><p>These sources provide possible starting points for studying agricultural prices in Nigeria. However, identifying a dataset is only the beginning. I will need to examine the available variables, consistency, completeness, observation frequency, and suitability for the research questions.</p><p>I also plan to investigate whether relevant economic variables can be obtained from reliable sources and aligned with the selected commodity-price data. The final dataset and the commodities included in the analysis will be determined by the results of this assessment.</p><p>This is important because I do not want to select variables simply because they sound relevant. They must be available in a form that allows them to be analysed responsibly.</p><p><strong>Models I Plan to Explore</strong></p><p>I plan to begin with a simple baseline before experimenting with more advanced machine-learning models.</p><p>Linear Regression</p><p>Linear Regression will provide a relatively simple benchmark. It will help establish how well a straightforward model can estimate commodity prices using the selected input variables.</p><p>Random Forest</p><p>Random Forest combines the predictions of multiple decision trees. It can capture nonlinear relationships and interactions between variables, making it a useful candidate for this type of problem.</p><p>Gradient Boosting</p><p>Gradient Boosting builds a predictive model progressively, with later stages working to improve earlier predictions. I will consider it as another approach for modelling potentially complex relationships in the data.</p><p>Other models may be considered if the final dataset and research requirements justify their inclusion. I do not intend to use every available algorithm simply to make the project look more advanced. The priority will be to select suitable models, understand how they work, and compare their performance fairly.</p><p><strong>How I Will Evaluate the Models</strong></p><p>A model can produce predictions without necessarily producing useful predictions. For that reason, I will evaluate the models using appropriate performance metrics.</p><p>Mean Absolute Error (MAE) will help measure the average absolute difference between predicted and actual prices.</p><p>Root Mean Squared Error (RMSE) will measure prediction errors while giving greater weight to larger errors.</p><p>R² will provide an additional measure of how much variation in the target variable is explained by the model within the evaluation framework.</p><p>I will interpret these measures together rather than relying on a single score. I also plan to compare models using the same evaluation periods and procedures. This will help ensure that the comparison is fair.</p><p>Importantly, I will not decide in advance which model should win. The results of the experiments should determine which approach performs best under the conditions of the study.</p><p><strong>Looking Beyond Prediction Accuracy</strong></p><p>One aspect of this research that particularly interests me is understanding whether adding economic information improves prediction. I plan to compare different groups of input variables.</p><p>The first group will focus on historical prices and relevant time-based features. The second will combine historical prices with suitable economic variables, such as inflation or exchange-rate indicators, where compatible data are available. If the data support it, I may investigate additional variables in a further comparison.</p><p>This will help answer an important question:</p><p>Does additional economic information improve price predictions, or can historical price patterns provide comparable predictive performance?</p><p>I also want to investigate which variables contribute most to the models’ predictions. For instance, if a previous price is consistently important, that may indicate that historical price information is particularly useful for forecasting. If an economic variable improves model performance, I will examine what that result could mean in the context of agricultural markets.</p><p>I will be careful not to confuse predictive importance with causation. A variable helping a model make better predictions does not, by itself, prove that the variable causes prices to change.</p><p>That distinction matters because the purpose of the research is to produce useful and defensible findings, not simply interesting graphs or model scores.</p><p><strong>Challenges I Anticipate</strong></p><p>I expect the project to involve several challenges.</p><p>One challenge will be finding data that are sufficiently complete and consistent. Some variables may have different reporting frequencies or may not cover the same period as the commodity-price data.</p><p>Another challenge will be determining which features are genuinely useful. Including more variables does not automatically improve a model, and some variables may introduce noise rather than useful information.</p><p>I will also need to avoid data leakage and ensure that the evaluation reflects a realistic forecasting situation.</p><p>Finally, even a model that performs well on historical observations may struggle when unusual events change market conditions. Unexpected disruptions, policy changes, extreme weather, or major economic shocks can create patterns that historical data do not adequately capture.</p><p>These challenges are part of the research process. I intend to document them and discuss their implications rather than hide them from the final findings.</p><p><strong>What I Hope to Achieve</strong></p><p>By the end of the project, I hope to develop a well-documented machine-learning workflow for predicting selected agricultural commodity prices in Nigeria.</p><p>The expected outputs include a prepared dataset, exploratory analysis, visualizations, predictive models, model comparisons, and an interpretation of the findings from an agricultural economics perspective.</p><p>I also hope to develop a clearer understanding of how data quality, feature selection, model choice, and validation affect the reliability of price predictions. More broadly, I want the project to demonstrate how data science can be applied to a practical agricultural problem.</p><p>The research may also provide a foundation for future work involving other variables, markets, or agricultural questions, depending on the findings and available data.</p><p>Any potential benefits for farmers, traders, agribusinesses, or policymakers will depend on the actual performance of the models and the extent to which their predictions prove useful in practice.</p><p><strong>Connecting Agriculture with Data Science</strong></p><p>This project represents an important learning opportunity for me.</p><p>My background in Agricultural Technology has given me an understanding of agriculture as a field involving production, research, and practical challenges. My growing interest in Agricultural Economics has encouraged me to think more about markets, prices, and financial decisions.</p><p>Through DataraFlow, I am developing the technical skills needed to investigate these issues using data. Bringing these areas together allows me to work on a problem that connects my academic background with the direction in which I want to grow professionally.</p><p>I am approaching this research as a learning process. I expect to encounter difficulties, revise my approach when necessary, and improve my understanding as I move from the proposal to data analysis and modelling.</p><p>For me, meaningful progress will not be measured only by whether a model produces a good score. It will also be measured by whether I can explain the problem clearly, justify my methods, evaluate the evidence honestly, and communicate what the results mean.</p><p><strong>Conclusion</strong></p><p>Agricultural commodity prices affect decisions throughout Nigeria’s agricultural value chain. Although price movements cannot be predicted with complete certainty, historical market data may contain useful information about trends, seasonality, and relationships that can support forecasting.</p><p>My proposed research, Machine Learning for Predicting Agricultural Commodity Prices in Nigeria: An Agricultural Economics Approach, will investigate how historical price information and relevant economic variables can be used to predict selected commodity prices.</p><p>By comparing a baseline with selected machine-learning models, evaluating their predictions on later observations, and interpreting the results from an agricultural economics perspective, I hope to develop a clearer understanding of both the capabilities and limitations of data-driven price forecasting.</p><p>This is the beginning of the research, not the conclusion. The next steps are to finalize the data, examine the evidence, build and evaluate the models, and allow the findings to determine what conclusions can reasonably be drawn.</p><p>I look forward to sharing the progress, challenges, and lessons from this project as the work develops. The question I am setting out to investigate is simple:<strong> How useful can historical agricultural market data and machine learning be in helping us understand and predict commodity prices in Nigeria?</strong></p><p>That is the question guiding my research.</p><p>This article introduces my proposed research project. The data analysis and model evaluation are planned stages of the study; no empirical results are claimed at this stage.</p><p>I am Daud Abdulkabir Alade, a First-Class Agricultural Technology graduate and the best graduating student at the department of Agronomy exploring the intersection of agriculture, agricultural economics, and data science through the DataraFlow programme.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95e75efdde64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Python Fundamentals to Working with Real Data: My Week 3 Learning Journey]]></title>
            <link>https://blog.gopenai.com/from-python-fundamentals-to-working-with-real-data-my-week-3-learning-journey-5ceeef98430d?source=rss-ab038533369f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ceeef98430d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[spoftware-development]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abdulkabirdauda]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 08:28:47 GMT</pubDate>
            <atom:updated>2026-09-24T12:15:14.308Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring Modules, Dates, Mathematics, JSON, Error Handling, Virtual Environments and My First Steps into SQL</p><p><strong>Table of Contents</strong></p><p>Introduction: Moving Beyond the Basics</p><p>Understanding Python Modules and Reusable Code</p><p>Working with Dates and Time Using Python</p><p>Using Python for Mathematical Operations</p><p>Understanding JSON and Working with Structured Data</p><p>Handling User Input and Making Programs Interactive</p><p>Error Handling: Making Python Programs More Reliable</p><p>PIP, Packages and Virtual Environments</p><p>An Introduction to SQL and Database Queries</p><p>What Week 3 Changed in My Understanding of Data</p><p>Conclusion: Connecting Python to the Data World</p><p>Introduction: Moving Beyond the Basics</p><p>Week 3 felt different from the earlier stages of my Python learning. During the previous weeks, I spent a lot of time understanding programming concepts such as object-oriented programming, inheritance, iterators, polymorphism and scope. Those topics helped me understand how Python code is structured and how different parts of a program interact.</p><p>This week, however, I started seeing Python from a more practical perspective. I was introduced to modules, dates, mathematical operations, JSON, user input, error handling, PIP, virtual environments and SQL.</p><p>At first, some of these concepts looked unrelated. As I worked through them, I began to understand that they are actually connected to the way programmers and data professionals work with real data. For example, data can come from a JSON file, be processed with Python, involve dates and mathematical calculations, and eventually be stored in or retrieved from a database using SQL. That connection became one of my biggest lessons from Week 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5I_mTl777Xl09LVD4uTG3A.png" /><figcaption>“My Week 3 workspace as I moved from Python fundamentals toward practical data handling.”</figcaption></figure><p>Understanding Python Modules and Reusable Code</p><p>One of the first things I learned this week was the idea of a Python module.</p><p>A module is simply a Python file containing code that can be reused in another program. Instead of writing every function ourselves, we can import modules that already provide the functionality we need.</p><p>For example, Python has a module called platform.</p><p>import platform</p><p>x = platform.system()</p><p>print(x)</p><p>The important thing I understood here is that import platform gives my program access to functionality that already exists inside the platform module.</p><p>I also learned about the dir() function.</p><p>import platform</p><p>x = dir(platform)</p><p>print(x)</p><p>The dir() function allows me to see the names of functions, classes and other objects available inside a module. This helped me understand that a module is not something mysterious. It is essentially a collection of reusable Python code.</p><p>I also learned that I do not always have to import an entire module. I can import a specific function or object.</p><p>For example:</p><p>from math import sqrt</p><p>print(sqrt(64))</p><p>Instead of writing:</p><p>import math</p><p>print(math.sqrt(64))</p><p>both approaches can produce the same result, but they differ in how the function is imported and referenced.</p><p>Take home;</p><p>The main lesson for me was reusability.</p><p>Rather than writing everything from scratch, Python allows me to build on existing code. This is important in practical programming because it saves time and makes programs easier to develop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*RYmLywjli_h3TvV17luP-g.png" /></figure><p><strong>Working with Dates and Time Using Python</strong></p><p>Dates are everywhere in real-world data, A dataset may contain information about when a transaction occurred, when a student registered, when an employee joined an organization, or when a particular event happened, Python provides the datetime module for working with dates and times.</p><p>For example:</p><p>import datetime</p><p>x = datetime.datetime.now()</p><p>print(x)</p><p>This returns the current date and time.</p><p>I also learned that I can extract individual parts of the date:</p><p>import datetime</p><p>x = datetime.datetime.now()</p><p>print(x.year)</p><p>print(x.month)</p><p>print(x.day)</p><p>This means that instead of treating the date as one large value, I can work with the year, month and day separately.</p><p>I also learned how to create a specific date:</p><p>import datetime</p><p>x = datetime.datetime(2020, 5, 17)</p><p>print(x)</p><p>Another interesting part was strftime().</p><p>It allows me to control how a date is displayed.</p><p>For example:</p><p>import datetime</p><p>x = datetime.datetime(2020, 5, 17)</p><p>print(x.strftime(“%A”))</p><p>print(x.strftime(“%B”))</p><p>print(x.strftime(“%Y”))</p><p>This can give the weekday, month and year in a readable format.</p><p>What this taught me?</p><p>I learned that dates are not just information displayed on a screen. They are data that can be extracted, formatted and manipulated. That is particularly important in data analysis because many datasets contain dates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*FR5jbiLsBgrUPkHGu39NPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*kNuIc0OPHmVwXfYJ3D_d7w.png" /><figcaption>Using Python’s datetime module to work with dates and extract useful information</figcaption></figure><p><strong>Using Python for Mathematical Operations</strong></p><p>Another part of Week 3 focused on mathematical operations. Python already provides some useful built-in mathematical functions.</p><p>For example:</p><p>numbers = [5, 10, 25]</p><p>print(min(numbers))</p><p>print(max(numbers))</p><p>print(abs(-7.25))</p><p>print(pow(4, 3))</p><p>Here, min() finds the smallest value, max() finds the largest value, abs() returns the positive value of a number, and pow() performs exponentiation.</p><p>I also learned about Python’s math module,which extends the list of mathematical functions</p><p>import math;using method and constants of the module</p><p>print(math.sqrt(64));returns the square root of a number</p><p>print(math.ceil(1.4));rounds a number upwards to its nearest integer</p><p>print(math.floor(1.4));rounds a number downwards to its nearest integer</p><p>print(math.pi); constant, returns the value of pi(3.14….)</p><p>The math module provides additional mathematical functions and constants.</p><p>For example, math.pi provides the value of π, which can be useful when calculating the area of a circle.</p><p>import math</p><p>radius = 5</p><p>area = math.pi * radius ** 2</p><p>print(area)</p><p>Take home</p><p>This section showed me that Python can be used not only for programming logic but also for mathematical and analytical tasks. This becomes especially relevant to me because data analysis involves calculations, measurements and numerical interpretation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*kZEc_PWZ477K7esctjuyMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*7jEcngKuGNPqm8NhNoENVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*GoGHV7EBrLYM__azP97d2A.png" /><figcaption>Quetions and answer from user and storing the answer for final ouput</figcaption></figure><p><strong>Understanding JSON and Working with Structured Data</strong></p><p>The JSON section was one of the areas that helped me understand how Python interacts with data outside the normal Python environment. JSON stands for JavaScript Object Notation, It is a common format used to store and exchange structured information.</p><p>Python and JSON have corresponding data types.</p><p>For example:</p><p>Python</p><p>JSON</p><p>Dictionary</p><p>Object</p><p>List</p><p>Array</p><p>Tuple</p><p>Array</p><p>String</p><p>String</p><p>Integer</p><p>Number</p><p>Float</p><p>Number</p><p>True</p><p>true</p><p>False</p><p>false</p><p>None</p><p>null</p><p>I learned that Python provides the json module for working with JSON.</p><p>For example:</p><p>import json</p><p>student = {</p><p>“name”: “John”,</p><p>“age”: 30,</p><p>“grade”: “A”</p><p>}</p><p>print(json.dumps(student))</p><p>The json.dumps() function converts a Python object into a JSON-formatted string.</p><p>I also learned that the output can be made easier to read by using indentation.</p><p>print(json.dumps(student, indent=4))</p><p>Instead of everything appearing on one line, the information is properly organised.</p><p>I also learned an important distinction between:</p><p>json.dumps()</p><p>and</p><p>json.loads()</p><p>dumps() converts a Python object into a JSON string, while loads() converts a JSON string back into a Python object.</p><p>For example:</p><p>import json</p><p>data = ‘{“name”: “John”, “age”: 30}’</p><p>student = json.loads(data)</p><p>print(student[“name”])</p><p>print(student[“age”])</p><p>This was important because it showed me that JSON is not only something I can display. I can actually move data between JSON and Python.</p><p>What I learned</p><p>I began to understand why JSON is important in data-related work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUtupeDE3xwUegCJQevZyA.png" /><figcaption>Practising the conversion and formatting of structured JSON data in Python</figcaption></figure><p><strong>Handling User Input and Making Programs Interactive</strong></p><p>I also learned how to make a Python program interact with a user using input().</p><p>For example:</p><p>name = input(“Enter your name: “)</p><p>print(f”Hello {name}”)</p><p>Python pauses when it reaches input() and waits for the user to provide information. I also learned that Python treats input as a string, even when the user enters a number.</p><p>For example:</p><p>age = input(“Enter your age: “)</p><p>print(type(age))</p><p>The result will show that age is a string.</p><p>If I want to perform numerical calculations, I need to convert the input.</p><p>age = int(input(“Enter your age: “))</p><p>print(age + 1)</p><p>For decimal values, I can use float().</p><p>number = float(input(“Enter a number: “))</p><p>print(number * 2)</p><p>What I learned</p><p>This section helped me understand the difference between receiving data and using data.</p><p>The user may provide information as text, but my program needs to convert it into the appropriate data type before performing certain operations.</p><p><strong>Error Handling: Making Python Programs More Reliable</strong></p><p>One thing I realised while working with user input is that users do not always provide the type of information a program expects.</p><p>For example, if a program expects a number and the user enters:</p><p>hello</p><p>an error can occur.</p><p>Python provides try and except to handle such situations.</p><p>For example:</p><p>try:</p><p>number = int(input(“Enter a number: “))</p><p>print(100 / number)</p><p>except ValueError:</p><p>print(“Please enter a valid number.”)</p><p>except ZeroDivisionError:</p><p>print(“You cannot divide by zero.”)</p><p>There are two different problems that can occur here.</p><p>ValueError handles a situation where the user enters something that cannot be converted into an integer.</p><p>ZeroDivisionError handles the situation where the user enters 0.</p><p>Instead of allowing the program to crash, I can give the user an appropriate message.</p><p>Take home;</p><p>Error handling is not simply about stopping errors. It is about making a program more robust, predictable and user-friendly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*1KNnalMqELZyaqAF79DNVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQBn3dJubbdB7I8Co1UFew.png" /><figcaption>Using exception handling to make a Python program respond safely to invalid input</figcaption></figure><p><strong>PIP, Packages and Virtual Environments</strong></p><p>Another important area I studied was package management. Python has many external packages that extend what the language can do. PIP is used to install Python packages.</p><p>For example:</p><p>pip install numpy</p><p>I also learned why virtual environments are useful.</p><p>A virtual environment creates an isolated environment for a particular Python project. This means that packages installed for one project do not necessarily interfere with another project.</p><p>For example, I can create a virtual environment with:</p><p>python -m venv myenv. but it failed in colab with ensurepip error, so iused the alternative package</p><p>!pip install virtualenv</p><p>On Windows, I can activate it with:</p><p>myenv\Scripts\activate</p><p>After activation, I can install a package:</p><p>pip install numpy</p><p>I can then check the installed packages using:</p><p>pip list</p><p>This helped me understand something beyond Python syntax: how Python projects are managed in practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqWcCjIqc1SodApxUC6D-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVVa07Y7Uj_QUthUi5i_Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVVa07Y7Uj_QUthUi5i_Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVVa07Y7Uj_QUthUi5i_Dw.png" /><figcaption>Verifying the packages installed in my Python environment using pip list</figcaption></figure><p><strong>An Introduction to SQL and Database Queries</strong></p><p>The final part of Week 3 introduced me to SQL — Structured Query Language.</p><p>This was particularly interesting because it connected what I had been learning in Python with the broader field of data.</p><p>Python can be used to analyse and manipulate data, but a lot of real-world structured data is stored inside databases and SQL provides a way to communicate with relational databases.</p><p>One of the first SQL commands I encountered was:</p><p>SELECT *</p><p>FROM week08.wb_gdp_2013;</p><p>At first, a query like this can look complicated. Breaking it down makes it much easier to understand.</p><p>SELECT tells SQL what information I want.</p><p>The * means I want all available columns.</p><p>FROM tells SQL which table I want to retrieve the information from.</p><p>Therefore:</p><p>SELECT *</p><p>FROM week08.wb_gdp_2013;</p><p>basically means:</p><p>“Give me all the columns and rows from this table.”</p><p>I also learned that I do not always need every column.</p><p>SELECT country, year</p><p>FROM week08.wb_gdp_2013;</p><p>This retrieves only the country and year columns.</p><p>Filtering Data with WHERE</p><p>SQL can also filter information.</p><p>For example:</p><p>SELECT *</p><p>FROM week08.wb_gdp_2013</p><p>WHERE year = 2013;</p><p>The WHERE clause tells SQL that I only want records satisfying a particular condition.</p><p>This is similar to filtering a dataset during data analysis.</p><p>Sorting Results with ORDER BY</p><p>I can also arrange the returned records.</p><p>SELECT country, year</p><p>FROM week08.wb_gdp_2013</p><p>ORDER BY country ASC;</p><p>ASC means ascending order.</p><p>I can also use:</p><p>ORDER BY country DESC;</p><p>to arrange the results in descending order.</p><p>Counting Data</p><p>SQL can also tell me how many records exist.</p><p>SELECT COUNT(*)</p><p>FROM week08.wb_gdp_2013;</p><p>The COUNT() function counts records.</p><p>This is useful when I need to know the size of a dataset or the number of records satisfying a particular condition.</p><p>Grouping and Aggregating Data</p><p>SQL can also perform calculations across groups.</p><p>For example:</p><p>SELECT country, AVG(x)</p><p>FROM some_table</p><p>GROUP BY country;</p><p>GROUP BY allows information to be grouped according to a particular column, while AVG() calculates an average.</p><p>This introduced me to the idea that SQL is not only used to retrieve data. It can also summarise and analyse data.</p><p>Joining Tables</p><p>Another important concept was joining tables.</p><p>Real-world databases do not always keep every piece of information in one table.</p><p>Two tables can be connected using a common key.</p><p>For example:</p><p>SELECT *</p><p>FROM a</p><p>JOIN b</p><p>ON a.key = b.key;</p><p>The JOIN combines related information from the two tables.</p><p>This is something I expect to encounter frequently as I progress further into data analysis and database work.</p><p><strong>What Week 3 Changed in My Understanding of Data</strong></p><p>Looking back at Week 3, I realised that the different topics were not as separate as they initially appeared.</p><p>Modules taught me how to reuse existing functionality.</p><p>datetime showed me how to work with dates.</p><p>The math module provided tools for numerical operations.</p><p>JSON showed me how structured data can be represented and exchanged.</p><p>User input showed me how programs can receive information.</p><p>Exception handling showed me how to deal with unexpected situations.</p><p>PIP and virtual environments introduced me to managing Python projects and dependencies.</p><p>Finally, SQL introduced me to querying information stored in databases.</p><p>The bigger picture started becoming clearer:</p><p>Code → Data → Storage → Retrieval → Analysis</p><p>This is the part of Week 3 that I found most valuable.</p><p><strong>Conclusion: Connecting Python to the Data World</strong></p><p>Week 3 was more than learning additional Python syntax for me.</p><p>It helped me begin understanding how programming connects with real-world data workflows.</p><p>I started the week learning how to import modules and work with dates and mathematics. I progressed into JSON, user input and error handling, then moved into package management and virtual environments. Finally, I was introduced to SQL and the basic logic behind querying databases.</p><p>I know there is still much more to learn, particularly when it comes to SQL and working with real datasets. However, this week gave me a clearer picture of where these skills fit within my broader data-learning journey.</p><p>The biggest lesson I am taking from Week 3 is that learning to code is only one part of becoming a data professional. The real value comes from understanding how different tools work together to collect, manage, retrieve and analyse data.</p><p>And that is exactly the direction I want to continue building toward.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ceeef98430d" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/from-python-fundamentals-to-working-with-real-data-my-week-3-learning-journey-5ceeef98430d">From Python Fundamentals to Working with Real Data: My Week 3 Learning Journey</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FROM PYTHON BASICS TO BUILDING MY FIRST OBJECT-ORIENTED SYSTEM]]></title>
            <link>https://blog.gopenai.com/from-python-basics-to-building-my-first-object-oriented-system-22d0aadd2635?source=rss-ab038533369f------2</link>
            <guid isPermaLink="false">https://medium.com/p/22d0aadd2635</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[pop]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-for-beginners]]></category>
            <dc:creator><![CDATA[Abdulkabirdauda]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 12:33:09 GMT</pubDate>
            <atom:updated>2026-09-18T11:16:57.887Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TABLE OF CONTENTS</strong></p><p>Week 2: Moving Beyond the Python Basics</p><p>From Functions to Objects: Understanding OOP</p><p>Inheritance: Learning to Build on Existing Classes</p><p>Iterators: Understanding What Happens Behind a for Loop</p><p>Polymorphism: One Interface, Different Behaviours</p><p>Scope and Encapsulation: Understanding Where Data Lives</p><p>Putting Everything Together: My Library Management System</p><p>The Challenges That Made Me Think Differently</p><p>What Week 2 Changed in My Understanding of Python</p><p>What I’m Taking Into Week</p><p>1. Week 2: Moving Beyond the Python Basics</p><p>Week 1 introduced me to Python from the ground up. I spent time getting comfortable with variables, conditions, loops, functions, lists, dictionaries, file handling, and basic problem-solving.</p><p>Week 2 felt different, I was no longer just writing small programs that performed one task. I started learning how Python programs can be structured around objects, classes, inheritance, reusable behaviour, and data. At first, some of the concepts looked like a completely different side of Python. Terms such as “__init__()”, inheritance, “super()”, iterators, polymorphism, “global”, “nonlocal”, and Method Resolution Order were new areas for me to understand.</p><p>What helped me was learning each concept through small examples before combining them into a larger project. By the end of the week, I had moved from simply asking, “How do I make this code work?” to also asking, “How should I structure this code?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hQ35ujtAe9E0iO-Bs5FXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqJVEWX3G9mD07XMsG7S-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aV26aoHW6Wzn-G60JUqPKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qp0VmihBdfAJIEcUGGnIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*1l0Aka4lED4rSsY7iRMAaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrvHFEovaVoz4yEh3KKEwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*RtPffNZkto6CWR_OACSqPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GwXTf8YmWi_V36wuuo22A.png" /><figcaption><strong>My week 2 DataraFlow task page showing the five sections of my completed week 2 workspace</strong></figcaption></figure><p>2. From Functions to Objects: Understanding OOP</p><p>The first major part of Week 2 was Object-Oriented Programming (OOP). I learned that a class can be used as a blueprint for creating objects. An object can have attributes that describe its data and methods that define what it can do. For example:</p><p>class Person:</p><p>def __init__(self, name, age):</p><p>self.name = name</p><p>self.age = age</p><p>def introduce(self):</p><p>print(f”My name is {self.name} and I am {self.age} years old.”)</p><p>I could then create an object:</p><p>person1 = Person(“John”, 36)</p><p>person1.introduce()</p><p>What initially seemed like extra syntax gradually started making sense. The “__init__()” method is automatically called when an object is created, while “self” allows the object to access its own attributes and methods.</p><p>I also learned about special methods such as “__str__()”, which controls the human-readable string representation of an object. This was an important shift for me because I began seeing Python code as something that could be organised around real-world entities rather than just a sequence of instructions.</p><p>3. Inheritance: Learning to Build on Existing Classes</p><p>After understanding classes, I moved into inheritance. Inheritance allows a child class to receive attributes and methods from a parent class. Instead of repeatedly writing the same code, a child class can build on an existing class. One example I worked with was:</p><p>class Person:</p><p>def __init__(self, fname, lname):</p><p>self.firstname = fname</p><p>self.lastname = lname</p><p>def printname(self):</p><p>print(self.firstname, self.lastname)</p><p>class Student(Person):</p><p>pass</p><p>The “Student” class automatically inherits from “Person”.</p><p>I also learned how “__init__()” works in inheritance and how “super()” can be used to call the parent’s initialization. For example:</p><p>class Student(Person):</p><p>def __init__(self, fname, lname, year):</p><p>super().__init__(fname, lname)</p><p>self.graduationyear = year</p><p>This helped me understand why inheritance is useful: the child class does not need to rewrite everything that already exists in the parent class.</p><p>I then applied the idea to more practical examples involving animals, shapes, bank accounts, vehicles, and eventually books and library members.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*Tlj147ek0luY-xCzyfyPrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*9Dc-_sAR_qmJr4zYovkQbQ.png" /></figure><p>4. Iterators: Understanding What Happens Behind a “for” Loop</p><p>Iterators were one of the concepts that made me look more closely at what Python is doing behind the scenes. Before this section, I was already comfortable using:</p><p>for x in numbers:</p><p>print(x)</p><p>But I had not really thought about how Python gets each item one at a time. I learned about the iterator protocol and the two important methods:</p><p>__iter__()</p><p>__next__()</p><p>I also learned that “iter()” can be used to obtain an iterator and “next()” can retrieve the next item.</p><p>For example:</p><p>numbers = [10, 20, 30, 40, 50]</p><p>my_iterator = iter(numbers)</p><p>print(next(my_iterator))</p><p>print(next(my_iterator))</p><p>When there are no more values, the iterator raises “StopIteration”.</p><p>I then created my own iterators, including a countdown iterator and an iterator for even numbers.</p><p>One example was:</p><p>class CountDown:</p><p>def __init__(self, n):</p><p>self.n = n</p><p>def __iter__(self):</p><p>return self</p><p>def __next__(self):</p><p>if self.n &gt;= 1:</p><p>value = self.n</p><p>self.n -= 1</p><p>return value</p><p>else:</p><p>raise StopIteration</p><p>This section helped me understand that a “for” loop is doing more work internally than what is visible in the simple syntax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*-KjDm7Q0s0IuoBVPkV52Tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*zE9mfxf-SewvT0G7Rg2Qsw.png" /></figure><p>5. Polymorphism: One Interface, Different Behaviours</p><p>Polymorphism was another important concept in Week 2.The word itself means “many forms.” In Python, I learned that different objects can have methods with the same name while behaving differently. For example, I worked with classes that had the same “move()” method but different implementations.</p><p>A car can drive:</p><p>class Car:</p><p>def move(self):</p><p>print(“Car drives”)</p><p>while a bicycle can move differently:</p><p>class Bicycle:</p><p>def move(self):</p><p>print(“Bicycle pedals”)</p><p>I could then place both objects in a list:</p><p>vehicles = [Car(), Bicycle()]</p><p>for vehicle in vehicles:</p><p>vehicle.move()</p><p>The same line:</p><p>vehicle.move()</p><p>produces different behaviour depending on the object.</p><p>I also learned that polymorphism can work together with inheritance and method overriding. This was one of the points where the different Week 2 concepts started connecting instead of feeling like separate topics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*aauvnD5nZ3iM7nR_U9ntVQ.png" /></figure><p>6. Scope and Encapsulation: Understanding Where Data Lives</p><p>The fifth major section focused on Python scope.</p><p>I learned about:</p><p>- local scope</p><p>- global scope</p><p>- enclosing scope</p><p>- the “global” keyword</p><p>- the “nonlocal” keyword</p><p>- built-in scope</p><p>One example that helped me understand the difference was:</p><p>x = 300</p><p>def myfunc():</p><p>x = 200</p><p>print(x)</p><p>myfunc()</p><p>print(x)</p><p>The function prints “200”, while the final “print(x)” prints “300”. The two variables have the same name but belong to different scopes. I also learned that “global” can be used when a function needs to modify a global variable, while “nonlocal” can be used when a nested function needs to modify a variable belonging to an enclosing function.</p><p>Another interesting exercise involved creating a local variable called “len”. That showed me that a local name can hide access to a built-in name within that scope.</p><p>This section made me realise that understanding Python is not only about knowing what a command does. I also need to understand where Python looks for a name and which value it is referring to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*m8wc-N5I4BUvq1ag839iig.png" /></figure><p>7. Putting Everything Together: My Library Management System</p><p>The biggest part of Week 2 was bringing the concepts together in one practical project: a Library Management System. This was different from the smaller exercises because I had to think about how several classes and concepts would work together. The system included a base “Book” class with:</p><p>- title</p><p>- author</p><p>- year</p><p>I then created:</p><p>- “EBook”</p><p>- “PrintedBook”</p><p>as subclasses.</p><p>The same idea was applied to library members:</p><p>- “Member”</p><p>- “StudentMember”</p><p>- “TeacherMember”</p><p>This allowed me to use inheritance to represent relationships between different</p><p>types of books and members.</p><p>Polymorphism in the project</p><p>I gave the different book classes a “get_description()” method. The method exists in the parent class, but the subclasses provide their own versions.</p><p>This meant that I could use:</p><p>book.get_description()</p><p>without having to manually check what type of book I was dealing with. I also made “borrow_book()” behave differently for students and teachers by giving them different borrowing limits.</p><p>Iterators in the project</p><p>The Library class was made iterable so that I could loop through all the books. The Member class was also made iterable so that I could loop through the books borrowed by a particular member. This gave the iterator concepts from earlier in the week a practical purpose.</p><p>Scope and encapsulation</p><p>I used:</p><p>_borrowed_books</p><p>as a protected attribute in the “Member” class.</p><p>I also used:</p><p>__library_name</p><p>as a private attribute in the “Library” class.</p><p>I then created getter and setter methods for the library name.</p><p>Tracking borrowed books</p><p>I also used a class-level variable to keep track of the total number of books borrowed by all members.</p><p>The final system could:</p><p>- store different types of books</p><p>- store different types of members</p><p>- track available books</p><p>- track borrowed books</p><p>- search by title or author</p><p>- iterate through books</p><p>- iterate through a member’s borrowed books</p><p>- enforce different borrowing limits</p><ul><li>count total borrowed books</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*d08y44eI083OG2DLjLiykw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*PdnP-3XCNkGQbmdApm2a1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*0iP5V2FfD8DpGA1tFbO_fA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*DPP7rDGzv8gNcVmhv2K10A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*HaMe8HYfFaNuI5iw4A-9Ug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*DKfC1V12MAKzKlFkEvRfuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*nMb0oXfhtpwihWqN1VM9Lg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_IYVXBzbvsQ8Z95Og5s5qA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*BwSiqwMo4fLnkXgn6rsnVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*LMKDWl36mBV7n3CkSfFsgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*dJQo8IwTY0iQcZnipuEVhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*vK2ECjIT3b61Sl69XOXNog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*vK2ECjIT3b61Sl69XOXNog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*o3kaMnP6ZqpMUmzU-RHS8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*el5Ct-1fwqXT5o0Z-ZrRjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*5MNSqg2VvjgnbNGabAjZvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*j8EJzINvh1vk3lQH2-VTrw.png" /><figcaption>Library sytem management code and results</figcaption></figure><p>8. The Challenges That Made Me Think Differently</p><p>Week 2 was not completely straightforward, one of the biggest challenges was understanding the difference between the concepts instead of simply memorizing their definitions.</p><p>Inheritance and polymorphism, for example, can look similar when first learning them because both involve classes and methods.</p><p>Iterators were another area that required more attention. At first, “__iter__()”, “__next__()”, “iter()”, “next()”, and “StopIteration” seemed like several separate things to remember.</p><p>Eventually, I understood them as parts of one process:</p><p>iter() → gets an iterator</p><p>next() → gets the next item</p><p>__iter__() → defines how the object becomes an iterator</p><p>__next__() → defines what the next item should be</p><p>StopIteration → tells Python there are no more items</p><p>Scope also challenged the way I normally thought about variables. Seeing the same variable name behave differently depending on where it was created made me pay more attention to Python’s rules for finding names.</p><p>The important lesson was that confusion was not necessarily a sign that I was failing. It often meant that I needed to slow down and understand what Python was doing rather than memorizing the answer.</p><p>9. What Week 2 Changed in My Understanding of Python</p><p>Week 1 taught me how to write Python statements and solve small problems.</p><p>Week 2 started teaching me how to design a Python program. That difference is important.</p><p>I now have a better understanding of why programmers use classes, why inheritance can reduce repetition, how polymorphism allows different objects to respond to the same method, how iterators work behind loops, and how scope affects the variables available to a program.</p><p>The Library Management System was particularly useful because it forced me to connect these ideas. Instead of learning:</p><p>This week is about inheritance and then moving on, I had to ask:</p><p>Where would inheritance actually make sense in a real program?</p><p>The answer became clearer when I represented different types of books and members as related classes. That is probably the biggest change in my thinking from this week: I am beginning to think about the structure behind a program, not just the individual lines of code.</p><p>10. What I’m Taking Into Week 3</p><p>I am leaving Week 2 with a stronger foundation in Python OOP and a better understanding of how larger programs can be organized. There is still a lot I don’t know, but I am becoming more comfortable with not knowing everything immediately.</p><p>My approach going forward is simple: learn the concept, write the code, make mistakes, understand the error, fix it, and then try to use the concept in something practical.</p><p>Week 2 was about moving from writing individual pieces of Python code to understanding how those pieces can work together. I’m looking forward to seeing what Week 3 brings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22d0aadd2635" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/from-python-basics-to-building-my-first-object-oriented-system-22d0aadd2635">FROM PYTHON BASICS TO BUILDING MY FIRST OBJECT-ORIENTED SYSTEM</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Agriculture to Python: What My First Week of Learning to Code Taught Me]]></title>
            <link>https://blog.gopenai.com/from-agriculture-to-python-what-my-first-week-of-learning-to-code-taught-me-be3a23ebd491?source=rss-ab038533369f------2</link>
            <guid isPermaLink="false">https://medium.com/p/be3a23ebd491</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Abdulkabirdauda]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 07:50:42 GMT</pubDate>
            <atom:updated>2026-09-10T14:46:48.929Z</atom:updated>
            <content:encoded><![CDATA[<p>My first week learning Python, solving beginner problems, making mistakes, and discovering that programming is more about problem-solving than memorising syntax.</p><p><strong>Table of Contents</strong></p><p>Introduction: Why I Started Learning Python</p><p>From Agriculture to Python</p><p>What I Learned During My First Week</p><p>Learning Python by Doing: The Tasks and Assignments I Worked On</p><p>Student Grades System</p><p>Simple Calculator</p><p>Shopping Cart</p><p>Guessing Game</p><p>File Handling</p><p>The Python Concepts I Encountered</p><p>The Assessments: Testing What I Had Learned</p><p>The Challenges I Faced</p><p>What Changed After One Week?</p><p>What I Would Tell Someone Starting Python</p><p>What Comes Next</p><p>Conclusion</p><p><strong>Introduction:</strong> Why I Started Learning Python</p><p>Starting something new can be uncomfortable, especially when it is outside the area you are already familiar with.For me, Python is one of those things.</p><p>My academic background is in agriculture, so programming was not something I had spent a lot of time doing before this programme. I have always been interested in how information can be used to understand problems and make better decisions, but learning how to actually write computer programs was a different experience.</p><p>That was one of the reasons I was excited to begin learning Python through DataraFlow.</p><p>I wanted to understand more than just how to write code. I wanted to understand how programming could eventually help me work with data, automate tasks, analyse information and solve practical problems.</p><p>My first week was therefore less about trying to become a programmer overnight and more about building the foundation.</p><p>And that foundation started with something very simple:</p><p>print(“Hello, World!”)</p><p>It looked almost too simple.</p><p>But as the week progressed, I realised that simple programs were teaching me concepts that would become important later.</p><p><strong>From Agriculture to Python</strong></p><p>One thing I found interesting during this first week was how different programming initially felt from my previous academic experiences. Agriculture deals with practical problems: crops, farmers, soil, production, food security, resources and decision-making. Programming deals with another kind of problem-solving.</p><p>Instead of asking:</p><p>What is affecting this crop?</p><p>I began asking questions such as:</p><p>How can I make the computer perform this calculation?</p><p>How can I tell the computer what to do when a condition changes?</p><p>How can I repeat an operation without writing the same instruction many times?</p><p>How can I store information and retrieve it later?</p><p>These questions helped me see programming differently.</p><p>Python was no longer just a programming language I was trying to learn. It became a way of expressing a solution to a problem in instructions that a computer could understand. That change in perspective was one of the most important things I took away from the first week.</p><p><strong>What I Learned During My First Week</strong></p><p>The first week introduced me to several fundamental Python concepts. Some of them were completely new to me, while others became clearer only after I used them in practical exercises.</p><p>I worked with:</p><p>Variables</p><p>Numbers and strings</p><p>User input</p><p>if, elif, and else</p><p>for loops</p><p>while loops</p><p>Lists</p><p>Tuples</p><p>Dictionaries</p><p>Functions</p><p>Modules and imports</p><p>Comparison operators</p><p>Exception handling</p><p>File handling</p><p>Basic problem-solving</p><p>One thing I quickly discovered was that knowing the meaning of a concept is different from actually using it. For example, I could understand that a loop repeats instructions. But writing a loop to solve an actual problem made the concept much clearer. That is why the practical exercises became one of the most important parts of my first week.</p><p><strong>Learning Python by Doing:</strong> The Tasks and Assignments I Worked On</p><p>The exercises moved from very simple programs to slightly larger problems. I found this approach useful because each task introduced something new while still building on previous concepts.</p><p>1. Student Grades System</p><p>One of the assignments was to create a simple student grading system. The program accepts marks for five subjects, calculates the average and then assigns a grade according to specified conditions.</p><p>What I built</p><p>The basic logic was:</p><p>Collect five marks from the user.</p><p>Add the marks together.</p><p>Calculate the average.</p><p>Use conditional statements to determine the grade.</p><p>Display the average and grade.</p><p><strong>What I learned:</strong></p><p>This assignment helped me understand how several Python concepts can work together.</p><p>I used input() to collect information from the user, converted the input into numbers, performed calculations and then used if, elif and else to make a decision. The important part for me was understanding that the computer does not “know” what grade a student deserves. I have to give it the conditions.</p><p>For example:</p><p>if average &gt;= 80:</p><p>grade = “A”</p><p>elif average &gt;= 60:</p><p>grade = “B”</p><p>The conditions are what tell the computer how to make the decision.</p><p>What this assignment taught me</p><p>The main lesson I took from this exercise was that programming involves breaking a real-world problem into smaller logical steps. Instead of thinking about the entire grading system at once, I could think:</p><p>Input → Calculation → Decision → Output</p><p>That way of thinking became useful in the other exercises.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*SFR8y2y59vREXs1mr0Xh5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*LrS1HK1kEvhOwakABgisUg.png" /><figcaption>My Student Grades System showing the calculation of an average and the corresponding grade.</figcaption></figure><p>2.<strong> Simple Calculator</strong></p><p>The second assignment involved building a basic calculator.</p><p>The user enters two numbers and selects an operation such as addition, subtraction, multiplication or division.</p><p>What I built</p><p>The program accepts:</p><p>First number</p><p>Second number</p><p>Mathematical operation</p><p>It then checks the selected operation and performs the appropriate calculation.</p><p>For example:</p><p>if operation == “+”:</p><p>result = num1 + num2</p><p>elif operation == “-”:</p><p>result = num1 — num2</p><p>What I learned</p><p>This exercise helped me understand conditional logic more practically.</p><p>The computer needs to know:</p><p>If the user chooses +, do addition.</p><p>If the user chooses -, do subtraction.</p><p>If the user chooses /, do division.</p><p>If the user chooses *, multiply.</p><p>This also introduced me to the importance of thinking about what could go wrong. For example, division by zero can cause an error. That made me realise that writing a program is not only about making it work under normal conditions. I also need to think about situations where the user provides an unexpected input.</p><p>What this assignment taught me</p><p>The calculator helped me understand that even a simple application involves several decisions.</p><p>It also made me more comfortable with user input and conditional statements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*oLTWi067uoLqPdlxhlQqmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*peVVMvBMk163O0p9wpOUtw.png" /><figcaption>My first simple calculator, using conditional statements to perform different mathematical operations.</figcaption></figure><p>3.<strong> Shopping Cart</strong></p><p>The Shopping Cart assignment introduced me to dictionaries and loops in a more practical situation. I created a dictionary containing items and their prices and then calculated the total price.</p><p>For example, the structure looked like:</p><p>cart = {</p><p>“Rice”: 15000,</p><p>“Milk”: 3000,</p><p>“Bread”: 2000</p><p>}</p><p>I then used the values in the dictionary to calculate the total.</p><p>What I learned</p><p>This exercise helped me understand the purpose of a dictionary.</p><p>Instead of storing information as unrelated values, I could associate a name with a value.</p><p>For example:</p><p>Rice → 1,500</p><p>Milk → 1,200</p><p>Bread → 1,000</p><p>I also used a for loop to go through the prices and add them together.</p><p>This was useful because it showed me how data structures and loops can work together.</p><p>What this assignment taught me</p><p>Before this exercise, I could understand the definition of a dictionary, but using one in a practical situation made the concept easier to remember.</p><p>I also learned the importance of an accumulator variable:</p><p>total = 0</p><p>The total starts at zero and changes as each price is added.</p><p>That simple idea appears in many programming problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*iOfX6Noqb59R85fSWHMVvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*s-MaQ4XUVsnApUgPuh3Rew.png" /><figcaption>Using a Python dictionary and loop to calculate the total value of items in a shopping cart.</figcaption></figure><p>4. <strong>Guessing Game</strong></p><p>The Guessing Game was one of the more interesting exercises because it introduced randomness and a while loop.</p><p>The program generates a random number between 1 and 20.</p><p>The user then keeps guessing until the correct number is entered.</p><p>The program also tells the user whether the guess is too high or too low.</p><p>What I learned</p><p>I used Python’s random module:</p><p>import random</p><p>Then I generated the secret number using:</p><p>random.randint(1, 20)</p><p>The while loop allowed the program to continue asking for guesses until the correct answer was provided.</p><p>I also used:</p><p>break</p><p>to stop the loop once the correct number was guessed.</p><p>What this assignment taught me</p><p>This was a good example of how different concepts can come together in one small program.</p><p>I was using:</p><p>A module</p><p>Variables</p><p>User input</p><p>Conditional statements</p><p>A loop</p><p>Comparison operators</p><p>break</p><p>The program was still simple, but it felt more like a real interactive application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*60MYTJdlS-f2xjNN47ZdDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*lV2Pc4k0VNoIbQ_RHTcEFw.png" /><figcaption>My Guessing Game using random number generation, conditional statements and a while loop.</figcaption></figure><p>5. <strong>File Handling</strong></p><p>The File Handling assignment was another important step because it showed me that a program can interact with information stored outside the program itself.</p><p>The task involved accepting student names, saving them to a text file and then reading the file to display the names.</p><p>What I built</p><p>The program first collected the names and stored them in a list.</p><p>I then opened a file in write mode and saved the names.</p><p>After that, I opened the file again in read mode and displayed its contents.</p><p>The basic structure was:</p><p>with open(“students.doc”, “w”) as file:</p><p>…</p><p>and later:</p><p>with open(“students.doc”, “r”) as file:</p><p>…</p><p>What I learned</p><p>This introduced me to file modes:</p><p>“w” for writing</p><p>“r” for reading</p><p>I also learned why with open() is useful when working with files.</p><p>The exercise helped me understand that data does not always have to disappear when a program finishes running. It can be saved and accessed again.</p><p>What this assignment taught me</p><p>This assignment changed the way I thought about simple Python programs. A program can receive information, process it and also store the information for future use. That is a basic idea, but I can already see why it becomes important when working with larger datasets and data analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*1dAau4SPgGDhhsqvodktCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*7_tVvPEQPVFhYg9PfEe7Lg.png" /><figcaption>Saving student names to a text file and reading the stored information back into Python</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*iyfAnxFImA9vfU1n_w0tiQ.png" /><figcaption>The result after inputting the names</figcaption></figure><p><strong>The Python Concepts I Encountered</strong></p><p>Beyond the five larger assignments, I also worked through several smaller Python problems and assessments. These exercises helped reinforce the basics.</p><p><strong>Variables and Data Types</strong></p><p>I learned about different types of data in Python, including:</p><p>Integers</p><p>Floats</p><p>Strings</p><p>Booleans</p><p>Lists</p><p>Tuples</p><p>Dictionaries</p><p>I learned that the type of information I am working with affects what I can do with it.</p><p>Lists and Tuples</p><p>I learned that lists and tuples can both store multiple values, but they are not exactly the same.</p><p>A list can be changed after it is created, while a tuple is generally immutable.</p><p>For example:</p><p>my_list = [1, 2, 3]</p><p>my_tuple = (1, 2, 3)</p><p>This helped me understand why Python provides different data structures for different situations.</p><p>Functions</p><p>Functions were another important concept.</p><p>A function allows me to group instructions together so they can be reused.</p><p>For example:</p><p>def calculate(a, b):</p><p>…</p><p>Initially, the idea of functions was not immediately obvious to me. But I began to understand that instead of writing the same instructions repeatedly, I can put them inside a function and call that function whenever I need it.</p><p>That is a much more organised way of writing programs.</p><p>Loops</p><p>I worked with both for and while loops.</p><p>A for loop is useful when I want to go through a sequence or repeat something for a known range.</p><p>A while loop is useful when I want something to continue as long as a particular condition remains true.</p><p>The Guessing Game helped make this difference much clearer to me.</p><p>Modules</p><p>I also learned what a Python module is and how modules can be imported.</p><p>For example:</p><p>import math</p><p>After importing the math module, I can use functions such as:</p><p>math.sqrt(25)</p><p>which gives:</p><p>5.0</p><p>The Guessing Game also gave me practical experience using the random module.</p><p>This showed me that I don’t have to write every useful function from scratch.</p><p>Exception Handling</p><p>I was introduced to handling errors with try and except. For example, division by zero can produce an error. Instead of allowing the program to stop unexpectedly, I can handle the situation:</p><p>try:</p><p>result = number1 / number2</p><p>except ZeroDivisionError:</p><p>print(“You cannot divide by zero.”)</p><p>This introduced me to an important programming idea:</p><p>Good programs should anticipate possible errors.</p><p><strong>The Assessments: Testing What I Had Learned</strong></p><p>The assessments gave me an opportunity to move beyond simply following examples.</p><p>I worked through questions involving:</p><p>Lists and tuples</p><p>The if __name__ == “__main__”: statement</p><p>Swapping variables</p><p>Python data types</p><p>FizzBuzz</p><p>Local and global variables</p><p>Functions that return even numbers</p><p>== and is</p><p>Counting words</p><p>Dictionaries</p><p>Finding the second-largest number</p><p>for and while loops</p><p>Exception handling</p><p>Palindromes</p><p>Python modules and imports</p><p>What I found useful about these assessments was that they forced me to think about why something works.</p><p>For example, understanding the difference between:</p><p>==</p><p>and:</p><p>is</p><p>is not just about memorising two symbols.</p><p>One compares values, while the other is used to check object identity respectively.</p><p>Similarly, the exercise on if __name__ == “__main__”: showed me that Python programs can be organised in a way that allows code to behave differently depending on whether a file is being run directly or imported.</p><p>These were small concepts, but together they gave me a broader understanding of how Python programs are structured.</p><p><strong>The Challenges I Faced</strong></p><p>Learning something new rarely goes perfectly. There were moments during the week when I had to stop and think about what the code was actually doing. One of the concepts I found confusing was the vowel-counting task. The idea seemed straightforward: go through a word or sentence and count the vowels. But I initially had difficulty understanding why I needed something like:</p><p>count = 0</p><p>I eventually understood that count was simply a variable keeping track of how many times the condition had been met. Every time a vowel was found, the counter increased. It was a small idea, but understanding it made loops and counters much clearer.</p><p>Functions were another area where I needed to slow down.</p><p>At first, terms such as parameters, arguments and return values made functions seem more complicated than they actually were. With practice, I began to see a function as a reusable block of instructions that can receive information, perform an operation and return a result.</p><p>Another challenge was simply getting used to thinking like a programmer. Sometimes the problem itself was easy to understand, but converting that idea into a sequence of instructions was harder.</p><p>That taught me something important:</p><p>Understanding the problem comes before writing the code.</p><p>When I rushed directly into writing code, I was more likely to get confused.</p><p>When I first broke the problem into smaller steps, the solution became easier to construct.</p><p><strong>What Changed After One Week?</strong></p><p>One week is not enough time to become an expert programmer. I am not going to pretend that it is. But it was enough time to change the way I look at programming. Before this week, Python was mainly a programming language I knew I needed to learn,but after working through the exercises myself, I started seeing it as a tool for solving problems.</p><p>I also learned that programming is not mainly about memorising hundreds of commands. It is about understanding a problem, breaking it into smaller parts and giving the computer clear instructions.</p><p>For example:</p><p>Problem → Break it down → Write the logic → Code it → Test it → Find errors → Improve it</p><p>That process became more familiar to me throughout the week. I also became more comfortable seeing errors. Instead of immediately thinking that an error means I cannot do something, I am beginning to see it as information about what needs to be corrected. That is an important mindset shift.</p><p><strong>What I Would Tell Someone Starting Python</strong></p><p>If I had to give advice to someone beginning Python today, I would say:</p><p>1. Don’t rush the basics.</p><p>It is tempting to jump straight into advanced topics because they sound more exciting. But variables, conditions, loops, functions and data structures are the foundation for everything that comes later.</p><p>2. Don’t just watch tutorials.</p><p>Writing the code yourself is different from watching someone else write it. The moment you start typing, mistakes will happen. That is part of learning.</p><p>3. Don’t be afraid of errors.</p><p>An error can be frustrating, but it also tells you that something needs attention. Read it, think about what the program was trying to do, then find where your assumption was wrong.</p><p>4. Break problems into smaller pieces.</p><p>A large programming problem can look intimidating. Instead of asking, “How do I solve this entire problem?”, ask:</p><p>What information do I need?</p><p>What calculation do I need?</p><p>What decision does the program need to make?</p><p>What should the output be?</p><p>This makes the problem much easier to approach.</p><p>5. Practice consistently.</p><p>One long study session cannot replace regular practice. Even small programs can help build familiarity with programming logic.</p><p><strong>What Comes Next?</strong></p><p>My first week was only the beginning. There are still many things I need to learn, and I know the difficulty will increase as I progress. The bigger goal is to move from basic Python programming toward working with data, analysis, machine learning and eventually more advanced applications of artificial intelligence.</p><p>What interests me most is the possibility of connecting these technical skills with real-world problems. Coming from an agricultural background, I am particularly interested in how data and technology can eventually be applied to problems involving agriculture, businesses, development and decision-making. But before reaching those advanced areas, I need to build a strong foundation. That is what this first week has given me, “A starting point”.</p><p><strong>My Key Takeaways From Week 1</strong></p><p>If I had to summarise my first week in five points, they would be:</p><p>1. Programming is about problem-solving, not just syntax.</p><p>2. Small programs can teach important concepts.</p><p>3. Making mistakes is part of learning to code.</p><p>4. Understanding the logic behind the code is more important than memorising it.</p><p>5. Consistent practice is more important than trying to learn everything at once.</p><p><strong>Conclusion</strong></p><p>My first week of learning Python was not about writing complicated programs, It was about learning how to think through problems and translate those solutions into code.</p><p>I started with simple instructions such as printing text and taking user input. From there, I worked with conditions, loops, functions, dictionaries, modules, file handling and error handling. Some concepts came easily, Others required me to stop, rethink the problem and try again. That is probably the most valuable lesson I am taking from the week.</p><p>Learning to code is not about getting everything right on the first attempt. It is about understanding why something did not work, correcting it and becoming better through repetition. I am still at the beginning of my Python journey, but I now have a clearer idea of where I am going. From agriculture to data, and from data to Python, this first week has given me a foundation on which I can continue building.</p><p><strong>Week 1 complete. More to learn. More problems to solve.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be3a23ebd491" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/from-agriculture-to-python-what-my-first-week-of-learning-to-code-taught-me-be3a23ebd491">From Agriculture to Python: What My First Week of Learning to Code Taught Me</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>