Back to Courses

Complete AI Mastery Course

Published

A comprehensive 10-module journey from AI foundations to advanced agentic systems and entrepreneurship. Master prompt engineering, automation, coding with AI, and build a future-proof career.

Progress

0%

Pricing & Access

Students pay this to access the course. Leave "Paid course" off for free/enrolled-only access.

CPD Accreditation

Required for CPD — what a learner can do after the course. One outcome per line.

CPD hours (auto-computed)

0 CPD Hours

CPD status

Not submitted

Submitting sends this course for CPD verification. Once approved and the fee is paid, the CPD logo appears on this course's certificates.

Interactive10 min

Debugging and Optimizing Code with AI

Teaches a disciplined debugging workflow, reading tracebacks, and the three families of bugs, then shows how to optimize code and use AI assistants effectively while staying the pilot who verifies every suggestion.

{"contentFormat":"slides.v1","completion":{"requireAllSlides":true,"requireQuiz":true},"slides":[{"kind":"title","eyebrow":"Module 6: Coding for AI + Vibe Coding","title":"Debugging and Optimizing Code with AI","body":"Every programmer spends a large share of time fixing code that doesn't work. AI assistants like Claude, ChatGPT, GitHub Copilot, and Cursor turn debugging into a fast conversation. This lesson teaches a reliable debugging workflow and how AI supercharges it without replacing your own judgment. You'll also learn optimization — making working code faster, cleaner, and cheaper to run — and how to ask an AI to help without blindly accepting its output. The goal is a partnership: you stay the pilot, the AI is your co-pilot.","outcomes":["Read and interpret Python tracebacks effectively","Apply a disciplined debugging workflow with AI assistance","Use AI to refactor and optimize code for readability and performance","Measure performance with timeit and understand Big O notation"],"narration":"Welcome to Module 6. In this lesson, we'll explore how to debug and optimize code with the help of AI. You'll learn practical techniques to fix bugs faster and make your code more efficient, all while staying in control as the pilot."},{"kind":"content","heading":"Reading Errors: Your First Skill","body":"Before using any AI, learn to read a traceback — Python's error report. It looks intimidating but is designed to help you.\n\n

python\nprices = [10, 20, 30]\nprint(prices[5])   # there is no index 5\n
\n\nThis produces:\n\n
\nIndexError: list index out of range\n
\n\nAnalogy: A traceback is like a receipt that shows exactly where your money went wrong. Read the last line first — it names the error type and message. Then look upward to find the file and line number. Ninety percent of beginner bugs are solved by simply reading that final line carefully.","callout":{"variant":"tip","title":"Traceback Reading Tip","text":"Always start with the last line of the traceback. It tells you the error type and a short message. Then trace upward to find the exact line that caused it."},"narration":"Let's start with the most fundamental skill: reading error messages. Python's traceback tells you exactly what went wrong and where. Focus on the last line first."},{"kind":"content","heading":"The Three Families of Bugs","body":"Understanding the type of bug helps you choose the right fix.\n\n- Syntax errors — the code cannot even start (a missing colon, unclosed bracket). Python refuses to run it.\n- Runtime errors — the code starts but crashes partway (dividing by zero, a missing dictionary key).\n- Logic errors — the code runs happily but gives the wrong answer. These are the hardest, because nothing crashes. AI is especially useful here because it reasons about intent, not just syntax.\n\nA disciplined debugging workflow:\n\n1. Reproduce the bug reliably.\n2. Read the traceback's last line.\n3. Isolate — narrow down to the smallest failing piece.\n4. Inspect with a quick print() or a debugger.\n5. Fix, then re-run to confirm.\n\nThe humble print() remains one of the most effective debugging tools ever invented:\n\n
python\ndef average(numbers):\n    print(\"DEBUG got:\", numbers)      # temporary inspection\n    return sum(numbers) / len(numbers)\n\naverage([])   # crashes — the print reveals the input was empty\n
\n\nFor complex bugs, consider using Python's built-in debugger pdb or an IDE debugger (e.g., VS Code's debugger). These let you step through code line by line and inspect variables.","callout":{"variant":"tip","title":"Debugging Tools","text":"For complex bugs, use pdb (Python's built-in debugger) or an IDE debugger. They let you step through code line by line and inspect variables at any point."},"narration":"Bugs come in three flavors: syntax, runtime, and logic. The hardest are logic errors, where code runs but gives wrong answers. A disciplined workflow helps you tackle them systematically. And don't forget print statements — they're still one of the best tools around."},{"kind":"content","heading":"Bringing in AI Effectively","body":"The quality of an AI's help depends entirely on what you give it. A weak prompt gets a weak answer.\n\nWeak: \"My code is broken, fix it.\"\n\nStrong — give the AI three things: the code, the full error, and what you expected to happen.\n\n
\nHere is my Python function and the error it raises.\n[paste code]\n[paste full traceback]\nExpected: return the mean; when the list is empty it should\nreturn 0.0 instead of crashing. Please fix and explain why.\n
\n\nIn Cursor or GitHub Copilot, you can highlight the broken function and use the inline chat (\"Fix this\") so the assistant sees the surrounding file automatically. A robust fixed version:\n\n
python\ndef average(numbers):\n    \"\"\"Return the mean, or 0.0 for an empty list.\"\"\"\n    if not numbers:              # guard against empty input\n        return 0.0\n    return sum(numbers) / len(numbers)\n
","callout":{"variant":"exercise","title":"Try It Yourself","text":"Paste a buggy function into an AI assistant with the full error and your expected behavior. Compare the AI's fix to your own. Notice how a clear prompt leads to a better answer."},"narration":"To get good help from AI, you need to give it good information. Include the code, the error, and what you expected. A clear prompt leads to a clear fix."},{"kind":"content","heading":"Optimization: From Working to Good","body":"Once code works, optimization makes it better. Two common wins:\n\n- Readability — clear names and small functions. AI is excellent at refactoring: \"Rewrite this to be more readable, without changing behaviour.\"\n- Performance — doing the same job with less time or memory. A classic beginner improvement is replacing a slow loop with a vectorised NumPy operation or a built-in.\n\n
python\n# Slow: manual loop\ntotal = 0\nfor x in range(1_000_000):\n    total += x\n\n# Faster and clearer: a built-in\ntotal = sum(range(1_000_000))\n
\n\nAlways measure before optimising. Python's timeit tells you which version is genuinely faster:\n\n
python\nimport timeit\nloop = timeit.timeit(\"s=0\\nfor x in range(10000): s+=x\", number=100)\nbuilt = timeit.timeit(\"sum(range(10000))\", number=100)\nprint(f\"loop: {loop:.4f}s  built-in: {built:.4f}s\")\n
\n\nRule of thumb: correctness first, readability second, speed last — and only where measurement proves it matters.\n\nBig O notation provides a framework for thinking about performance. For example, a loop that scans a list once is O(n), while nested loops are O(n²). Understanding Big O helps you choose the right algorithm before you even write code.","callout":{"variant":"note","title":"Big O Thinking","text":"Big O notation describes how runtime grows with input size. O(n) is linear, O(n²) is quadratic. Choosing an O(n) algorithm over O(n²) can make your code thousands of times faster for large inputs."},"narration":"Optimization is about making working code better. Focus on readability first, then measure performance before optimizing. Big O notation gives you a mental model for efficiency."},{"kind":"content","heading":"Real-World Examples","body":"AI-assisted debugging and optimization work across the globe. Here are three stories:\n\n- A freelance developer in Nairobi, Kenya inherits a messy 200-line script. She pastes it into Claude and asks for a refactor into small, named functions with docstrings. The behaviour stays identical, but the code becomes maintainable for the client who takes over.\n- A data analyst in São Paulo, Brazil has a pandas report that takes three minutes to run. Cursor's assistant spots a loop that rebuilds a table on every iteration and replaces it with a single grouped operation, cutting runtime to two seconds.\n- A student in Jakarta, Indonesia hits a stubborn KeyError. Instead of guessing for an hour, he pastes the traceback and the offending line into ChatGPT with his expected behaviour, learns that an API sometimes omits a field, and adds a safe .get() default — a fix and a lesson at once.\n\nThese examples show that AI can help anywhere, but the human remains the pilot who understands the context and validates the solution.","narration":"Let's see how these techniques work in practice. From Nairobi to São Paulo to Jakarta, developers use AI to debug and optimize code faster, while staying in control."},{"kind":"quiz","heading":"Check Your Understanding","questions":[{"question":"When reading a Python traceback, which part should you look at first?","options":["The first line of the traceback","The last line of the traceback","The middle of the traceback","The file path only"],"questionId":"cmrf73kag002dpd27nc3jz6n1"},{"question":"Which of the following is the best way to ask an AI to debug your code?","options":["\"My code is broken, fix it.\"","\"Here is my code and the error. I expected it to do X. Please fix and explain.\"","\"What is wrong with this code?\"","\"Fix this function.\""],"questionId":"cmrf73kag002epd27hbjb9f5j"},{"question":"What is the recommended order of priorities when optimizing code?","options":["Speed first, then readability, then correctness","Correctness first, then readability, then speed","Readability first, then speed, then correctness","Speed first, then correctness, then readability"],"questionId":"cmrf73kag002fpd27nuyqd20u"}],"narration":"Now let's test your understanding with a quick quiz. These questions cover the key concepts we've discussed.","quizId":"cmk7lli4q002lg4p88110rovb"},{"kind":"summary","heading":"Key Takeaways","takeaways":["Read the last line of a traceback first — it names the error type and message.","Use a disciplined workflow: reproduce, read, isolate, inspect, fix, re-run.","Give AI clear context: code, error, and expected behavior for best results.","Optimize for correctness first, then readability, then speed — and measure before optimizing.","Big O notation helps you think about performance at the algorithm level.","Use debugging tools like print(), pdb, or IDE debuggers for complex bugs."],"narration":"To wrap up, remember these key points. Debugging is a skill you can improve with practice and the right tools. AI is a powerful co-pilot, but you remain the pilot. Keep coding and keep learning!"}]}