Course content

Python

Learn Python from scratch. Master variables, lists, functions, classes, files, and testing through real Kenyan examples.

📚 Beginner ⏱ 50 lessons · ~8h

In simple terms

Before You Write Code, You Need Python

Python is a program that reads your code and runs it. Right now, your computer probably doesn't have it - so we need to install it first.

The good news? Python is completely free and works on Windows, Mac, and Linux.

Think of it like this: Python is like a translator. You write instructions in Python language, and the translator (the Python program) converts them into something your computer understands. Without the translator installed, your computer can't understand you.
  • Go to python.org in your browser
  • Click the big yellow "Download Python" button
  • Run the installer - it's just like installing any other app
  • After installing, you'll be able to run Python code on your computer

Deep dive

Step-by-Step Installation

On Windows

  1. Open your browser and go to python.org
  2. Click Downloads → the latest version downloads automatically
  3. Open the downloaded file (it looks like python-3.x.x-amd64.exe)
  4. VERY IMPORTANT: Check the box that says "Add Python to PATH" at the bottom of the installer - do this before clicking Install
  5. Click Install Now and wait for it to finish
  6. Click Close when done
What is PATH? PATH tells Windows where to find programs. Without checking that box, you can't run Python from the terminal. Don't skip it!

On Mac

  1. Go to python.org → Downloads → macOS
  2. Download the .pkg file and open it
  3. Follow the installer steps - click Continue, Agree, Install
  4. Done! Mac installs are simpler

On Linux (Ubuntu/Debian)

Linux usually already has Python. Open a terminal and check:

python3 --version

If it's not installed:

sudo apt update
sudo apt install python3

Verify Your Installation

After installing, open a terminal (on Windows: press Win+R, type cmd, press Enter) and type:

python --version

On Mac/Linux:

python3 --version

You should see something like Python 3.12.0. If you do - Python is installed and working!

Challenge

Your Task

  1. Install Python on your computer following the steps above
  2. Open a terminal (Command Prompt on Windows, Terminal on Mac/Linux)
  3. Type python --version (or python3 --version on Mac/Linux)
  4. Take note of the version number shown - that's your Python!

If you see an error like "python is not recognized", go back and make sure you checked "Add Python to PATH" during installation. You may need to reinstall.

Summary

What You've Done

  • Python is now installed on your computer
  • You can verify it runs by checking the version in the terminal
  • On Windows: always add Python to PATH during installation
  • Next step: set up a code editor so you can write Python files comfortably

In simple terms

You Need a Good Place to Write Code

You could write Python in Notepad - but that's like trying to cook a meal with no kitchen tools. You can do it, but it's painful.

VS Code (Visual Studio Code) is the most popular code editor in the world. It's free, made by Microsoft, and works on every operating system.

Think of it like this: VS Code is like Microsoft Word, but for writing code instead of essays. It colours your code so you can read it easily, catches typos, and even suggests what to write next.
  • It's free - download from code.visualstudio.com
  • It colours your code (called syntax highlighting) so it's easy to read
  • It shows errors before you even run your code
  • It has a built-in terminal so you don't need to switch windows

Deep dive

Installing VS Code and Setting It Up for Python

Step 1: Download VS Code

  1. Go to code.visualstudio.com
  2. Click the big blue download button - it detects your operating system automatically
  3. Run the installer (on Windows, just keep clicking Next and then Install)
  4. Open VS Code when done

Step 2: Install the Python Extension

VS Code on its own doesn't know about Python. We need to add the Python plugin:

  1. In VS Code, press Ctrl+Shift+X (or Cmd+Shift+X on Mac) to open Extensions
  2. In the search box, type Python
  3. Click the one published by Microsoft (it has millions of downloads)
  4. Click Install
Why do you need this? The Python extension gives VS Code superpowers - it highlights errors in real time, lets you run code with one click, and shows documentation when you hover over a function.

Step 3: Create Your Project Folder

  1. Create a new folder on your Desktop (or Documents) called my-python-projects
  2. In VS Code, click File → Open Folder
  3. Select your new folder
  4. VS Code will now show your folder in the sidebar on the left

Key VS Code Shortcuts to Know

  • Ctrl+` - Open the built-in terminal
  • Ctrl+S - Save your file
  • Ctrl+Shift+P - Command palette (search for any VS Code feature)
  • F5 - Run your Python file

Challenge

Your Task

  1. Download and install VS Code from code.visualstudio.com
  2. Install the Python extension by Microsoft
  3. Create a folder called my-python-projects somewhere on your computer
  4. Open that folder in VS Code
  5. Press Ctrl+` to open the built-in terminal - you should see a command prompt appear at the bottom of VS Code

If the terminal shows your folder path, you're all set up and ready to write your first real Python file!

Summary

What You've Done

  • VS Code is installed - your professional code writing environment
  • The Python extension is installed - VS Code now understands Python
  • You have a project folder ready for your Python files
  • You know how to open the built-in terminal with Ctrl+`
  • Next: write your first .py file and run it!

In simple terms

Time to Write Real Python on Your Computer

So far you've been learning Python in the browser. That's great for practice - but real Python development happens on your computer, in real files.

A Python file is just a text file that ends in .py - like hello.py or calculator.py. You write your code in the file, then run it from the terminal.

Think of it like this: The .py file is your recipe. The Python program is the chef. The terminal is the kitchen. You hand the chef your recipe, and they cook it and show you the result.

Here's the entire process in 3 steps:

  1. Create a file called hello.py
  2. Write print("Hello, World!") in it
  3. Run it from the terminal: python hello.py

Deep dive

Creating and Running Your First Python File

Step 1: Create a New File

  1. Open VS Code with your project folder open
  2. In the sidebar, click the New File icon (a page with a + sign)
  3. Name it hello.py and press Enter
  4. The file opens in the editor

Step 2: Write Your Code

Type this into the file:

print("Hello, World!")
print("My name is Python.")
print("I am ready to learn!")

Press Ctrl+S to save.

Step 3: Run It from the Terminal

  1. Press Ctrl+` to open the terminal inside VS Code
  2. The terminal should already be in your project folder - you'll see the path
  3. Type this and press Enter:
python hello.py

On Mac/Linux, use:

python3 hello.py

You should see:

Hello, World!
My name is Python.
I am ready to learn!
If you get an error: Make sure you saved the file (Ctrl+S) and that you're in the right folder in the terminal. Type ls (Mac/Linux) or dir (Windows) to see what files are in your current folder. If you don't see hello.py, navigate to the right folder.

Navigating Folders in the Terminal

If your terminal isn't in the right folder, use cd (change directory):

cd Desktop/my-python-projects

Then try running your file again.

The Big Picture

From now on, this is how you'll work as a Python developer:

  1. Write code in a .py file in VS Code
  2. Save with Ctrl+S
  3. Run with python filename.py in the terminal
  4. See the output, fix bugs, repeat

Challenge

Your Task

  1. Create a file called about_me.py in your project folder
  2. Write at least 3 print() statements that share facts about yourself - your name, your favourite food, and what you want to build with Python
  3. Save the file
  4. Run it from the terminal: python about_me.py
  5. See your facts printed out!

Bonus: Try adding a 4th line that uses a variable - like name = "Alice" and then print(name).

Summary

What You've Done

  • You created a real Python file (.py) on your computer
  • You ran it from the terminal using python filename.py
  • You now know the complete developer workflow: write → save → run → read output
  • This is exactly how professional Python developers work every day
  • From here, every concept you learn in the browser applies directly to your local files

In simple terms

The Simple Version

Python is a programming language - a way of giving instructions to a computer. What makes Python special is that it reads almost like plain English, so it is easier to learn than most other languages.

  • Python was created by Guido van Rossum and released in 1991
  • It is used by Google, Instagram, Netflix, NASA, and millions of developers worldwide
  • You can use it for websites, games, data analysis, AI, and automation
  • print() is your first command - it displays a message on screen
  • Python runs on Windows, macOS, and Linux without changes to your code
Think of it like this: Among all the programming languages, Python is like Swahili - it was designed to be understood by as many people as possible. Just like Swahili uses simple, clear words that East Africans across many communities can share, Python uses clear, readable commands that programmers around the world can follow without confusion.

Deep dive

What's Really Happening

1. How Python Runs Your Code

Python is an interpreted language. When you run a Python file, an interpreter reads it line by line and executes each instruction immediately - no separate compilation step needed. This makes Python fast to experiment with.

# Python reads this top to bottom
print("Line 1 runs first")
print("Line 2 runs second")
print("Line 3 runs third")

2. Dynamic Typing

You never declare what type a variable is - Python figures it out automatically. The same variable can hold a number, then a string, then a list.

x = 42          # x is an integer
x = "Nairobi"   # now x is a string
x = [1, 2, 3]   # now x is a list
print(type(x))  # <class 'list'>

3. The Zen of Python

Python has a guiding philosophy: Beautiful is better than ugly. Simple is better than complex. Readability counts. This shapes how Python code is written - clean and clear over clever and compact.

Key Concept: Run import this in Python to read the full Zen of Python - nineteen guiding principles written by Tim Peters that explain why Python looks and feels the way it does.

Try It Yourself

Try it
Output

Challenge

Challenge

Use the editor below to write a Python program that:

  1. Prints your name
  2. Prints the city you live in
  3. Prints the result of 5 + 3

Hint: Use print() for each line. Text must be in quotes, numbers don't need quotes.

Summary

Summary

  • Python is a popular, beginner-friendly programming language
  • It's used for web development, data science, AI, and automation
  • Python code reads almost like English
  • print() displays output to the screen
  • Comments start with # and are ignored by Python
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Every programmer's first program prints "Hello World". In Python, this is just one line. The print() function displays whatever you put inside the parentheses - text, numbers, or calculations.

  • print("Hello") displays text to the screen
  • Text (called a string) must go inside quotes - single ' or double " both work
  • Numbers and maths go without quotes: print(5 + 3)
  • Python runs your code from top to bottom, one line at a time
  • If Python shows an error, read it carefully - it tells you exactly which line and what went wrong
Think of it like this: print() is like a school announcer reading out a message on the PA system. You write the message, and Python reads it aloud to the screen. Whatever you put inside the brackets is what gets announced.

Deep dive

What's Really Happening

1. How the Python Interpreter Works

When you run a Python file, the interpreter reads it line by line. Each print() call sends text to standard output (stdout) - the terminal or console. The function accepts any number of arguments separated by commas.

print("Hello Python world!")
print('Single quotes work too')
print("Name:", "Amina", "Age:", 16)  # prints with spaces between
print(10 + 5)       # prints 15
print(2 ** 8)       # prints 256 (2 to the power of 8)

2. Reading Error Messages

Python error messages always tell you the file name, line number, and error type. Learning to read them is a core skill.

# This causes a SyntaxError (missing closing quote):
print("Hello)

# This causes a NameError (variable doesn't exist):
print(message)

# This works:
print("Hello")   # correct

3. print() Options

print() has optional parameters: sep changes the separator between items, end changes what prints at the end (default is a new line).

print("Kenya", "Uganda", "Tanzania", sep=" | ")
# Kenya | Uganda | Tanzania

print("Loading", end="...")
print("Done")
# Loading...Done
Key Concept: Every programmer makes mistakes. An error message is Python helping you, not punishing you. The line number in the error tells you exactly where to look.

Try It Yourself

Try it
Output

Challenge

Challenge

Write a program that prints four lines:

  1. Your full name
  2. Your favourite subject in school
  3. The result of 100 divided by 4
  4. The message: "Python is awesome!"

Summary

Summary

  • print() displays text and values to the screen
  • Strings can use single or double quotes
  • Python runs code top to bottom, line by line
  • Error messages tell you the line number and type of error
  • Every programmer makes mistakes — reading errors is a skill
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A variable is a name that stores a value. You create one by writing a name, an equals sign, and the value. Python remembers that value so you can use it later.

  • Use = to assign a value: name = "Amina"
  • Use the variable by writing its name: print(name)
  • You can change the value anytime by reassigning: name = "Wanjiru"
  • Names should be lowercase with underscores: student_name, total_score
  • No spaces, no special characters - just letters, numbers, and underscores
Think of it like this: A variable is like a labeled container at a market stall. You have a tin labeled "Sugar", one labeled "Flour", and one labeled "Salt". You can look inside any tin by calling its name, put more in, or swap the contents. The label is the variable name; what's inside is the value.

Deep dive

What's Really Happening

1. Variables are Labels, Not Boxes

In Python, a variable is actually a label pointing to an object in memory. When you write x = 42, Python creates an integer object with value 42 somewhere in memory, then makes the label x point to it. Reassigning x = "hello" makes the label point to a new string object - the old integer is unchanged.

x = 42
y = x        # y points to the SAME object as x
print(x, y)  # 42 42

x = 99       # x now points to a new object
print(x, y)  # 99 42  -  y still points to the original 42

2. Dynamic Typing and type()

Python is dynamically typed - the variable holds whatever type you assign. Use type() to check.

score = 100
print(type(score))   # <class 'int'>

score = 98.5
print(type(score))   # <class 'float'>

score = "A+"
print(type(score))   # <class 'str'>

3. Naming Rules (PEP 8)

Python's style guide (PEP 8) says variable names should be snake_case - all lowercase, words separated by underscores. Avoid single-letter names except in loops. Never use reserved words like print, list, for as variable names.

Key Concept: Use descriptive names. student_name is better than sn. total_marks is better than t. Your code should read like a sentence.

Try It Yourself

Try it
Output

Challenge

Challenge

Create variables for a student profile and print a message using them:

  1. Create a variable name with your name
  2. Create a variable age with your age
  3. Create a variable city with your city
  4. Print: "My name is [name], I am [age] years old, from [city]"

Hint: You can combine variables with commas in print: print("Hello", name)

Summary

Summary

  • Variables store values — use = to assign
  • Variable names: lowercase, underscores, no spaces
  • You can reassign a variable to a new value anytime
  • Python is dynamically typed — no need to declare types
  • Use descriptive names: student_name not sn
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A string is any text in Python - wrapped in single or double quotes. Strings have built-in tools called methods that let you transform them: change case, remove spaces, replace words, and more.

  • .upper() makes all letters capital: "nairobi".upper() → "NAIROBI"
  • .lower() makes all letters small: "AMINA".lower() → "amina"
  • .title() capitalises first letter of each word: "john otieno".title() → "John Otieno"
  • .strip() removes extra spaces from both ends
  • Join strings with +: "Hello" + " " + "Amina" → "Hello Amina"
Think of it like this: A string is like an SMS message. It is just text - you can write anything in it. String methods are like phone features: auto-correct changes the case, trim removes extra spaces, and replace swaps one word for another. The message itself doesn't change until you tell it to.

Deep dive

What's Really Happening

1. Strings are Immutable

In Python, strings cannot be changed in place - they are immutable. When you call .upper(), Python creates a new string object and returns it. The original is unchanged.

name = "amina"
upper_name = name.upper()
print(name)        # still "amina"  -  unchanged
print(upper_name)  # "AMINA"  -  new string

2. Escape Characters and Multi-line Strings

Use \n for a new line, \t for a tab, and \' or \" to include quotes inside strings.

print("Line 1\nLine 2\nLine 3")

# Multi-line strings use triple quotes
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you!"""
print(poem)

3. Useful String Methods

county = "  nairobi county  "
print(county.strip())         # "nairobi county"
print(county.strip().title()) # "Nairobi County"
print(county.replace("nairobi", "mombasa").strip())

sentence = "The bus is fast"
print(sentence.startswith("The"))  # True
print(sentence.count("t"))         # 2
print(len(sentence))               # 18
Key Concept: String methods always return a new string - they do not modify the original. Chain them together: " hello ".strip().title() gives "Hello".

Try It Yourself

Try it
Output

Challenge

Challenge

Famous Kenyan athletes have names. Let's work with them:

  1. Store "eliud kipchoge" in a variable athlete
  2. Print the name with title() format
  3. Print the name in ALL CAPS
  4. Print: "The great athlete is: [name]" using concatenation with +

Summary

Summary

  • Strings are text wrapped in single or double quotes
  • title() capitalises first letter of each word
  • upper() / lower() change the whole string's case
  • + joins strings together (concatenation)
  • \n = newline, \t = tab inside strings
  • strip() removes whitespace from both ends
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

An f-string lets you put variable values directly inside a string. Put f before the opening quote, then use curly braces {} around any variable or expression you want to insert.

  • Put f before the quote: f"Hello, {name}!"
  • Anything inside {} is evaluated and inserted into the string
  • You can do maths inside: f"Total: {price * qty}"
  • You can call methods: f"Hello, {name.title()}!"
  • Much cleaner than joining strings with +
Think of it like this: An f-string is like a letter template. Imagine a letter that says "Dear [Name], your balance is [Amount]." You fill in the blanks with real values each time you send it. The {} curly braces are the blank spaces waiting to be filled.

Deep dive

What's Really Happening

1. f-strings vs Older Methods

Python has three ways to format strings. f-strings (introduced in Python 3.6) are the clearest and fastest.

name = "Otieno"
score = 94.5

# Old way  -  hard to read
print("Name: " + name + ", Score: " + str(score))

# .format()  -  better but verbose
print("Name: {}, Score: {}".format(name, score))

# f-string  -  cleanest
print(f"Name: {name}, Score: {score}")

2. Expressions and Formatting Inside {}

You can put any Python expression inside the curly braces - not just variable names.

price = 250
qty = 3
print(f"Total: KSh {price * qty}")          # KSh 750
print(f"Name: {'amina'.title()}")            # Name: Amina
print(f"Pi approx: {22/7:.2f}")             # Pi approx: 3.14
print(f"Padded: {score:>10}")               # right-aligned in 10 chars

3. Multi-line f-strings

name = "Wanjiku"
grade = "Form 3"
school = "Starehe Girls"

report = f"""
Student: {name}
Grade: {grade}
School: {school}
Average: {87.3:.1f}%
"""
print(report)
Key Concept: The : inside {} adds formatting. {value:.2f} rounds to 2 decimal places. {value:,} adds comma separators to large numbers: f"{1000000:,}" → "1,000,000".

Try It Yourself

Try it
Output

Challenge

Challenge

Create a market receipt using f-strings:

  1. Variables: item = "unga", price = 120, qty = 2
  2. Print: "Item: Unga" (use title() on item)
  3. Print: "Price per bag: KSh 120"
  4. Print: "Total cost: KSh 240" (calculate qty * price inside the f-string)

Summary

Summary

  • f-strings embed variables directly in strings using f"...{variable}..."
  • Any Python expression can go inside {}
  • Use :.2f to format floats to 2 decimal places
  • f-strings are cleaner than + concatenation
  • Available in Python 3.6 and later
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Python works with two main types of numbers: integers (whole numbers) and floats (numbers with a decimal point). Python can also do all the maths you'd expect from a calculator - and more.

  • Integers: 10, -5, 1000 - whole numbers, no decimal
  • Floats: 3.14, -0.5, 99.9 - numbers with decimals
  • + add, - subtract, * multiply, / divide
  • ** means "to the power of": 2**10 = 1024
  • // floor division (no remainder): 17 // 5 = 3
  • % modulo (the remainder): 17 % 5 = 2
Think of it like this: Python is like a very smart shop calculator. An integer is like counting full bags of maize - you can't have half a bag. A float is like money - you can have KSh 99.50. The % operator is like dividing students into groups and asking "how many are left over?"

Deep dive

What's Really Happening

1. Integer vs Float Arithmetic

Division with / always returns a float. Use // for integer division and % for the remainder.

print(10 / 3)    # 3.3333... (float)
print(10 // 3)   # 3 (integer, floor division)
print(10 % 3)    # 1 (remainder)
print(10 ** 3)   # 1000 (power)

# Mixing int and float always gives float
print(1 + 2.0)   # 3.0

2. Float Precision Issues

Floats are stored in binary, which causes tiny rounding errors for some values. This is a known issue in all programming languages.

print(0.1 + 0.2)  # 0.30000000000000004 (not exactly 0.3!)

# Fix with round()
print(round(0.1 + 0.2, 2))  # 0.3

3. Useful Number Features

# Underscores make large numbers readable
population = 54_000_000   # same as 54000000
distance = 384_400        # km to the moon

# Multiple assignment
x = y = z = 0

# Constants (by convention, use ALL_CAPS)
MAX_SPEED = 120
PI = 3.14159
Key Concept: Use int() and float() to convert between types: int("42") → 42, float("3.14") → 3.14. This is essential when reading user input, which is always a string.

Try It Yourself

Try it
Output

Challenge

Challenge

Calculate a mobile data bill:

  1. Daily data cost: KSh 20, used for 30 days
  2. Calculate and print the monthly cost
  3. Add 16% VAT: multiply by 1.16
  4. Print: "Monthly bill with VAT: KSh [amount]" (use f-string, round to 2 decimal places)

Summary

Summary

  • Integers are whole numbers; floats have decimal points
  • Operators: + - * / // % **
  • ** is exponent: 3**2 = 9
  • // is floor division; % is modulo (remainder)
  • Use underscores in large numbers: 1_000_000
  • int() and float() convert between types
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A comment is a note you leave in your code for yourself or other programmers. Python ignores comments completely - they exist for humans, not the computer.

  • Start a comment with #: # This is a comment
  • Everything after # on that line is ignored by Python
  • You can put a comment at the end of a line of code
  • Comments explain why your code does something, not what it does
  • Good comments save time - you'll thank yourself later when reading old code
Think of it like this: Comments are like the notes a teacher writes in the margin of a student's book. The student reads the lesson (the code), but the teacher's margin notes (comments) help explain tricky parts. The notes don't change the lesson - they just help you understand it better.

Deep dive

What's Really Happening

1. What Python Does with Comments

The Python interpreter completely skips any line starting with #. Comments have zero performance impact - they don't slow your program down at all. They are stripped out before code is processed.

# Calculate the total cost for a school trip
students = 45
cost_per_student = 500   # KSh per student
total = students * cost_per_student
print(f"Trip cost: KSh {total:,}")  # KSh 22,500

2. When to Write Comments

Write comments to explain why, not what. The code already shows what it does. Comments add context that the code cannot show on its own.

# BAD comment  -  just repeats what the code says:
x = x + 1  # add 1 to x

# GOOD comment  -  explains why:
x = x + 1  # offset by 1 because index starts at 0

# GOOD comment  -  explains a non-obvious choice:
# Using // instead of / to avoid float rounding errors
pages = total_chars // 500

3. Temporarily Disabling Code

You can comment out lines to disable them while testing. This is faster than deleting and retyping.

name = "Amina"
# name = "Wanjiru"   # disabled for now  -  testing with Amina
print(name)
Key Concept: The Zen of Python says "Readability counts." Well-commented code is a sign of a thoughtful programmer. Comment for your future self - you will not remember why you wrote something three months from now.

Try It Yourself

Try it
Output

Challenge

Challenge

Add meaningful comments to this code and fix the variable names to follow Python conventions:

x = 54000000
y = 580000
z = x - y
print(z)

Rename: x → kenya_population, y → nairobi_population, z → rural_population. Add a comment above each variable explaining what it represents.

Summary

Summary

  • Comments start with # — Python ignores them
  • Write comments to explain why, not just what
  • Good variable names reduce the need for comments
  • The Zen of Python: simplicity, readability, beauty
  • PEP 8 is Python's official style guide
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A list stores multiple values in one variable, in a specific order. Use square brackets and separate items with commas.

  • Create a list: counties = ["Nairobi", "Mombasa", "Kisumu"]
  • Access items by index - counting starts at 0: counties[0] → "Nairobi"
  • Use -1 to get the last item: counties[-1] → "Kisumu"
  • Get the length with len(counties)
  • Lists can hold strings, numbers, or a mix of both
Think of it like this: A list is like a shopping list at the corner shop. You write items one after another: maize flour, cooking oil, sugar, salt. Each item has a position - flour is item number 1, oil is item 2. In Python, item 1 is at index 0. You can read any item by its position, and you know how many items are on the list.

Deep dive

What's Really Happening

1. Lists are Ordered and Mutable

Unlike strings, lists are mutable - you can change individual items directly. The order you put items in is preserved.

fruits = ["mango", "avocado", "passion fruit", "guava"]
print(fruits[0])   # mango
print(fruits[-1])  # guava
print(fruits[1:3]) # ['avocado', 'passion fruit']

fruits[0] = "papaya"  # change first item
print(fruits)  # ['papaya', 'avocado', 'passion fruit', 'guava']

2. Lists Can Hold Any Type

# Mixed list
student = ["Amina Osei", 16, "Form 3", True, 87.5]

# List of lists (2D)
teams = [
    ["Otieno", "Wanjiru", "Mwangi"],
    ["Aisha", "Baraka", "Njeri"],
]
print(teams[0][1])  # "Wanjiru"

3. Checking and Searching

counties = ["Nairobi", "Mombasa", "Kisumu", "Nakuru"]

# Check membership
print("Kisumu" in counties)     # True
print("Eldoret" in counties)    # False
print("Eldoret" not in counties) # True

# Find position
print(counties.index("Mombasa"))  # 1
Key Concept: Index 0 is the first item - this trips up every beginner at least once. list[-1] always gives you the last item, no matter how long the list is.

Try It Yourself

Try it
Output

Challenge

Challenge

Create a list of 5 Kenyan counties and:

  1. Print the first county
  2. Print the last county using negative indexing
  3. Print: "I want to visit [third county]!" using an f-string
  4. Print how many counties are in your list

Summary

Summary

  • Lists use square brackets: ['item1', 'item2']
  • Indexing starts at 0: list[0] is the first item
  • Negative indexing: list[-1] is the last item
  • len(list) returns the number of items
  • Lists are mutable — they can be changed after creation
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Lists are mutable - you can add, change, and remove items after the list is created. Python gives you several methods to do this.

  • .append(item) - adds one item to the end of the list
  • .insert(index, item) - adds an item at a specific position
  • .remove(item) - removes the first occurrence of a value
  • .pop() - removes and returns the last item (or item at given index)
  • del list[index] - deletes an item by position
Think of it like this: Modifying a list is like managing a guest list for a community event. You start with some names, then someone calls to say they're coming - you .append() their name. A guest cancels - you .remove() their name. Someone VIP arrives last minute - you .insert() them at the top. The list keeps updating as things change.

Deep dive

What's Really Happening

1. append() vs insert() vs extend()

guests = ["Amina", "Otieno", "Wanjiru"]

guests.append("Baraka")          # adds to end
guests.insert(0, "Chairperson")  # adds at index 0
guests.extend(["Njeri", "Musa"]) # adds multiple items
print(guests)
# ['Chairperson', 'Amina', 'Otieno', 'Wanjiru', 'Baraka', 'Njeri', 'Musa']

2. Removing Items - Three Ways

items = ["rice", "beans", "pasta", "beans", "bread"]

items.remove("beans")   # removes FIRST "beans" only
print(items)  # ['rice', 'pasta', 'beans', 'bread']

last = items.pop()      # removes and RETURNS last item
print(last)   # bread
print(items)  # ['rice', 'pasta', 'beans']

del items[0]            # deletes by index, returns nothing
print(items)  # ['pasta', 'beans']

3. Clearing and Copying

original = ["Nairobi", "Mombasa", "Kisumu"]
copy = original.copy()   # safe copy

original.clear()         # empties the list
print(original)  # []
print(copy)      # ['Nairobi', 'Mombasa', 'Kisumu']  -  unchanged
Key Concept: .remove() raises a ValueError if the item is not in the list. Check first with if item in list: to avoid crashes.

Try It Yourself

Try it
Output

Challenge

Challenge

Manage a guest list for a Kenyan party:

  1. Start with: ['Amina', 'Brian', 'Cynthia', 'David']
  2. Brian can no longer come — remove him
  3. A new guest 'Faith' is invited — add her to the end
  4. The host's parents arrive as VIPs — insert 'Mama' and 'Baba' at position 0
  5. Print the final guest list

Summary

Summary

  • append(item) — adds to end
  • insert(i, item) — adds at index i
  • del list[i] — removes item at index i
  • pop() — removes and returns last item; pop(i) removes at index i
  • remove(value) — removes first occurrence of value
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Python gives you ways to sort and organise your lists - alphabetically, numerically, in reverse, or without changing the original order.

  • .sort() - permanently sorts the list (changes it in place)
  • sorted(list) - returns a sorted copy, original unchanged
  • .reverse() - reverses the current order permanently
  • sorted(list, reverse=True) - sorted in descending order
  • len(list) - tells you how many items the list has
Think of it like this: Sorting a list is like arranging books on a shelf. .sort() rearranges the books on the actual shelf - the shelf changes. sorted() is like making a photocopy of the shelf arrangement and organising the copy - the real shelf stays the same. .reverse() is like turning the whole shelf around to read from right to left.

Deep dive

What's Really Happening

1. sort() Modifies In Place, sorted() Does Not

rivers = ["Tana", "Athi", "Nile", "Mara", "Galana"]

# sorted()  -  original unchanged
sorted_rivers = sorted(rivers)
print(rivers)         # ['Tana', 'Athi', 'Nile', 'Mara', 'Galana']
print(sorted_rivers)  # ['Athi', 'Galana', 'Mara', 'Nile', 'Tana']

# sort()  -  changes original permanently
rivers.sort()
print(rivers)  # ['Athi', 'Galana', 'Mara', 'Nile', 'Tana']

# Descending order
rivers.sort(reverse=True)
print(rivers)  # ['Tana', 'Nile', 'Mara', 'Galana', 'Athi']

2. Reverse vs Sort Descending

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

numbers.reverse()       # reverses current order  -  NOT sorted
print(numbers)  # [6, 2, 9, 5, 1, 4, 1, 3]

numbers.sort(reverse=True)  # sorts high to low
print(numbers)  # [9, 6, 5, 4, 3, 2, 1, 1]

3. Sorting with a Custom Key

names = ["wanjiru", "OTIENO", "Amina", "baraka"]

# Sort ignoring case
names.sort(key=str.lower)
print(names)  # ['Amina', 'baraka', 'OTIENO', 'wanjiru']

# Sort strings by length
words = ["python", "coding", "loops", "data"]
words.sort(key=len)
print(words)  # ['coding', 'data', 'loops', 'python']
Key Concept: .sort() returns None - do not write my_list = my_list.sort() because that would set your list to None. Call .sort() on its own line.

Try It Yourself

Try it
Output

Challenge

Challenge

You have a list of Kenyan football teams:

teams = ['Gor Mahia', 'AFC Leopards', 'Tusker FC', 'KCB FC', 'Bandari FC']
  1. Print the teams in alphabetical order (without changing the list)
  2. Print the teams in reverse alphabetical order
  3. Print the original list to confirm it's unchanged
  4. Now sort the list permanently and print it

Summary

Summary

  • sort() — permanently sorts a list
  • sort(reverse=True) — sorts in descending order
  • sorted(list) — returns sorted copy, original unchanged
  • reverse() — permanently reverses a list
  • len(list) — returns item count
  • min(), max(), sum() — work on number lists
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A for loop runs a block of code once for each item in a list (or any collection). Instead of writing the same code ten times, you write it once and let Python repeat it.

  • The loop variable (e.g. county) takes the value of each item one at a time
  • The indented code block runs once per item
  • After the loop finishes, code continues from the next non-indented line
  • You can name the loop variable anything - choose something meaningful
  • Always put a colon : after the for line
Think of it like this: A for loop is like a teacher doing roll call. The teacher has a class list. For each name on the list, the teacher calls it out and marks it. When the list is done, roll call is over. Python does the same - for each item in your list, it runs your code, then moves to the next item until all are done.

Deep dive

What's Really Happening

1. The Loop Variable and Indentation

Python uses indentation (4 spaces or 1 tab) to define what is inside the loop. Any line indented after the for line is part of the loop. The first non-indented line ends the loop.

counties = ["Nairobi", "Mombasa", "Kisumu", "Nakuru"]

for county in counties:
    print(f"Processing: {county}")         # inside loop
    print(f"  Length: {len(county)} chars") # also inside loop

print("Loop done!")  # outside loop  -  runs once at the end

2. Doing Work Inside the Loop

scores = [72, 85, 91, 60, 78, 95]
total = 0

for score in scores:
    total += score   # same as: total = total + score

average = total / len(scores)
print(f"Average score: {average:.1f}")  # 80.2

3. Nested for Loops

subjects = ["Maths", "English"]
terms = ["Term 1", "Term 2", "Term 3"]

for subject in subjects:
    for term in terms:
        print(f"{subject}  -  {term}")
Key Concept: The loop variable name is yours to choose. for county in counties is readable because "county" is singular of "counties". This pattern - singular loop variable, plural collection - makes your code read naturally.

Try It Yourself

Try it
Output

Challenge

Challenge

Create a list of 5 Kenyan foods and loop through them:

  1. Print each food with the message: "[Food] is delicious!"
  2. After the loop, print: "Those are all great Kenyan foods!"
  3. Try using .title() on each food name

Example foods: ugali, chapati, nyama choma, mandazi, pilau

Summary

Summary

  • for item in list: loops through every item
  • The loop body must be indented (4 spaces)
  • Code after the loop (not indented) runs once
  • Choose meaningful loop variable names: for student in students
  • Python repeats the loop body once per item, no matter the list size
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

range() generates a sequence of numbers without you having to type them all out. It is perfect for counting loops and building numerical lists.

  • range(5) → 0, 1, 2, 3, 4 (stops before 5)
  • range(1, 6) → 1, 2, 3, 4, 5
  • range(2, 11, 2) → 2, 4, 6, 8, 10 (step of 2)
  • list(range(5)) converts it to a real list
  • min(), max(), sum() work on numerical lists instantly
Think of it like this: range() is like a ruler. A ruler from 0 to 30 doesn't write the numbers on paper - it just has markings. When you use the ruler, you read each mark one by one. range() gives Python a ruler with number markings, and the for loop reads each mark.

Deep dive

What's Really Happening

1. range() is Lazy - It Doesn't Store All Numbers

range(1000000) does NOT create a list of a million numbers in memory. It creates a range object that generates each number on demand. This is very efficient.

r = range(1, 11)
print(type(r))   # <class 'range'>
print(list(r))   # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Very efficient  -  no memory used for the million numbers:
total = sum(range(1, 1_000_001))
print(total)  # 500000500000

2. Building Lists with range()

# Squares of 1 to 10
squares = [x**2 for x in range(1, 11)]
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Odd numbers
odds = list(range(1, 20, 2))
print(odds)  # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

# Countdown
countdown = list(range(10, 0, -1))
print(countdown)  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

3. Statistics on Lists

scores = [72, 85, 91, 60, 78, 95, 88, 73]
print(f"Lowest:  {min(scores)}")     # 60
print(f"Highest: {max(scores)}")     # 95
print(f"Total:   {sum(scores)}")     # 642
print(f"Average: {sum(scores)/len(scores):.1f}")  # 80.3
Key Concept: [expression for item in range(...)] is called a list comprehension - a compact, Pythonic way to build lists. It replaces 3–4 lines of append-loop code with one readable line.

Try It Yourself

Try it
Output

Challenge

Challenge

Use range() to:

  1. Print all odd numbers from 1 to 20 (hint: range(1, 21, 2))
  2. Create a list of the first 10 multiples of 5
  3. Calculate and print the sum of numbers from 1 to 100

Summary

Summary

  • range(stop) generates 0 to stop-1
  • range(start, stop) generates start to stop-1
  • range(start, stop, step) skips by step
  • list(range(...)) converts range to a list
  • min(), max(), sum() work on number lists
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A slice extracts a portion of a list. A tuple is like a list that can never be changed after it is created.

  • list[1:4] - items at indexes 1, 2, 3 (end not included)
  • list[:3] - first 3 items
  • list[2:] - from index 2 to the end
  • list[-3:] - last 3 items
  • list[:] - a full copy of the list
  • Tuples use (): point = (10, 20) - cannot be changed
Think of it like this: Slicing a list is like cutting a loaf of bread into slices. You decide where to start cutting and where to stop - and you get just that piece. A tuple is like a printed bus ticket - the destination, date, and price are fixed and cannot be erased or changed. A list is like a whiteboard you can edit anytime.

Deep dive

What's Really Happening

1. Slice Notation: start:stop:step

players = ["Otieno", "Amina", "Wanjiru", "Baraka", "Njeri", "Musa"]

print(players[1:4])    # ['Amina', 'Wanjiru', 'Baraka']
print(players[:3])     # ['Otieno', 'Amina', 'Wanjiru']
print(players[3:])     # ['Baraka', 'Njeri', 'Musa']
print(players[-2:])    # ['Njeri', 'Musa']
print(players[::2])    # every second: ['Otieno', 'Wanjiru', 'Njeri']
print(players[::-1])   # reversed: ['Musa', 'Njeri', 'Baraka', 'Wanjiru', 'Amina', 'Otieno']

2. Copying Lists with [:]

team_a = ["Otieno", "Amina", "Wanjiru"]
team_b = team_a[:]      # TRUE copy  -  independent

team_b.append("Baraka")
print(team_a)  # ['Otieno', 'Amina', 'Wanjiru']  -  unchanged
print(team_b)  # ['Otieno', 'Amina', 'Wanjiru', 'Baraka']

# Without [:], both variables point to the same list:
team_c = team_a         # NOT a copy  -  same list!
team_c.append("Oops")
print(team_a)  # ['Otieno', 'Amina', 'Wanjiru', 'Oops']  -  changed!

3. Tuples - When and Why

coordinates = (-1.286389, 36.817223)  # Nairobi GPS  -  never changes
print(coordinates[0])   # -1.286389

# Tuple unpacking
lat, lng = coordinates
print(f"Lat: {lat}, Lng: {lng}")

# Trying to change a tuple raises TypeError:
# coordinates[0] = 0  # TypeError: 'tuple' object does not support item assignment
Key Concept: Use a tuple when data should never change - GPS coordinates, RGB colours, days of the week. Use a list when data will change - a shopping cart, a leaderboard, a to-do list.

Try It Yourself

Try it
Output

Challenge

Challenge

  1. Create a list of 8 Kenyan counties
  2. Print the first 3 counties
  3. Print the last 3 counties
  4. Print the middle 4 counties (indexes 2-5)
  5. Copy the list and add 2 more counties to the copy only
  6. Confirm the original list is unchanged

Summary

Summary

  • list[0:3] — items at indexes 0, 1, 2
  • list[:3] — first 3; list[2:] — from index 2 to end
  • list[-3:] — last 3 items
  • list[:] — a copy of the entire list
  • Tuples use () and are immutable — cannot be changed
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

An if statement runs code only when a condition is true. This is how programs make decisions.

  • if condition: - runs the block if condition is True
  • else: - runs when the if condition is False
  • Comparison operators: == equal, != not equal, > greater, < less, >=, <=
  • Combine conditions: and, or, not
  • in checks membership: "Nairobi" in cities
Think of it like this: An if statement is like a bouncer at the entrance of a club. The bouncer checks a condition: "Are you over 18?" If yes - you get in (the if block runs). If no - you are turned away (the else block runs). The decision is made every time someone tries to enter.

Deep dive

What's Really Happening

1. Boolean Expressions and Truthiness

Every condition evaluates to either True or False. Python also treats some values as "truthy" or "falsy" automatically.

# Falsy values  -  treated as False in conditions:
# False, None, 0, 0.0, "", [], {}, ()

name = ""
if name:
    print("Name provided")
else:
    print("No name given")  # this runs  -  empty string is falsy

2. Comparison Operators

age = 16
grade = "A"
county = "Nairobi"

print(age >= 18)            # False
print(grade == "A")         # True
print(grade != "F")         # True
print(county in ["Nairobi", "Mombasa"])  # True
print(age >= 13 and age < 18)  # True  -  teenager

3. if/else and Short-Circuit Evaluation

score = 78

if score >= 90:
    print("Distinction")
else:
    print("Pass")   # this runs

# Combining: and / or
username = "admin"
password = "1234"

if username == "admin" and password == "1234":
    print("Login successful")
else:
    print("Invalid credentials")
Key Concept: Use == to compare (is it equal?), not = (which assigns). if x = 5: is a syntax error. if x == 5: is a comparison.

Try It Yourself

Try it
Output

Challenge

Challenge

Write a program that checks KCSE grades:

  1. Variable: grade = 75
  2. If grade >= 80: print "A - Excellent!"
  3. If grade >= 60: print "B - Good"
  4. If grade >= 40: print "C - Average"
  5. Otherwise: print "D - Needs improvement"
  6. Also check if the student passed (>= 40) and print accordingly

Summary

Summary

  • if condition: runs block if condition is True
  • else: runs if the condition is False
  • Comparison: == != > < >= <=
  • and / or — combine conditions
  • in / not in — check list membership
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

elif (else if) lets you check multiple conditions one after another. Python checks each condition in order and runs the first one that is True. If none match, else runs.

  • Python checks conditions top to bottom - first match wins
  • You can have as many elif blocks as you need
  • else is optional - it catches everything that didn't match
  • Only ONE block ever runs - the rest are skipped
  • Order matters: put more specific conditions before general ones
Think of it like this: elif is like a traffic light. Red means stop (first condition). Yellow means slow down (second condition). Green means go (third condition). Only one light is on at a time, and the lights are checked in order. Python's if-elif-else works exactly the same way.

Deep dive

What's Really Happening

1. Grading Example

def get_grade(score):
    if score >= 80:
        return "A"
    elif score >= 65:
        return "B"
    elif score >= 50:
        return "C"
    elif score >= 40:
        return "D"
    else:
        return "F"

print(get_grade(85))  # A
print(get_grade(62))  # B
print(get_grade(30))  # F

2. Why Order Matters

# WRONG  -  85 matches the first condition (>= 50) and prints "Pass"
# even though it should print "Distinction"
score = 85
if score >= 50:
    print("Pass")       # runs!  -  wrong
elif score >= 80:
    print("Distinction") # never reached

# CORRECT  -  most specific condition first
if score >= 80:
    print("Distinction")  # runs correctly
elif score >= 50:
    print("Pass")

3. Multiple Independent Conditions

If conditions are independent (not mutually exclusive), use separate if statements instead of elif.

score = 85
county = "Nairobi"

# These are independent  -  use separate if statements
if score >= 80:
    print("Qualifies for national competition")
if county == "Nairobi":
    print("Nairobi regional representative")
Key Concept: elif vs separate if: Use elif when conditions are mutually exclusive (only one can be true). Use separate if statements when conditions are independent and multiple can be true at once.

Try It Yourself

Try it
Output

Challenge

Challenge

Build a Safaricom data bundle selector:

  1. Variable: balance = 150 (KSh)
  2. If balance >= 500: print "Daily Unlimited Bundle - KSh 500"
  3. elif balance >= 100: print "100MB Bundle - KSh 100"
  4. elif balance >= 50: print "50MB Bundle - KSh 50"
  5. else: print "Insufficient balance. Please top up."

Summary

Summary

  • elif tests another condition if previous ones were False
  • Only the first True block runs in an if-elif-else chain
  • You can have many elif blocks
  • else is optional — it catches everything not caught above
  • Use multiple if statements when multiple conditions can be true simultaneously
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A dictionary stores data as key: value pairs. Instead of accessing items by position (like lists), you access them by a meaningful name (the key).

  • Create with curly braces: {"key": value, "key2": value2}
  • Access a value: person["name"]
  • Add or change a value: person["age"] = 25
  • Remove a key: del person["age"]
  • Check if key exists: "name" in person
Think of it like this: A dictionary is like a phone book. In a phone book, each name (key) is paired with a phone number (value). You don't look up by page number - you look up by name. "Amina" → "0712345678". That's exactly how Python dictionaries work.

Deep dive

What's Really Happening

1. Dictionary Operations

student = {
    "name": "Amina Osei",
    "age": 16,
    "grade": "Form 3",
    "school": "Alliance Girls",
}

print(student["name"])        # Amina Osei
print(student.get("score", 0)) # 0  -  safe default if key missing

student["score"] = 87.5       # add new key
student["age"] = 17           # update existing key
del student["grade"]          # remove key

print(len(student))           # 4 key-value pairs

2. Safe Access with .get()

Using student["missing_key"] raises a KeyError if the key doesn't exist. Use .get(key, default) for safe access.

data = {"name": "Otieno", "age": 22}

# Unsafe  -  raises KeyError:
# print(data["score"])

# Safe  -  returns None or default:
print(data.get("score"))        # None
print(data.get("score", 0))     # 0

3. Dictionary Methods

person = {"name": "Wanjiru", "city": "Nairobi", "age": 30}

print(person.keys())    # dict_keys(['name', 'city', 'age'])
print(person.values())  # dict_values(['Wanjiru', 'Nairobi', 30])
print(person.items())   # dict_items([('name', 'Wanjiru'), ...])
Key Concept: Dictionary keys must be unique and immutable (strings, numbers, tuples). Values can be anything - strings, numbers, lists, even other dictionaries.

Try It Yourself

Try it
Output

Challenge

Challenge

Create a dictionary for a Kenyan student profile:

  1. Keys: name, school, grade, favourite_subject, county
  2. Print each value using its key
  3. Add a new key age
  4. Change the grade to "Form 3"
  5. Print the final dictionary

Summary

Summary

  • Dictionaries: {'key': 'value'}
  • Access: dict['key']
  • Add/modify: dict['key'] = value
  • Delete: del dict['key']
  • Safe access: dict.get('key', default)
  • Check membership: 'key' in dict
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

You can loop through a dictionary to visit each key-value pair. Python gives you methods to loop through just keys, just values, or both at once.

  • for key in dict: - loops through keys
  • for key, value in dict.items(): - loops through key-value pairs
  • for value in dict.values(): - loops through values only
  • for key in dict.keys(): - same as looping directly
  • Use sorted(dict) to loop in alphabetical order
Think of it like this: Looping through a dictionary is like going through a class register one student at a time. Each student (key) has marks (value). You call each student's name, check their marks, and record what you need. When you've gone through every entry, you're done.

Deep dive

What's Really Happening

1. Looping with .items()

scores = {
    "Amina": 87,
    "Otieno": 72,
    "Wanjiru": 95,
    "Baraka": 68,
}

for name, score in scores.items():
    if score >= 80:
        status = "PASS with distinction"
    else:
        status = "PASS"
    print(f"{name}: {score}  -  {status}")

2. Looping in Sorted Order

capitals = {
    "Kenya": "Nairobi",
    "Uganda": "Kampala",
    "Tanzania": "Dodoma",
    "Rwanda": "Kigali",
}

for country in sorted(capitals):
    print(f"{country}: {capitals[country]}")
# Kenya: Nairobi
# Rwanda: Kigali
# Tanzania: Dodoma
# Uganda: Kampala

3. Building Dictionaries in a Loop

names = ["Amina", "Otieno", "Wanjiru"]
raw_scores = [87, 72, 95]

# Build a dictionary from two lists
results = {}
for name, score in zip(names, raw_scores):
    results[name] = score

print(results)  # {'Amina': 87, 'Otieno': 72, 'Wanjiru': 95}
Key Concept: As of Python 3.7+, dictionaries maintain insertion order. Looping through a dictionary visits keys in the order they were added. Use sorted() if you want alphabetical order.

Try It Yourself

Try it
Output

Challenge

Challenge

Create a dictionary of 5 Kenyan athletes and their sport. Then:

  1. Loop through all pairs and print: "[Name] competes in [Sport]"
  2. Print all athlete names in alphabetical order
  3. Print all unique sports (some athletes may share a sport)

Summary

Summary

  • dict.items() — returns key-value pairs
  • dict.keys() — returns keys
  • dict.values() — returns values
  • sorted(dict.keys()) — loop in alphabetical order
  • set(dict.values()) — unique values only
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Nesting means putting collections inside other collections - a list inside a dictionary, a dictionary inside a list, or a dictionary inside a dictionary. This lets you model real-world data that has structure within structure.

  • A list of dictionaries - e.g. a list of students, each with their own details
  • A dictionary of lists - e.g. a school with lists of subjects per class
  • A dictionary of dictionaries - e.g. users, each with their own profile
  • Access nested data by chaining brackets: data["key"][0]["name"]
Think of it like this: Nesting is like a set of Russian matryoshka dolls - each one contains another inside it. Or think of a school filing cabinet: the cabinet (outer dictionary) has drawers (inner lists), and each drawer has folders (inner dictionaries), each folder has documents (values). Real data is always structured this way.

Deep dive

What's Really Happening

1. List of Dictionaries

students = [
    {"name": "Amina", "grade": "A", "score": 87},
    {"name": "Otieno", "grade": "B", "score": 72},
    {"name": "Wanjiru", "grade": "A", "score": 95},
]

for student in students:
    print(f"{student['name']}: {student['grade']} ({student['score']})")

# Filter  -  only A students
a_students = [s for s in students if s["grade"] == "A"]
print(f"{len(a_students)} students got an A")

2. Dictionary of Lists

school = {
    "Form 1": ["Maths", "English", "Science", "Kiswahili"],
    "Form 2": ["Maths", "English", "Chemistry", "Physics"],
    "Form 3": ["Maths", "English", "Biology", "Geography"],
}

for form, subjects in school.items():
    print(f"\n{form}:")
    for subject in subjects:
        print(f"  - {subject}")

3. Dictionary of Dictionaries

users = {
    "amina01": {"name": "Amina Osei", "role": "student", "score": 87},
    "otieno_k": {"name": "Otieno Kamau", "role": "student", "score": 72},
    "ms_wanjiru": {"name": "Wanjiru Mwangi", "role": "teacher", "score": None},
}

for username, profile in users.items():
    print(f"{username}: {profile['name']} ({profile['role']})")
Key Concept: Nesting mirrors how real data is structured. A JSON response from any web API looks exactly like a Python dictionary with nested lists and dictionaries inside. Understanding nesting is essential for working with APIs and databases.

Try It Yourself

Try it
Output

Challenge

Challenge

Build a Kenya school database:

  1. Create a list of 3 school dictionaries, each with: name, county, type (primary/secondary), subjects (a list)
  2. Loop through and print each school's name and subjects

Summary

Summary

  • Lists of dictionaries: useful for many objects of the same type
  • Lists in dictionaries: store multiple values for one key
  • Dictionaries in dictionaries: model complex relationships
  • Access nested data by chaining: dict['key1']['key2']
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

input() pauses your program and waits for the user to type something and press Enter. Whatever they type comes back as a string.

  • name = input("What is your name? ") - shows a prompt and waits
  • The result is always a string - even if the user types a number
  • Convert to number with int() or float(): age = int(input("Age: "))
  • The prompt message (inside the quotes) is what the user sees
  • A trailing space in the prompt keeps the cursor away from the text
Think of it like this: input() is like a waiter taking your order at a restaurant. The waiter asks a question (the prompt), stands and waits while you decide, then writes down exactly what you say (your typed input) and brings it to the kitchen (your program). The program then does something with your order.

Deep dive

What's Really Happening

1. input() Always Returns a String

name = input("Enter your name: ")
print(f"Hello, {name}!")

age_str = input("Enter your age: ")
print(type(age_str))  # <class 'str'>  -  always a string!

age = int(age_str)    # convert to integer for maths
birth_year = 2025 - age
print(f"You were born around {birth_year}")

2. Validating Input

age_str = input("Enter your age: ")

if age_str.isdigit():
    age = int(age_str)
    print(f"You are {age} years old")
else:
    print("Please enter a valid number")

3. Building a Simple Interactive Program

print("=== School Fee Calculator ===")
student = input("Student name: ")
grade = input("Grade (Form 1-4): ")
fee_per_term = float(input("Fee per term (KSh): "))

annual_fee = fee_per_term * 3
print(f"\nStudent: {student}")
print(f"Grade: {grade}")
print(f"Annual fee: KSh {annual_fee:,.0f}")
Key Concept: Never trust user input. Always validate before converting. int("hello") raises a ValueError. Use .isdigit() to check first, or wrap the conversion in a try/except block (covered in Lesson 32).

Try It Yourself

Try it
Output

Challenge

Challenge

Build an M-Pesa balance checker (simulated):

  1. Ask the user: "Enter your M-Pesa balance: " and convert to float
  2. Ask: "Enter amount to send: " and convert to float
  3. If balance >= amount: print "Transaction successful! Remaining: KSh [balance - amount]"
  4. Else: print "Insufficient funds. Your balance: KSh [balance]"

Note: In our browser editor, use fixed values instead of input() for testing.

Summary

Summary

  • input(prompt) — displays prompt and returns user's input as a string
  • Always convert to number with int() or float() before math
  • number % 2 == 0 — checks if a number is even
  • Multi-line prompts: use \n in the string or build with +=
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A while loop keeps running a block of code as long as a condition is True. When the condition becomes False, the loop stops.

  • while condition: - keeps going as long as condition is True
  • You must change something inside the loop that eventually makes the condition False
  • break - exits the loop immediately
  • continue - skips the rest of the current iteration and goes to the next
  • An infinite loop (condition never becomes False) will run forever - use break to exit
Think of it like this: A while loop is like a night watchman at a gate. The watchman keeps working while the gate is open and it is still night. The moment it becomes daytime (condition becomes False), the watchman goes home. If something urgent happens (intruder!), the watchman can leave immediately - that is break.

Deep dive

What's Really Happening

1. Counting Loops with while

count = 1
while count <= 5:
    print(f"Count: {count}")
    count += 1   # MUST increment  -  otherwise infinite loop!
print("Done")

2. Input Validation Loop

while True:
    answer = input("Type 'yes' or 'no': ").lower()
    if answer == 'yes':
        print("Great! Moving on.")
        break
    elif answer == 'no':
        print("OK, stopping here.")
        break
    else:
        print("Invalid. Please type 'yes' or 'no'.")

3. break and continue

numbers = [12, 7, 3, 19, 5, 8, 11]
i = 0

while i < len(numbers):
    n = numbers[i]
    i += 1

    if n % 2 == 0:
        continue   # skip even numbers

    if n > 15:
        break      # stop if number exceeds 15

    print(n)  # prints 7, 3
Key Concept: Use a for loop when you know how many iterations you need. Use a while loop when you keep going until a condition changes - like waiting for valid user input, reading data until end-of-file, or running a game until the player quits.

Try It Yourself

Try it
Output

Challenge

Challenge

Build a countdown timer simulation:

  1. Start at 10, count down to 1, printing each number
  2. When it reaches 0, print "Go! Simama!" (use while loop)
  3. Also print a message for each step: "T-minus [number]..."

Summary

Summary

  • while condition: — runs until condition is False
  • Always update the condition variable or use break — avoid infinite loops
  • break — exits the loop immediately
  • continue — skips rest of loop body, goes back to condition
  • Flags: boolean variables that control a loop
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A function is a named block of code you write once and can use many times. Instead of repeating the same code in multiple places, you put it in a function and call it by name whenever you need it.

  • Define with def function_name():
  • Call it by writing the name with parentheses: function_name()
  • The indented code inside the function runs each time you call it
  • Functions should do one thing and do it well
  • Always put a docstring (description in triple quotes) right after def
Think of it like this: A function is like a recipe. A bread recipe is written once in a recipe book. Whenever you want bread, you follow the recipe - you don't invent it again from scratch each time. You can make bread on Monday, Wednesday, and Sunday, always using the same recipe. Functions work the same way: write once, use many times.

Deep dive

What's Really Happening

1. Defining and Calling Functions

def greet():
    """Display a simple greeting."""
    print("Hello! Welcome!")
    print("Welcome to Python.")

greet()   # call it once
greet()   # call it again  -  same code runs again

2. The def Statement and Scope

When Python sees def, it creates a function object and binds it to the name. Variables created inside a function are local - they only exist inside that function.

def calculate_bmi(weight_kg, height_m):
    """Calculate Body Mass Index."""
    bmi = weight_kg / (height_m ** 2)   # local variable
    return bmi

result = calculate_bmi(70, 1.75)
print(f"BMI: {result:.1f}")
# print(bmi)  # NameError  -  bmi only exists inside the function

3. Docstrings

def format_phone(number):
    """
    Format a Kenyan phone number to international format.

    Args:
        number (str): Phone number starting with 07 or 01
    Returns:
        str: Number in format +254XXXXXXXXX
    """
    if number.startswith("0"):
        return "+254" + number[1:]
    return number

print(format_phone("0712345678"))  # +254712345678
print(format_phone.__doc__)        # prints the docstring
Key Concept: A function without return returns None automatically. Good functions are small, focused, and well-named. If you need a comment to explain what a function does, your function name probably isn't descriptive enough.

Try It Yourself

Try it
Output

Challenge

Challenge

Write two functions:

  1. display_message() — prints one sentence explaining what you're learning (Python functions)
  2. favorite_book(title) — accepts a book title and prints: "One of my favourite books is [title]"

Call each function at least once.

Summary

Summary

  • def function_name(): defines a function
  • Functions run when called: function_name()
  • Parameters receive values (arguments) passed in the call
  • Docstrings describe what a function does (triple quotes)
  • Variables inside functions are local — they don't exist outside
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Arguments are values you pass into a function when you call it. Parameters are the variable names inside the function definition that receive those values.

  • Positional arguments - matched by position: greet("Amina", 16)
  • Keyword arguments - matched by name: greet(age=16, name="Amina")
  • Default values - used when no argument is provided: def greet(name, lang="English"):
  • Keyword arguments can be in any order
  • Default parameters must come after non-default ones
Think of it like this: Arguments are like ingredients you bring to a chef (the function). A bread recipe (function) needs flour, water, and salt (parameters). When you bring the ingredients (arguments), the chef follows the recipe with exactly what you provided. If you forget the salt, the chef uses a default amount they keep on the counter.

Deep dive

What's Really Happening

1. Positional vs Keyword Arguments

def describe_student(name, grade, school="Unknown"):
    """Print a student description."""
    print(f"{name}  -  {grade} at {school}")

# Positional (order matters):
describe_student("Amina", "Form 3", "Alliance Girls")

# Keyword (order doesn't matter):
describe_student(grade="Form 2", name="Otieno")

# Default used when school not provided:
describe_student("Wanjiru", "Form 4")

2. Default Values - Important Gotcha

# DANGER: mutable default argument  -  shared across all calls!
def add_score(student, score, scores=[]):   # BAD
    scores.append(score)
    return scores

# SAFE: use None as default, create inside function
def add_score(student, score, scores=None):  # GOOD
    if scores is None:
        scores = []
    scores.append(score)
    return scores

3. Multiple Return Values

def get_stats(numbers):
    """Return min, max, and average of a list."""
    return min(numbers), max(numbers), sum(numbers)/len(numbers)

scores = [72, 85, 91, 60, 78]
low, high, avg = get_stats(scores)
print(f"Low: {low}, High: {high}, Avg: {avg:.1f}")
Key Concept: Python functions can return multiple values as a tuple. return a, b, c is the same as return (a, b, c). Unpack them with x, y, z = function().

Try It Yourself

Try it
Output

Challenge

Challenge

Write a function make_shirt(size, message='I love Python') that prints the shirt size and message. Then:

  1. Call it with only a size (use default message)
  2. Call it with a size and a custom message using positional args
  3. Call it with keyword arguments in any order

Summary

Summary

  • Positional args are matched by order — order matters
  • Keyword args are matched by name — order flexible
  • Default values make arguments optional
  • Parameters with defaults must come after those without
  • Keyword and positional can mix — positional must come first
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A return value is what a function sends back to the code that called it. The return statement immediately exits the function and hands back a value.

  • return value - exits the function and sends back the value
  • The returned value can be stored in a variable: result = my_function()
  • A function without return returns None
  • You can return early from a function using return alone
  • Return makes functions composable - you can use one function's output as another's input
Think of it like this: Return values are like a courier delivery. You hand over a package (arguments), they ride to the destination, complete the task (function body), and then return to you with a receipt (return value). The receipt is proof that the job was done and contains useful information about what happened.

Deep dive

What's Really Happening

1. Return Stops Execution

def check_age(age):
    """Return whether someone can vote."""
    if age < 18:
        return "Too young to vote"   # exits here if age < 18
    if age >= 100:
        return "Please verify age"   # exits here if age >= 100
    return "Eligible to vote"        # reached only if 18 <= age < 100

print(check_age(16))   # Too young to vote
print(check_age(25))   # Eligible to vote
print(check_age(110))  # Please verify age

2. Using Return Values

def get_full_name(first, last, middle=""):
    """Return a formatted full name."""
    if middle:
        return f"{first} {middle} {last}".title()
    return f"{first} {last}".title()

name = get_full_name("amina", "osei")
greeting = f"Welcome, {name}!"
print(greeting.upper())  # chain the result

3. Returning Dictionaries

def build_student(name, score):
    """Return a student record as a dictionary."""
    grade = "A" if score >= 80 else "B" if score >= 65 else "C"
    return {
        "name": name,
        "score": score,
        "grade": grade,
        "passed": score >= 40,
    }

student = build_student("Wanjiru", 87)
print(student)
print(f"{student['name']} got grade {student['grade']}")
Key Concept: Functions that return values are far more flexible than functions that just print. A return value can be passed to another function, stored, formatted, or used in calculations. A printed value is gone forever.

Try It Yourself

Try it
Output

Challenge

Challenge

Write a function make_album(artist_name, album_title, num_songs=None) that returns a dictionary with album info. Then:

  1. Call it without num_songs
  2. Call it with num_songs
  3. Print both results

Summary

Summary

  • return value sends a value back to the caller
  • The function exits immediately when it hits return
  • Without return, functions return None
  • Return values can be any type: string, number, list, dictionary
  • Optional parameters use default '' or None — test with if parameter:
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

You can pass a list to a function just like any other value. A function can then loop through it, modify it, or return a new list based on it.

  • Pass a list: process(my_list)
  • The function receives a reference - changes inside the function affect the original
  • Pass a copy to prevent changes: process(my_list[:])
  • Return a new list from the function when you want the original unchanged
  • List operations inside functions work the same as outside
Think of it like this: Passing a list to a function is like handing your shopping list to a friend to do the shopping for you. If your friend crosses out items as they shop (modifying the list), your original list is changed. If they make a photocopy of the list first, your original stays safe. In Python, my_list[:] is the photocopy.

Deep dive

What's Really Happening

1. Lists are Passed by Reference

def add_bonus(scores, bonus):
    """Add bonus points to each score  -  modifies original."""
    for i in range(len(scores)):
        scores[i] += bonus

results = [72, 85, 60, 78]
add_bonus(results, 5)
print(results)  # [77, 90, 65, 83]  -  original changed!

2. Passing a Copy to Protect the Original

def add_bonus_safe(scores, bonus):
    """Return new list with bonus  -  original unchanged."""
    return [score + bonus for score in scores]

results = [72, 85, 60, 78]
boosted = add_bonus_safe(results[:], 5)  # pass a copy
print(results)  # [72, 85, 60, 78]  -  unchanged
print(boosted)  # [77, 90, 65, 83]

3. Building New Lists in Functions

def filter_passes(scores, pass_mark=40):
    """Return only passing scores."""
    return [s for s in scores if s >= pass_mark]

def get_top_students(students, n=3):
    """Return the top n students sorted by score."""
    return sorted(students, key=lambda s: s["score"], reverse=True)[:n]

exam = [72, 35, 85, 28, 91, 45, 60]
print(filter_passes(exam))  # [72, 85, 91, 45, 60]
Key Concept: In Python, lists are passed by reference - the function receives the same list object, not a copy. This is efficient (no copying large data) but means functions can accidentally change your data. Pass list[:] or use list.copy() when you want to protect the original.

Try It Yourself

Try it
Output

Challenge

Challenge

Write a function show_magicians(magicians) that prints each magician's name. Then write make_great(magicians) that adds "the Great" to each name in the list (modify in place). Call both and verify the list was modified.

Summary

Summary

  • You can pass any list to a function as an argument
  • Functions can loop through, read, or modify a list
  • Modifications to a list inside a function are permanent (original is changed)
  • To preserve the original, pass a copy: my_list[:] or my_list.copy()
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Sometimes you don't know in advance how many arguments a function will receive. Python's *args and **kwargs let functions accept any number of arguments.

  • *args - collects any number of positional arguments into a tuple
  • **kwargs - collects any number of keyword arguments into a dictionary
  • You can pass 1 argument or 100 - the function handles it
  • The names args and kwargs are convention - the * and ** are what matter
Think of it like this: *args is like a buffet where the chef doesn't know how many guests will come or how much each person will eat. The chef prepares food and serves however many plates are needed. Some days 5 people come, some days 50 - the buffet system handles any number. **kwargs is like a custom order form where each guest writes their own preferences by name.

Deep dive

What's Really Happening

1. *args - Variable Positional Arguments

def make_pizza(*toppings):
    """Make a pizza with any number of toppings."""
    print("Making pizza with:")
    for topping in toppings:
        print(f"  - {topping}")

make_pizza("cheese")
make_pizza("cheese", "mushrooms", "peppers")
make_pizza("beef", "peppers", "onions", "tomatoes")

2. **kwargs - Variable Keyword Arguments

def build_profile(username, **info):
    """Build a user profile with any extra details."""
    profile = {"username": username}
    profile.update(info)
    return profile

p1 = build_profile("amina01", age=16, school="Alliance Girls", county="Nairobi")
p2 = build_profile("otieno_k", age=22, job="developer")

print(p1)
print(p2)

3. Combining All Argument Types

def log_event(event_type, *messages, **metadata):
    """Log an event with messages and metadata."""
    print(f"[{event_type.upper()}]")
    for msg in messages:
        print(f"  {msg}")
    for key, value in metadata.items():
        print(f"  {key}: {value}")

log_event("info", "User logged in", "Session started",
          user="amina01", ip="41.90.64.1")
Key Concept: Order matters when combining: def func(required, *args, **kwargs). Required positional parameters come first, then *args, then **kwargs. This order is enforced by Python.

Try It Yourself

Try it
Output

Challenge

Challenge

Write a function build_car(manufacturer, model, **options) that returns a dictionary. Include the manufacturer and model in the dictionary, plus any keyword options. Call it with and without extra options and print both results.

Summary

Summary

  • *args collects extra positional arguments into a tuple
  • **kwargs collects extra keyword arguments into a dictionary
  • Order: regular params → *args → defaults → **kwargs
  • The names args and kwargs are convention — any name works
  • Use when you don't know how many arguments will be passed
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A module is a Python file containing functions, classes, and variables that you can import and use in your own programs. Python comes with a huge standard library of modules - and you can also install thousands more.

  • Import a whole module: import random, then random.choice(list)
  • Import specific items: from math import sqrt, pi
  • Import with alias: import datetime as dt
  • Common built-in modules: random, math, datetime, os, json
  • Your own .py file is also a module you can import
Think of it like this: Modules are like different toolboxes in a workshop. A carpenter's workshop has a woodwork toolbox, a measuring toolbox, and a finishing toolbox. You open only the toolbox you need for the current job. import math opens the maths toolbox. import random opens the randomness toolbox. Each gives you the right tools for the task at hand.

Deep dive

What's Really Happening

1. Importing and Using Standard Modules

import random
import math

# random module
fruits = ["mango", "avocado", "passion fruit", "guava", "papaya"]
print(random.choice(fruits))           # random item
print(random.randint(1, 100))          # random integer 1-100
random.shuffle(fruits)                  # shuffle in place
print(fruits)

# math module
print(math.sqrt(144))    # 12.0
print(math.pi)           # 3.14159...
print(math.ceil(4.2))    # 5
print(math.floor(4.9))   # 4

2. datetime Module

from datetime import datetime, date

now = datetime.now()
print(f"Date: {now.strftime('%d %B %Y')}")
print(f"Time: {now.strftime('%H:%M')}")

birthday = date(2008, 3, 15)
today = date.today()
age_days = (today - birthday).days
print(f"Days since birthday: {age_days}")

3. Creating Your Own Module

# Save as: kenya_utils.py
COUNTIES = 47
def format_phone(number):
    if number.startswith("0"):
        return "+254" + number[1:]
    return number

# In another file:
import kenya_utils
print(kenya_utils.COUNTIES)
print(kenya_utils.format_phone("0712345678"))
Key Concept: from module import * imports everything but pollutes your namespace and makes it unclear where names come from. Prefer import module or from module import specific_name for clarity.

Try It Yourself

Try it
Output

Challenge

Challenge

Use the random module to build a simple name picker:

  1. Create a list of 5 Kenyan names
  2. Use random.choice() to pick a random winner
  3. Use random.shuffle() to shuffle the list
  4. Print the shuffled list and the winner

Summary

Summary

  • import module — import an entire module
  • from module import func — import a specific function
  • import module as alias — use a shorter name
  • Common modules: random, math, os, datetime, json
  • if __name__ == "__main__": — code that only runs when the file is executed directly
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A class is a blueprint for creating objects. It bundles data (attributes) and behaviour (methods) together. An instance is one specific object created from that blueprint.

  • Define a class with class ClassName:
  • __init__ is the constructor - runs when you create an instance
  • self refers to the specific instance being created or used
  • Attributes store data: self.name = name
  • Methods are functions inside the class that operate on the instance
Think of it like this: A class is like the blueprint for a house. The blueprint describes how many rooms, where the doors are, and how big the kitchen is. An instance is an actual house built from that blueprint. You can build many houses from one blueprint - each is a separate house but they all share the same design. Attributes are the house's details (colour, number of rooms); methods are what you can do in the house (cook, sleep, shower).

Deep dive

What's Really Happening

1. Defining a Class

class Student:
    """Represents a student at a Kenyan school."""

    def __init__(self, name, grade, school):
        """Initialize student attributes."""
        self.name = name
        self.grade = grade
        self.school = school
        self.scores = []

    def add_score(self, subject, score):
        """Add a subject score."""
        self.scores.append({"subject": subject, "score": score})

    def get_average(self):
        """Return average score."""
        if not self.scores:
            return 0
        return sum(s["score"] for s in self.scores) / len(self.scores)

    def describe(self):
        """Print a summary of the student."""
        print(f"{self.name}  -  {self.grade} at {self.school}")
        print(f"Average score: {self.get_average():.1f}")

2. Creating and Using Instances

amina = Student("Amina Osei", "Form 3", "Alliance Girls")
otieno = Student("Otieno Kamau", "Form 2", "Starehe Boys")

amina.add_score("Maths", 87)
amina.add_score("English", 92)
amina.add_score("Science", 79)

amina.describe()
otieno.describe()  # separate instance  -  different data

3. Modifying Instance Attributes

# Direct modification
amina.grade = "Form 4"

# Through a method (preferred  -  allows validation)
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        if amount > 0:
            self.balance += amount
            return True
        return False
Key Concept: self is just a convention - Python passes the instance automatically as the first argument to every method. You could name it anything, but everyone uses self. Always include it as the first parameter of every method.

Try It Yourself

Try it
Output

Challenge

Challenge

Create a Restaurant class with:

  • Attributes: restaurant_name and cuisine_type
  • Method describe_restaurant() that prints both attributes
  • Method open_restaurant() that prints the restaurant is open

Create two different instances and call the methods on each.

Summary

Summary

  • A class is a blueprint; an instance is the actual object
  • __init__ runs automatically when an instance is created
  • self refers to the current instance — always the first method parameter
  • Attributes store data: self.name = name
  • Methods are functions defined inside a class
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Once you have a class, you create instances and work with them. You can set attributes directly, use methods to update them, and use Python's special __str__ method to control how an object displays itself.

  • Set defaults in __init__ so every instance starts with sensible values
  • Use methods to modify attributes - they can validate the data before changing it
  • Use __str__ to define what print(instance) shows
  • Class attributes are shared by all instances; instance attributes are per-instance
Think of it like this: Working with instances is like personalising your school locker. The school provides identical lockers (the class), but each student fills theirs with their own books, adds their own padlock, and sticks their own photos (attributes). Each locker is independent - what Amina puts in hers doesn't affect Otieno's.

Deep dive

What's Really Happening

1. Class Attributes vs Instance Attributes

class Student:
    school = "Starehe Boys"   # class attribute  -  shared by all

    def __init__(self, name, grade):
        self.name = name      # instance attribute  -  unique per student
        self.grade = grade

s1 = Student("Amina", "Form 3")
s2 = Student("Otieno", "Form 2")

print(s1.school)   # Starehe Boys (from class)
print(s2.school)   # Starehe Boys (from class)

Student.school = "Alliance Girls"  # changes for ALL instances
print(s1.school)   # Alliance Girls

2. __str__ Method

class Student:
    def __init__(self, name, grade, score):
        self.name = name
        self.grade = grade
        self.score = score

    def __str__(self):
        return f"Student({self.name}, {self.grade}, score={self.score})"

s = Student("Amina", "Form 3", 87)
print(s)   # Student(Amina, Form 3, score=87)
print(str(s))  # same

3. Incrementing Attributes with Methods

class Counter:
    def __init__(self):
        self.count = 0
        self.history = []

    def increment(self, amount=1):
        self.count += amount
        self.history.append(self.count)

    def reset(self):
        self.count = 0
        self.history.clear()

c = Counter()
c.increment()
c.increment(5)
c.increment(3)
print(c.count)    # 9
print(c.history)  # [1, 6, 9]
Key Concept: Always use methods to change attributes when validation is needed. Direct assignment (obj.attr = value) bypasses any checks. A method can verify the value before storing it.

Try It Yourself

Try it
Output

Challenge

Challenge

Extend the Car class:

  1. Add a fuel_level attribute with a default of 50 (percent)
  2. Add describe_fuel() that prints the fuel level
  3. Add fill_tank(amount) that increases fuel — but caps at 100
  4. Create a car, describe its fuel, fill it, and describe again

Summary

Summary

  • Default attribute values are set in __init__ without parameters
  • Attributes can be modified directly: instance.attr = value
  • Methods provide controlled ways to modify attributes
  • Increment methods add to an attribute value
  • Underscores in numbers improve readability: 23_500
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Inheritance lets a new class take on all the attributes and methods of an existing class, then add its own. The existing class is called the parent; the new one is the child.

  • Define child class: class Teacher(Person): inherits from Person
  • Call parent's __init__ with super().__init__(...)
  • The child gets all the parent's methods for free
  • The child can add new attributes and methods
  • The child can override a parent method by redefining it
Think of it like this: Inheritance is like a child inheriting traits from a parent. Amina might inherit her mother's height and her father's intelligence (parent class attributes), but she also has her own unique personality and skills (child class additions). She "overrides" her parents' cooking style with her own recipes. In Python, child classes inherit everything from parents but can customise anything they need.

Deep dive

What's Really Happening

1. Basic Inheritance

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def describe(self):
        print(f"{self.name}, age {self.age}")

class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)   # call parent __init__
        self.grade = grade
        self.scores = []

    def describe(self):               # override parent method
        super().describe()            # call parent version first
        print(f"  Grade: {self.grade}")

class Teacher(Person):
    def __init__(self, name, age, subject):
        super().__init__(name, age)
        self.subject = subject

    def describe(self):
        super().describe()
        print(f"  Teaches: {self.subject}")

2. Using Inherited Classes

s = Student("Amina", 16, "Form 3")
t = Teacher("Ms Wanjiru", 35, "Mathematics")

s.describe()
t.describe()

# isinstance() checks class hierarchy
print(isinstance(s, Student))  # True
print(isinstance(s, Person))   # True  -  also a Person
print(isinstance(t, Student))  # False

3. Multiple Levels

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "Woof!"

class ServiceDog(Dog):
    def __init__(self, name, task):
        super().__init__(name)
        self.task = task
    def describe(self):
        return f"{self.name} is trained for: {self.task}"
Key Concept: Use inheritance when there is a clear "is-a" relationship: a Student IS-A Person. Don't use it just to share code - if the relationship isn't "is-a", use composition (give the class an attribute that is an instance of another class) instead.

Try It Yourself

Try it
Output

Challenge

Challenge

Create an IceCreamStand that inherits from a Restaurant class:

  1. Restaurant has name, cuisine_type, and describe()
  2. IceCreamStand adds a flavours list attribute
  3. Add display_flavours() to print all available flavours
  4. Create an instance and call both describe() and display_flavours()

Summary

Summary

  • Child class: class Child(Parent):
  • super().__init__(...) calls the parent's initialiser
  • Child inherits all parent attributes and methods
  • Override a method by redefining it in the child class
  • Instances can hold other instances as attributes (composition)
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Python can read text files from your computer. Use with open(filename) as f: - the with block automatically closes the file when done.

  • open('file.txt') opens a file for reading (default mode)
  • .read() - reads the entire file as one string
  • .readlines() - reads all lines into a list
  • Loop through lines with for line in f:
  • Always use with - it guarantees the file is closed even if an error occurs
Think of it like this: Reading a file is like reading a letter someone left for you on your desk. You open the envelope (open()), read the contents (.read()), and then put the letter back (with closes it automatically). The letter stays on your desk - reading it doesn't remove or change it.

Deep dive

What's Really Happening

1. Reading a Whole File

# Assume we have a file "students.txt" with one name per line
with open("students.txt") as f:
    contents = f.read()
    print(contents)
    print(f"Characters: {len(contents)}")

2. Reading Line by Line

with open("students.txt") as f:
    for line in f:
        name = line.strip()   # removes trailing \n
        if name:              # skip empty lines
            print(f"Processing: {name}")

3. Reading into a List and Analysing

with open("scores.txt") as f:
    lines = f.readlines()

scores = [int(line.strip()) for line in lines if line.strip()]
print(f"Students: {len(scores)}")
print(f"Average: {sum(scores)/len(scores):.1f}")
print(f"Highest: {max(scores)}")
print(f"Lowest:  {min(scores)}")
Key Concept: File paths can be relative ("data.txt" - same directory) or absolute ("/home/amina/data.txt"). On Windows, use forward slashes or raw strings: r"C:\Users\Amina\data.txt". The with statement uses a context manager - it calls f.close() automatically when the block ends.

Try It Yourself

Try it
Output

Challenge

Challenge

Create a text file called names.txt with 5 Kenyan names (one per line), then write a program that:

  1. Reads the file
  2. Prints each name with a greeting: "Habari, [Name]!"
  3. Counts how many names are in the file and prints the total

Note: In CodeHub's editor, use open() with a string variable if file I/O isn't available — focus on the logic.

Summary

Summary

  • open('file.txt') returns a file object
  • with open(...) as f: auto-closes the file
  • f.read() reads entire file as a string
  • f.readlines() returns a list of lines
  • for line in f: iterates line by line (memory-efficient)
  • Use .strip() or .rstrip() to remove newlines
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

Python can write text to files, creating new files or overwriting existing ones. Use open(filename, 'w') for writing, or 'a' to append to an existing file.

  • 'w' mode - write (creates file or overwrites existing)
  • 'a' mode - append (adds to the end, doesn't delete existing content)
  • f.write("text") - writes text (add \n manually for new lines)
  • f.writelines(list) - writes a list of strings
  • Always use with to ensure the file is properly saved and closed
Think of it like this: Writing to a file is like writing in a school exercise book. Mode 'w' is like getting a brand new book - you start fresh (old content is gone). Mode 'a' is like opening the same book to the next blank page and continuing from where you left off. The book stays after class (the file persists after your program ends).

Deep dive

What's Really Happening

1. Writing to a New File

students = ["Amina Osei", "Otieno Kamau", "Wanjiru Mwangi"]

with open("class_list.txt", "w") as f:
    f.write("Form 3A Class List\n")
    f.write("=" * 20 + "\n")
    for i, name in enumerate(students, 1):
        f.write(f"{i}. {name}\n")

print("File saved!")

2. Appending to an Existing File

new_student = "Baraka Njoroge"

with open("class_list.txt", "a") as f:
    f.write(f"{new_student}\n")  # adds to existing content

# Verify
with open("class_list.txt") as f:
    print(f.read())

3. Writing Structured Data

results = [
    {"name": "Amina", "score": 87, "grade": "A"},
    {"name": "Otieno", "score": 72, "grade": "B"},
    {"name": "Wanjiru", "score": 95, "grade": "A"},
]

with open("results.csv", "w") as f:
    f.write("Name,Score,Grade\n")   # header
    for r in results:
        f.write(f"{r['name']},{r['score']},{r['grade']}\n")
Key Concept: 'w' mode creates the file if it doesn't exist, or silently erases it if it does. Always double-check before using 'w' on important files. Use 'a' if you want to preserve existing content and only add to it.

Try It Yourself

Try it
Output

Challenge

Challenge

Build a simple guest book:

  1. Create a list of 3 guest names
  2. Write them to guest_book.txt (one per line, with a greeting)
  3. Append one more guest using 'a' mode
  4. Read the file back and print all contents

Summary

Summary

  • 'w' — write mode: creates or overwrites the file
  • 'a' — append mode: adds to end without erasing
  • 'r' — read mode (default)
  • file.write(string) — write a string (add \n manually)
  • file.writelines(list) — write a list of strings
  • Always use with open(...) to ensure files are properly closed
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

An exception is an error that occurs while your program is running. Instead of letting the program crash, you can catch the exception and handle it gracefully using try/except.

  • try: - put the risky code here
  • except ErrorType: - runs if that error occurs
  • else: - runs only if no error occurred
  • finally: - always runs, error or not (use for cleanup)
  • Common exceptions: ValueError, FileNotFoundError, ZeroDivisionError, KeyError
Think of it like this: try/except is like a safety net at a circus acrobat performance. The acrobat (your code) attempts something risky. If they fall (exception occurs), the safety net catches them (except block runs) and they land safely instead of crashing to the ground. The show continues. Without the net, one mistake ends everything.

Deep dive

What's Really Happening

1. Catching Specific Exceptions

def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Cannot divide by zero")
        return None
    else:
        print(f"Result: {result}")
        return result
    finally:
        print("divide() finished")   # always runs

divide(10, 2)   # Result: 5.0 → divide() finished
divide(10, 0)   # Error: Cannot divide by zero → divide() finished

2. Multiple except Blocks

def safe_convert(value):
    try:
        return int(value)
    except ValueError:
        print(f"'{value}' is not a valid integer")
        return None
    except TypeError:
        print("Input must be a string or number")
        return None

print(safe_convert("42"))     # 42
print(safe_convert("hello"))  # error message, None
print(safe_convert(None))     # error message, None

3. FileNotFoundError

filename = "students.txt"
try:
    with open(filename) as f:
        data = f.read()
except FileNotFoundError:
    print(f"File '{filename}' not found.")
    print("Creating a new file...")
    with open(filename, "w") as f:
        f.write("# Student records\n")
Key Concept: Catch specific exceptions, not all of them. A bare except: catches everything including keyboard interrupts and system errors, making bugs very hard to find. Always specify the exception type: except ValueError:, not just except:.

Try It Yourself

Try it
Output

Challenge

Challenge

Write a safe division calculator function safe_divide(a, b) that:

  1. Tries to divide a by b
  2. Catches ZeroDivisionError and returns None with a message
  3. Catches TypeError if non-numbers are passed
  4. Returns the result if successful

Test it with: normal division, divide by zero, and passing a string.

Summary

Summary

  • try/except catches exceptions and prevents crashes
  • except ExceptionType: catches a specific error
  • else: runs only if no exception occurred
  • finally: always runs (cleanup code)
  • pass — do nothing (fail silently)
  • Catch specific exceptions — avoid bare except:
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

JSON (JavaScript Object Notation) is a format for storing and sharing data. Python's json module lets you save Python dictionaries and lists to files, and load them back.

  • json.dump(data, file) - saves Python data to a JSON file
  • json.load(file) - loads data from a JSON file back into Python
  • json.dumps(data) - converts data to a JSON string (no file needed)
  • json.loads(string) - converts a JSON string back to Python data
  • JSON supports: strings, numbers, lists, dicts, booleans, None
Think of it like this: JSON is like a well-organised shop ledger. The shopkeeper writes down every item sold: name, price, quantity, date. The ledger format is so standard that any other shopkeeper can read it and understand it instantly. JSON is the "ledger format" that any programming language in the world can read - Python, JavaScript, Java, Swahili apps - all of them understand JSON.

Deep dive

What's Really Happening

1. Saving and Loading Data

import json

# Data to save
students = [
    {"name": "Amina", "score": 87, "grade": "A"},
    {"name": "Otieno", "score": 72, "grade": "B"},
    {"name": "Wanjiru", "score": 95, "grade": "A"},
]

# Save to file
with open("students.json", "w") as f:
    json.dump(students, f, indent=2)   # indent makes it readable

# Load back
with open("students.json") as f:
    loaded = json.load(f)

print(loaded[0]["name"])   # Amina
print(type(loaded))        # <class 'list'>

2. Pattern: Load or Create

import json

def load_data(filename):
    """Load data from JSON, return empty dict if file not found."""
    try:
        with open(filename) as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

def save_data(filename, data):
    """Save data to JSON file."""
    with open(filename, "w") as f:
        json.dump(data, f, indent=2)

# Usage
data = load_data("scores.json")
data["Baraka"] = 88
save_data("scores.json", data)

3. JSON Strings (No File Needed)

import json

# Python dict → JSON string (for sending over network)
profile = {"name": "Amina", "county": "Nairobi", "active": True}
json_str = json.dumps(profile)
print(json_str)  # {"name": "Amina", "county": "Nairobi", "active": true}

# JSON string → Python dict (for receiving from network)
received = '{"name": "Otieno", "score": 72}'
data = json.loads(received)
print(data["name"])  # Otieno
Key Concept: JSON is the universal language of web APIs. When you fetch data from any website or service, it almost always comes as JSON. Knowing how to parse JSON is essential for building real-world applications.

Try It Yourself

Try it
Output

Challenge

Challenge

Build a "favourite numbers" saver:

  1. Ask the user to enter 3 favourite numbers
  2. Store them in a list and save to favourites.json
  3. Load the file back and print: "Your favourite numbers are: [list]"
  4. Add error handling in case the file doesn't exist yet

Summary

Summary

  • import json
  • json.dump(data, file) — save Python object to JSON file
  • json.load(file) — load JSON file into Python object
  • json.dumps(data) — convert to JSON string (no file)
  • json.loads(string) — parse JSON string
  • JSON supports: str, int, float, bool, None, list, dict
  • indent=4 makes the JSON file human-readable
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

A test is code that checks whether your other code works correctly. Python's built-in unittest module lets you write automated tests that run every time to verify your functions do what they're supposed to do.

  • Import unittest and create a class that inherits from unittest.TestCase
  • Every test method name must start with test_
  • assertEqual(a, b) - passes if a == b, fails if not
  • assertTrue(x) - passes if x is True
  • setUp() - runs before each test to prepare data
Think of it like this: Testing your code is like checking your maths homework before submitting it to the teacher. You worked out each sum, then went back and verified each answer is correct. Automated tests do the same thing automatically - every time you change your code, they re-check all the answers instantly, so you know immediately if something broke.

Deep dive

What's Really Happening

1. Writing Your First Test

import unittest

def get_formatted_name(first, last, middle=""):
    """Return a neatly formatted full name."""
    if middle:
        return f"{first} {middle} {last}".title()
    return f"{first} {last}".title()

class NamesTestCase(unittest.TestCase):

    def test_first_last_name(self):
        """Do names like 'amina osei' work?"""
        formatted = get_formatted_name("amina", "osei")
        self.assertEqual(formatted, "Amina Osei")

    def test_first_middle_last_name(self):
        """Do names with a middle name work?"""
        formatted = get_formatted_name("john", "hooker", "lee")
        self.assertEqual(formatted, "John Lee Hooker")

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

2. All Assertion Methods

class MathTestCase(unittest.TestCase):

    def test_assertions(self):
        self.assertEqual(2 + 2, 4)
        self.assertNotEqual(2 + 2, 5)
        self.assertTrue(5 > 3)
        self.assertFalse(5 < 3)
        self.assertIn("Nairobi", ["Nairobi", "Mombasa"])
        self.assertNotIn("Eldoret", ["Nairobi", "Mombasa"])
        self.assertIsNone(None)
        self.assertIsNotNone("hello")

3. setUp() - Shared Test Data

class StudentTestCase(unittest.TestCase):

    def setUp(self):
        """Create test data used by multiple tests."""
        self.student = {"name": "Amina", "scores": [87, 92, 79]}

    def test_name(self):
        self.assertEqual(self.student["name"], "Amina")

    def test_score_count(self):
        self.assertEqual(len(self.student["scores"]), 3)

    def test_average(self):
        avg = sum(self.student["scores"]) / len(self.student["scores"])
        self.assertAlmostEqual(avg, 86.0, places=0)
Key Concept: Good tests are: fast (run in milliseconds), independent (each test sets up its own data), and descriptive (the test name explains what it checks). A failing test is not a failure - it's a bug caught before it reached users.

Try It Yourself

Try it
Output

Challenge

Challenge

Write a function get_city_country(city, country, population=None) that returns a string like "Santiago, Chile" or "Santiago, Chile - population 5,000,000". Then write a unittest.TestCase class with:

  1. test_city_country() — test without population
  2. test_city_country_population() — test with population

Summary

Summary

  • import unittest
  • Test class inherits from unittest.TestCase
  • Test method names must start with test_
  • Common assertions: assertEqual, assertTrue, assertIn
  • setUp() runs before each test method
  • Run tests: if __name__ == '__main__': unittest.main()
  • Good tests: each tests one thing, clear names, fast to run
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

The Simple Version

You now know all the core Python building blocks. The next step is to choose a direction and start building something real. Python has three major project paths for beginners, each with its own ecosystem of tools.

  • Game Development - install pygame and build 2D games: sprites, movement, collision detection
  • Data Visualization - install matplotlib and plotly to create beautiful charts and graphs from real data
  • Web Development - install django or flask to build websites and APIs that anyone can visit
  • Install packages with pip: python -m pip install package_name
  • Use virtual environments to keep each project's packages separate
Think of it like this: You've just finished Form 4 and have your KCSE certificate (your Python basics). Now you choose your career path. Do you go to university for Engineering (data science), Arts (web development), or Sports Science (game development)? Each path uses the same foundation you built, but specialises in a different direction. The certificate gets you in the door - the specialisation is where the exciting work begins.

Deep dive

What's Really Happening

1. Virtual Environments - Start Every Project With One

# Create a virtual environment
python -m venv my_project_env

# Activate (Windows)
my_project_env\Scripts\activate

# Activate (macOS/Linux)
source my_project_env/bin/activate

# Install packages (inside the venv)
pip install pygame
pip install matplotlib pandas
pip install django

# Save dependencies list
pip freeze > requirements.txt

# Deactivate when done
deactivate

2. The Python Ecosystem

# Data Science stack
pip install numpy pandas matplotlib scikit-learn

# Web development
pip install django          # full-featured framework
pip install flask           # lightweight framework
pip install fastapi uvicorn # modern async API framework

# Useful utilities
pip install requests        # HTTP requests to APIs
pip install pillow          # image processing
pip install pytest          # better testing than unittest

3. Where to Learn Next

Resources for continuing your Python journey:

  • docs.python.org - the official Python documentation
  • pypi.org - the Python Package Index: find a package for anything
  • realpython.com - tutorials, articles, and video courses
  • github.com - read and contribute to open source Python projects
  • Python Discord - active community for help and collaboration
Key Concept: The best way to learn is to build something you actually care about. Pick one project - a school fee calculator, a quiz game, a weather app, a simple website - and build it. You will learn more from one real project than from ten tutorials you never finish.

Try It Yourself

Try it
Output

Challenge

Challenge

Think about a project you'd like to build with Python. Write a program that:

  1. Stores your project idea in a variable project_idea
  2. Stores the Python library you'd use in a variable library
  3. Stores one skill you learned in this course in a variable skill_learned
  4. Prints a summary: "My project: [idea] | Library: [library] | I can: [skill]"

Then open your terminal and run python -m pip install requests to install your first external package!

Summary

Summary

  • You've completed all the core Python language basics
  • Use pip to install external packages: python -m pip install package_name
  • Use virtual environments (python -m venv env_name) to isolate project dependencies
  • Three major paths: Game Development (pygame), Data Visualization (matplotlib/plotly), Web Development (Django/Flask)
  • Python community: docs.python.org, PyPI, Real Python, Python Discord
  • The best way to learn is to build something — pick a project and start!
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */ .learn-body .editor-container, .editor-container { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch; } @media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } } .editor-container .editor-panel, .editor-container .preview-panel { display: flex; flex-direction: column; min-width: 0; overflow: hidden; border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff; } .editor-container .panel-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; background: var(--green-900, #0f3d28); color: #fff; font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase; } .editor-container .editor-buttons { display: flex; gap: 6px; } .editor-container .editor-buttons button { font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer; border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff; } .editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; } .editor-container .editor-buttons button:hover { filter: brightness(1.12); } .editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } .editor-container textarea { flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px; background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto; font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace; } .editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); } .editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; } .editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; } /* CodeHub lesson callouts and sections, unstyled in the plain learn template */ .learn-body .analogy, .learn-body .info-box { margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a); background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65; } .learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; } .learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; } .learn-body .try-it, .learn-body .challenge { margin-top: 28px; } .learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; } /* Lesson playground [5818] * * Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages. * A block is the markup CodeHub lessons already carry: * *
*
*
Label *
* *
*
Result
*
* * No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe * (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage. * JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does). * Plain ES5 on purpose: the file is inlined into WordPress pages without a build step. */ (function () { 'use strict'; if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; } var SKULPT = [ 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js' ]; var AUTO_RUN_DELAY = 400; var LANGS = { html: 1, css: 1, javascript: 1, python: 1 }; // Source text for a script that runs inside the generated document. JSON.stringify output is safe in a // script block except for a closing script tag, an HTML comment opener and the two line separators, so escape // every "<" and U+2028/2029. function js(value) { return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } var OUTPUT_STYLE = 'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' + '.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}'; function javascriptDoc(code) { return '' + OUTPUT_STYLE + '
' + '(function(){var out=document.getElementById("out");' + 'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' + 'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' + 'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' + 'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' + 'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' + 'window.alert=function(m){show(["alert: "+m],"info")};' + 'window.addEventListener("error",function(e){show([e.message],"error")});' + 'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' + 'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' + ''; } function pythonDoc(code) { return '' + OUTPUT_STYLE + '
Running...
' + '' + '(function(){var out=document.getElementById("out");' + 'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' + 'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' + 'out.innerHTML="";' + 'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' + 'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' + 'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' + 'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' + '.catch(function(e){line(String(e),"error")})})();' + ''; } function htmlDoc(code) { if (/<!doctype|]/i.test(code)) { return code; } return 'body{font-family:Arial,sans-serif;padding:16px}' + code + ''; } function buildDoc(lang, code) { if (lang === 'javascript') { return javascriptDoc(code); } if (lang === 'python') { return pythonDoc(code); } return htmlDoc(code); } function langOf(box) { var l = (box.getAttribute('data-lang') || 'html').toLowerCase(); return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html'; } function ensure(parent, selector, make) { var el = parent.querySelector(selector); if (!el) { el = make(); parent.appendChild(el); } return el; } function element(tag, className, text) { var e = document.createElement(tag); if (className) { e.className = className; } if (text) { e.textContent = text; } return e; } function setup(box) { if (box.getAttribute('data-pg-ready')) { return; } var lang = langOf(box); var editor = box.querySelector('.editor-panel'); var textarea = box.querySelector('textarea'); if (!editor || !textarea) { return; } box.setAttribute('data-pg-ready', '1'); box.setAttribute('data-pg-lang', lang); var preview = ensure(box, '.preview-panel', function () { var p = element('div', 'preview-panel'); var h = element('div', 'panel-header'); h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output')); p.appendChild(h); return p; }); var frame = preview.querySelector('iframe'); if (!frame) { frame = document.createElement('iframe'); preview.appendChild(frame); } frame.setAttribute('sandbox', 'allow-scripts'); frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output'); frame.setAttribute('loading', 'lazy'); frame.setAttribute('referrerpolicy', 'no-referrer'); textarea.setAttribute('spellcheck', 'false'); textarea.setAttribute('aria-label', 'Code editor'); var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); }); var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run')); var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset')); run.type = 'button'; reset.type = 'button'; var initial = textarea.value; var live = lang === 'html' || lang === 'css'; var timer = null; function render() { if (timer) { clearTimeout(timer); timer = null; } frame.srcdoc = buildDoc(lang, textarea.value); } run.addEventListener('click', render); reset.addEventListener('click', function () { textarea.value = initial; if (live) { render(); } else { frame.srcdoc = emptyDoc(); } }); textarea.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); } }); if (live) { textarea.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(render, AUTO_RUN_DELAY); }); render(); } else { frame.srcdoc = emptyDoc(); } } function emptyDoc() { return '' + OUTPUT_STYLE + '
Press Run (or Ctrl+Enter) to see the output.
'; } function scan(root) { var boxes = (root || document).querySelectorAll('.editor-container'); for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); } } window.__pgPlayground = { scan: scan, buildDoc: buildDoc }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); } else { scan(document); } })();

In simple terms

APIs: How Apps Talk to Each Other

When you open a weather app and it shows you today's temperature - how does it know? It didn't guess. It asked a weather service for that data using something called an API.

API stands for Application Programming Interface. In plain English: it's a way for one program to ask another program for information or to do something.

Think of it like this: An API is like a waiter at a restaurant. You (your app) sit at a table. The kitchen (another service) has the food (data). You don't walk into the kitchen yourself - you tell the waiter (API) what you want, and the waiter brings it back to you.
  • Weather apps use weather APIs to get temperature, rain, and wind data
  • Google Maps uses APIs to get traffic and directions
  • Payment apps use Stripe or PayPal APIs to process money
  • Login with Google uses Google's API to check who you are

As a Python developer, you'll use APIs constantly to pull real data into your programs.

Deep dive

How APIs Actually Work

The Request-Response Cycle

Every API interaction has two parts:

  1. Request - you send a message to the API asking for something
  2. Response - the API sends back an answer

This happens over the internet using URLs - just like how your browser loads a webpage, but instead of HTML, you get back data (usually in JSON format).

A Real Example

This URL fetches earthquake data from the US Geological Survey API:

https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson

If you paste that in your browser, you'll see raw earthquake data. Your Python program can do the same thing - automatically.

HTTP Status Codes

When an API responds, it includes a status code:

  • 200 - OK, everything worked
  • 404 - Not Found (you asked for something that doesn't exist)
  • 401 - Unauthorized (you need an API key)
  • 500 - Server Error (something broke on their end)
API Keys: Many APIs require you to sign up and get a key - like a password that identifies you. Some APIs are free with no key required. We'll start with free, keyless APIs so you can practise immediately.

REST APIs

The most common type of API you'll use is called a REST API. It uses standard web URLs to request data. You send a GET request to a URL, and it returns JSON data back.

# Concept  -  you'll write this in the next lesson:
# GET https://api.example.com/users/123
# Response: {"id": 123, "name": "Alice", "email": "[email protected]"}

Challenge

Your Task

Before writing any code, let's explore an API in your browser:

  1. Open your browser and go to this URL (a free, no-key-needed API):
https://jsonplaceholder.typicode.com/users/1
  1. You should see JSON data for a fake user - name, email, address, etc.
  2. Now try changing the 1 at the end to 2, 3, or 10 - each number gives you a different user
  3. Try this URL too - it returns a list of posts:
https://jsonplaceholder.typicode.com/posts

You just used an API! In the next lesson, you'll do the same thing from Python code.

Summary

Key Points

  • An API lets programs talk to each other over the internet
  • You send a request to a URL, you get back a response (usually JSON)
  • Status code 200 means success; 404 means not found
  • Many APIs require an API key (like a password); some are free with no key
  • REST APIs use URLs - you already know how to read URLs, so you're halfway there

In simple terms

Python Can Browse the Internet Too

Just like your browser fetches web pages, Python can fetch data from the internet. It does this using a library called requests.

The requests library is Python's most popular tool for working with APIs. It makes fetching data from the internet as simple as one line of code.

Think of it like this: The requests library is like your browser, but for your Python program. Instead of showing you a webpage, it hands the data directly to your code.
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users/1")
print(response.status_code)   # 200 = success
print(response.json())        # the actual data

That's it. Three lines to fetch real data from the internet.

Deep dive

Installing and Using requests

Step 1: Install requests

Open your terminal (inside VS Code or standalone) and run:

pip install requests

You only need to do this once. pip is Python's package installer - it downloads libraries from the internet.

On Mac/Linux you may need to use pip3 install requests instead.

Making a GET Request

import requests

url = "https://jsonplaceholder.typicode.com/users/1"
response = requests.get(url)

print(response.status_code)  # Should print 200

Reading the Response

import requests

response = requests.get("https://jsonplaceholder.typicode.com/users/1")

# Get the data as a Python dictionary
data = response.json()

print(data["name"])    # Leanne Graham
print(data["email"])   # [email protected]
print(data["phone"])   # 1-770-736-8031 x56442

Checking for Errors

Always check if the request succeeded before using the data:

import requests

response = requests.get("https://jsonplaceholder.typicode.com/users/1")

if response.status_code == 200:
    data = response.json()
    print("Got data:", data["name"])
else:
    print("Something went wrong:", response.status_code)
Good habit: Always check the status code. Networks fail, APIs go down, URLs change. Checking the status code means your program won't crash silently.

Fetching a List

import requests

response = requests.get("https://jsonplaceholder.typicode.com/users")
users = response.json()  # This is a list of 10 users

for user in users:
    print(user["name"], "-", user["email"])

Challenge

Your Task

Create a file called api_practice.py and write a program that:

  1. Installs the requests library (run pip install requests in terminal first)
  2. Fetches all 10 fake users from: https://jsonplaceholder.typicode.com/users
  3. Loops through the list and prints each user's name and company name

Hint: each user has a "company" key, and inside it a "name" key. So: user["company"]["name"]

Expected output (first 2 lines):

Leanne Graham - Romaguera-Crona
Ervin Howell - Deckow-Crist

Summary

Key Points

  • Install requests once with pip install requests
  • requests.get(url) sends a GET request and returns a response object
  • response.status_code tells you if it worked (200 = success)
  • response.json() converts the response into a Python dict or list
  • Always check the status code before using the data

In simple terms

JSON: The Language APIs Speak

When APIs send you data, it almost always arrives in a format called JSON (JavaScript Object Notation). Don't worry about the name - it's just a way of writing data that every programming language understands.

Think of it like this: JSON is like a universal translator. The weather API might be written in Java, your Python program is written in Python, but they both speak JSON. It's the common language that lets them understand each other.

Here's what JSON looks like:

{
    "name": "Alice",
    "age": 25,
    "city": "Nairobi",
    "hobbies": ["reading", "coding", "cooking"],
    "address": {
        "street": "123 Main St",
        "country": "Kenya"
    }
}

Looks familiar? That's because JSON looks almost exactly like a Python dictionary - and Python can convert between the two instantly.

Deep dive

JSON in Python

JSON to Python Dictionary

When you call response.json(), Python automatically converts the JSON into a Python dictionary or list - so you can work with it using everything you already know.

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
post = response.json()

# post is now a regular Python dictionary
print(post["title"])
print(post["body"])
print(post["userId"])

Nested JSON

JSON data is often nested (dictionaries inside dictionaries, or lists of dictionaries):

import requests

response = requests.get("https://jsonplaceholder.typicode.com/users/1")
user = response.json()

# Accessing nested data
print(user["name"])
print(user["address"]["city"])         # nested dict
print(user["address"]["geo"]["lat"])   # double nested

JSON Lists

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts")
posts = response.json()   # This is a list of 100 posts

print(f"Total posts: {len(posts)}")

# Show first 5
for post in posts[:5]:
    print(f"Post {post['id']}: {post['title']}")

The json Module (for Files)

Python also has a built-in json module for reading/writing JSON files:

import json

# Save data to a JSON file
data = {"name": "Alice", "score": 95}
with open("data.json", "w") as f:
    json.dump(data, f)

# Read it back
with open("data.json", "r") as f:
    loaded = json.load(f)

print(loaded["name"])   # Alice
json.dump() - writes Python dict to a JSON file
json.load() - reads a JSON file into a Python dict
json.dumps() - converts dict to a JSON string
json.loads() - converts a JSON string to a dict

Challenge

Your Task

Create json_practice.py and write a program that:

  1. Fetches all posts from: https://jsonplaceholder.typicode.com/posts
  2. Filters to only show posts where userId == 1 (there should be 10)
  3. For each of those posts, print the id and title
  4. At the end, print how many posts user 1 has written

Bonus: Save the filtered posts to a file called user1_posts.json using the json module.

Summary

Key Points

  • JSON is the standard data format for APIs - it looks like Python dictionaries
  • response.json() converts API response to a Python dict or list automatically
  • Access nested data with chained keys: data["address"]["city"]
  • Use Python list operations (for, len(), slicing) to work with JSON lists
  • Use the json module to save/load JSON files: json.dump() and json.load()

In simple terms

Let's Build Something Real

You now know enough to build a real, useful Python program that fetches live data from the internet.

We're going to build a weather app - one that tells you the current temperature and weather conditions for any city. And the best part? The API we'll use is completely free and requires no sign-up.

Think of it like this: You're going to write a Python program that does exactly what the weather app on your phone does - except you built it yourself, and you understand every line.

We'll use the Open-Meteo API which gives free weather data, and the Nominatim (OpenStreetMap) API to convert a city name into coordinates.

Deep dive

Building the Weather App Step by Step

Step 1: Get City Coordinates

Weather APIs work with latitude and longitude, not city names. So first we convert the city name to coordinates:

import requests

def get_coordinates(city_name):
    url = "https://nominatim.openstreetmap.org/search"
    params = {
        "q": city_name,
        "format": "json",
        "limit": 1
    }
    headers = {"User-Agent": "MyWeatherApp/1.0"}
    response = requests.get(url, params=params, headers=headers)

    if response.status_code == 200:
        results = response.json()
        if results:
            lat = results[0]["lat"]
            lon = results[0]["lon"]
            return float(lat), float(lon)
    return None, None

Step 2: Get the Weather

def get_weather(lat, lon):
    url = "https://api.open-meteo.com/v1/forecast"
    params = {
        "latitude": lat,
        "longitude": lon,
        "current": "temperature_2m,weathercode,windspeed_10m",
        "temperature_unit": "celsius"
    }
    response = requests.get(url, params=params)

    if response.status_code == 200:
        return response.json()
    return None

Step 3: Decode the Weather Code

def weather_description(code):
    descriptions = {
        0: "Clear sky",
        1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
        45: "Foggy", 48: "Depositing rime fog",
        51: "Light drizzle", 53: "Moderate drizzle",
        61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain",
        71: "Slight snow", 73: "Moderate snow", 75: "Heavy snow",
        80: "Slight showers", 81: "Moderate showers", 82: "Heavy showers",
        95: "Thunderstorm",
    }
    return descriptions.get(code, f"Unknown (code {code})")

Step 4: Put It All Together

city = input("Enter a city name: ")

lat, lon = get_coordinates(city)
if lat is None:
    print(f"Could not find coordinates for '{city}'")
else:
    data = get_weather(lat, lon)
    if data:
        current = data["current"]
        temp = current["temperature_2m"]
        wind = current["windspeed_10m"]
        code = current["weathercode"]
        desc = weather_description(code)

        print(f"\nWeather in {city}:")
        print(f"  Condition:   {desc}")
        print(f"  Temperature: {temp}°C")
        print(f"  Wind speed:  {wind} km/h")
    else:
        print("Could not fetch weather data.")
params= is a neat feature of requests - instead of adding query parameters manually to the URL, you pass them as a dictionary and requests builds the URL for you.

Challenge

Your Task

Create weather_app.py and build the complete weather app by combining all the functions from this lesson.

  1. Put all three functions in one file: get_coordinates(), get_weather(), weather_description()
  2. Ask the user for a city name using input()
  3. Display the weather report
  4. Test it with at least 3 different cities (try Nairobi, London, Tokyo)

Bonus: Add a loop so the user can check weather for multiple cities without restarting the program. Stop when they type "quit".

Summary

What You've Built

  • A real weather app that fetches live data from the internet
  • You used two different APIs together - one for coordinates, one for weather
  • You learned how to pass params= to requests for cleaner URLs
  • You used functions to organise your API code into reusable pieces
  • This is exactly how professional developers build API-powered apps

In simple terms

Real Data About Real Developers

GitHub is where the world's code lives. It has a powerful free API that lets you explore repositories, users, commits, and more - all with Python.

The GitHub API is a great example of a real-world API: it has public data (no key needed) and also private data (needs a key). We'll start with public data.

Think of it like this: GitHub is like a library for code. The GitHub API is the librarian. You can ask the librarian to find any public book (repository) - who wrote it, how popular it is, what changes were made. All without entering the library yourself.

Deep dive

Working with the GitHub API

Searching Repositories

import requests

def search_repos(language, sort="stars", count=5):
    url = "https://api.github.com/search/repositories"
    params = {
        "q": f"language:{language}",
        "sort": sort,
        "per_page": count
    }
    headers = {"Accept": "application/vnd.github.v3+json"}
    response = requests.get(url, params=params, headers=headers)
    return response.json()

results = search_repos("python", sort="stars", count=5)
for repo in results["items"]:
    print(f"{repo['full_name']}")
    print(f"  Stars: {repo['stargazers_count']:,}")
    print(f"  Description: {repo['description']}")
    print()

Getting a User's Profile

import requests

def get_github_user(username):
    url = f"https://api.github.com/users/{username}"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    return None

user = get_github_user("torvalds")  # Creator of Linux
if user:
    print(f"Name: {user['name']}")
    print(f"Public repos: {user['public_repos']}")
    print(f"Followers: {user['followers']:,}")
    print(f"Bio: {user['bio']}")

Listing a User's Repositories

import requests

def get_user_repos(username):
    url = f"https://api.github.com/users/{username}/repos"
    params = {"sort": "updated", "per_page": 10}
    response = requests.get(url, params=params)
    return response.json()

repos = get_user_repos("torvalds")
for repo in repos:
    print(f"{repo['name']} - {repo['description']}")
Rate Limiting: The GitHub API allows 60 requests per hour without authentication. If you need more, create a free GitHub account and use a Personal Access Token. Add it to your headers: "Authorization": "token YOUR_TOKEN"

Checking Rate Limits

import requests

response = requests.get("https://api.github.com/rate_limit")
limits = response.json()
print(f"Requests remaining: {limits['rate']['remaining']}")
print(f"Resets at: {limits['rate']['reset']}")

Challenge

Your Task

Create github_explorer.py that builds a mini GitHub explorer:

  1. Ask the user to enter a GitHub username
  2. Fetch and display that user's profile (name, followers, public repos, bio)
  3. Fetch and display their 5 most recently updated repositories (name + description)
  4. Handle the case where the user doesn't exist (status code 404)

Bonus: After showing a user's repos, ask if they want to look up another user. Loop until they type "quit".

Try it with these usernames: torvalds, gvanrossum (creator of Python), github

Summary

What You've Learned

  • The GitHub API exposes real data about users and repositories
  • You can build URL paths dynamically: f"https://api.github.com/users/{username}"
  • Always handle different status codes (200, 404, etc.) gracefully
  • The :, format specifier adds comma separators to large numbers
  • You now know enough about APIs to use almost any REST API in the world

In simple terms

Django: Build Websites with Python

So far, everything you've built with Python runs in the terminal. But what if you want to build a real website - with pages people can visit in their browser?

That's what Django is for. Django is a Python framework that handles all the hard parts of building a website for you - so you can focus on writing the features that matter.

Think of it like this: Building a website from scratch is like building a house starting from making your own bricks. Django is like using pre-built walls, floors, and a roof - you just arrange them and add your own rooms (features). It handles the repetitive stuff so you can focus on what makes your site unique.
  • Django handles URL routing - deciding which code runs when someone visits a URL
  • Django handles databases - storing and retrieving data without writing raw SQL
  • Django handles user authentication - login, logout, registration out of the box
  • Django handles security - protection against common hacking techniques, built in

Companies like Instagram, Pinterest, and Disqus have been built with Django.

Deep dive

How Django Works: The MVT Pattern

Django follows a pattern called MVT: Model, View, Template. Every Django website is built around these three pieces:

Model - Your Data

A Model defines what data you store. For a blog, you might have a Post model with a title, content, and date. Django automatically creates the database table for you.

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

View - Your Logic

A View is a Python function that receives a web request and returns a response. It fetches data from the model and decides what to send back.

def home(request):
    posts = Post.objects.all()
    return render(request, "home.html", {"posts": posts})

Template - Your HTML

A Template is an HTML file with special tags that let you show dynamic data:

{% for post in posts %}
  <h2>{{ post.title }}</h2>
  <p>{{ post.content }}</p>
{% endfor %}

The Full Cycle

  1. User visits /posts/ in their browser
  2. Django checks its URL patterns and calls the home view
  3. The view fetches posts from the database using the Model
  4. The view renders the Template with the posts data
  5. Django sends the finished HTML back to the user's browser
Why MVT and not MVC? Django calls it MVT (Model-View-Template) but it's similar to the popular MVC (Model-View-Controller) pattern. The "Controller" part is handled automatically by Django's URL dispatcher.

Challenge

Think Through It

Before we start coding Django, think about a website you'd like to build. Answer these questions in a text file or notebook:

  1. What is your website about? (a blog, a to-do list, a shop, a news site...)
  2. What data does it need to store? List 2-3 things (e.g. for a blog: posts, authors, comments)
  3. What pages will it have? (home page, detail page, add new item page...)

Keep these answers - you'll use them as a guide when we build your first Django project in the next lesson!

Summary

Key Points

  • Django is a Python web framework - it builds the foundation of a website for you
  • It follows the MVT pattern: Model (data), View (logic), Template (HTML)
  • Django handles routing, databases, authentication, and security automatically
  • Used by Instagram, Pinterest, and many other large websites
  • Next: install Django and create your first project

In simple terms

From Zero to a Running Website in Minutes

Setting up Django involves just a few commands in the terminal. By the end of this lesson, you'll have a working website running on your computer - even if it's just a basic one.

Think of it like this: Starting a Django project is like setting up a new restaurant space. You rent the building (create the project), set up the kitchen layout (configure settings), and then you're ready to start cooking (building features).

Here's what we'll do:

  1. Install Django with pip
  2. Create a new Django project
  3. Run the development server
  4. Create your first Django app

Deep dive

Setting Up Django Step by Step

Step 1: Create a Virtual Environment

A virtual environment keeps your project's dependencies separate from other Python projects:

# In your terminal, navigate to where you want your project
cd Desktop

# Create the virtual environment
python -m venv mysite-env

# Activate it:
# On Windows:
mysite-env\Scripts\activate
# On Mac/Linux:
source mysite-env/bin/activate

# Your terminal prompt should now show (mysite-env) at the start
Why virtual environments? Imagine two projects - one needs Django version 3, another needs Django version 4. Without virtual environments, they'd conflict. With them, each project has its own isolated set of packages.

Step 2: Install Django

pip install django

Verify it installed:

python -m django --version

Step 3: Create a New Project

django-admin startproject mysite

This creates a mysite/ folder with this structure:

mysite/
    manage.py          ← your control panel
    mysite/
        settings.py    ← project configuration
        urls.py        ← URL patterns
        wsgi.py        ← for deployment
        asgi.py        ← for async deployment

Step 4: Run the Development Server

cd mysite
python manage.py runserver

Open your browser and go to http://127.0.0.1:8000 - you should see a Django welcome page! Your first website is running!

Press Ctrl+C to stop the server.

Step 5: Create Your First App

In Django, a "project" is the whole website. An "app" is one feature or section of the website (like a blog, or a store):

python manage.py startapp blog

Now register it in mysite/settings.py:

INSTALLED_APPS = [
    ...
    'blog',    # Add this line
]

Challenge

Your Task

  1. Create a virtual environment called django-env
  2. Activate it
  3. Install Django
  4. Create a Django project called mysite
  5. Run the development server
  6. Open http://127.0.0.1:8000 in your browser and confirm you see the Django welcome page
  7. Stop the server (Ctrl+C) and create an app called blog
  8. Add 'blog' to INSTALLED_APPS in settings.py

If you see the Django rocket launch page, congratulations - you've got a Django project running on your machine!

Summary

Key Points

  • Always use a virtual environment for Django projects - it keeps dependencies clean
  • django-admin startproject name creates a new project
  • python manage.py runserver starts your local development server at port 8000
  • python manage.py startapp name creates a new app inside your project
  • Register new apps in settings.py under INSTALLED_APPS

In simple terms

Your Database, Written in Python

Every website needs to store data - blog posts, user accounts, products. In Django, you define your data using Models - Python classes that Django automatically turns into database tables.

You never have to write SQL. Django does it for you.

Think of it like this: A Model is like filling out a form that says "I want a table called Post with columns for title, content, and date." Django takes that form, creates the table, and gives you tools to add, read, update, and delete rows - all in Python.
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Those 5 lines of Python create a full database table with 4 columns (Django adds an id column automatically).

Deep dive

Creating and Using Models

Common Field Types

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)      # Short text (up to 200 chars)
    content = models.TextField()                  # Long text (no limit)
    author = models.CharField(max_length=100)     # Short text
    published = models.BooleanField(default=False) # True/False
    views = models.IntegerField(default=0)         # Whole number
    price = models.DecimalField(max_digits=8, decimal_places=2)  # Money
    created_at = models.DateTimeField(auto_now_add=True)  # Set once on create
    updated_at = models.DateTimeField(auto_now=True)      # Updates every save
    image = models.ImageField(upload_to='images/')  # File upload

    def __str__(self):
        return self.title

Running Migrations

After defining a model, you need to tell Django to create the database table:

# Step 1: Create migration files (Django figures out what SQL to run)
python manage.py makemigrations

# Step 2: Apply the migrations (actually creates the table)
python manage.py migrate
Always run both commands whenever you change a model - add a field, remove a field, change a field type. Django will calculate exactly what database changes are needed.

Using the Django Admin

Django has a built-in admin panel where you can add/edit/delete data. First, create a superuser:

python manage.py createsuperuser

Then register your model in blog/admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Run the server, go to http://127.0.0.1:8000/admin, log in, and you can manage your data through a nice web interface - for free, without writing any code!

Querying the Database

from blog.models import Post

# Get all posts
posts = Post.objects.all()

# Get one post by id
post = Post.objects.get(id=1)

# Filter posts
recent = Post.objects.filter(published=True)

# Order posts
ordered = Post.objects.order_by('-created_at')  # newest first

# Count
total = Post.objects.count()

# Create a new post
Post.objects.create(title="My First Post", content="Hello world!")

Challenge

Your Task

In your Django project's blog/models.py:

  1. Create a Post model with these fields:
    • title - CharField (max 200 characters)
    • content - TextField
    • author - CharField (max 100 characters)
    • created_at - DateTimeField (auto_now_add=True)
    • published - BooleanField (default=False)
  2. Add a __str__ method that returns the title
  3. Run makemigrations and migrate
  4. Register the model in admin.py
  5. Create a superuser and log into the admin at /admin
  6. Add 3 blog posts through the admin interface

Summary

Key Points

  • A Django Model is a Python class that becomes a database table
  • Common field types: CharField, TextField, IntegerField, BooleanField, DateTimeField
  • Always run makemigrations then migrate after changing models
  • The Django admin gives you a free web interface to manage your data
  • Query your data with Model.objects.all(), .get(), .filter(), .create()

In simple terms

Connecting URLs to Code

Right now your Django project doesn't show any real pages - just the welcome screen. To build real pages, you need two things: Views and URLs.

  • A URL pattern says: "when someone visits /blog/, call this function"
  • A View is the function that handles the request and returns a response
Think of it like this: URLs are like the address on an envelope. Views are the people who open and respond to those envelopes. When a letter arrives at /blog/, Django looks up who handles that address (the URL pattern), then delivers it to the right person (the view function).

Deep dive

Building Your First Real Page

Step 1: Write the View

In blog/views.py:

from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.filter(published=True).order_by('-created_at')
    return render(request, 'blog/post_list.html', {'posts': posts})

def post_detail(request, post_id):
    post = Post.objects.get(id=post_id)
    return render(request, 'blog/post_detail.html', {'post': post})

Step 2: Create URL Patterns for Your App

Create a new file blog/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('post/<int:post_id>/', views.post_detail, name='post_detail'),
]

Step 3: Include Your App URLs in the Project

Edit mysite/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),  # Add this line
]

Now /blog/ will show all posts, and /blog/post/1/ will show post #1.

URL Parameters

<int:post_id> in the URL pattern captures a number from the URL and passes it to the view as post_id. You can also use <str:slug> for text.

The name= parameter in URL patterns lets you reference URLs by name instead of hardcoding the path. Use {% url 'post_list' %} in templates. This way, if you change the URL path, you don't have to update every link.

Returning Simple Responses

from django.http import HttpResponse

def simple_view(request):
    return HttpResponse("<h1>Hello, World!</h1>")

Challenge

Your Task

  1. In blog/views.py, create a post_list view that fetches all published posts
  2. Create blog/urls.py with a URL pattern for the post list at '' (empty = root of /blog/)
  3. Include your blog URLs in the main mysite/urls.py at the path 'blog/'
  4. Run the server and visit http://127.0.0.1:8000/blog/ - you should get a TemplateDoesNotExist error (that's fine! It means the view is working, we just haven't created the template yet)
  5. Bonus: Also create a post_detail view that accepts a post ID from the URL

A TemplateDoesNotExist error is progress - it means Django found your view and tried to render the template. We'll create templates in the next lesson.

Summary

Key Points

  • A View is a Python function that receives a request and returns a response
  • URL patterns connect URL paths to view functions using path()
  • Capture URL parameters with <int:name> or <str:name>
  • Use include() in the main urls.py to delegate to app-level URL files
  • Name your URL patterns with name= so templates can reference them by name

In simple terms

Templates: Where Python Meets HTML

A template is an HTML file with special Django tags that let you insert dynamic data. Instead of writing a separate HTML page for every blog post, you write one template, and Django fills it in with the right data each time.

Think of it like this: A template is like a letter template. Instead of writing "Dear Alice, your order of shoes has arrived" and "Dear Bob, your order of a book has arrived" separately - you write one template: "Dear [NAME], your order of [ITEM] has arrived." Then you fill it in for each person automatically.

Django templates use two special syntaxes:

  • {{ variable }} - displays a value
  • {% tag %} - runs logic (if, for, etc.)

Deep dive

Creating Django Templates

Step 1: Create the Template Folder Structure

blog/
    templates/
        blog/
            post_list.html
            post_detail.html

Step 2: The Post List Template

Create blog/templates/blog/post_list.html:

<!DOCTYPE html>
<html>
<head>
    <title>My Blog</title>
</head>
<body>
    <h1>My Blog</h1>

    {% if posts %}
        {% for post in posts %}
            <article>
                <h2><a href="{% url 'post_detail' post.id %}">{{ post.title }}</a></h2>
                <p>By {{ post.author }} on {{ post.created_at|date:"d M Y" }}</p>
                <p>{{ post.content|truncatewords:30 }}</p>
            </article>
            <hr>
        {% endfor %}
    {% else %}
        <p>No posts yet!</p>
    {% endif %}
</body>
</html>

Step 3: The Post Detail Template

Create blog/templates/blog/post_detail.html:

<!DOCTYPE html>
<html>
<head><title>{{ post.title }}</title></head>
<body>
    <a href="{% url 'post_list' %}">← Back to all posts</a>
    <h1>{{ post.title }}</h1>
    <p>By {{ post.author }} | {{ post.created_at|date:"d M Y" }}</p>
    <div>{{ post.content|linebreaks }}</div>
</body>
</html>

Template Tags and Filters

{# This is a comment  -  not shown on the page #}

{% if user.is_authenticated %}Welcome, {{ user.username }}!{% endif %}

{% for item in items %}{{ forloop.counter }}. {{ item }}{% endfor %}

{{ post.content|truncatewords:50 }}   {# Show only first 50 words #}
{{ post.created_at|date:"d M Y" }}    {# Format date #}
{{ post.title|upper }}                 {# Uppercase #}
{{ post.content|linebreaks }}          {# Convert newlines to <br> and <p> #}

Template Inheritance (Base Template)

Instead of repeating the HTML structure in every template, create a base template:

{# base.html #}
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    <nav><a href="/">Home</a> | <a href="/blog/">Blog</a></nav>
    {% block content %}{% endblock %}
</body>
</html>

Then in other templates:

{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
    <h1>All Posts</h1>
    ...
{% endblock %}
Template inheritance is one of Django's most powerful features - write your navigation, header, and footer once in base.html, and every other page automatically gets them.

Challenge

Your Task

  1. Create the template folder structure: blog/templates/blog/
  2. Create post_list.html that loops through posts and shows title, author, date, and a snippet of content
  3. Create post_detail.html that shows a full post
  4. Use {% url %} to link the list items to their detail pages and add a "back" link
  5. Run the server and visit http://127.0.0.1:8000/blog/ - you should see your actual posts!
  6. Bonus: Create a base.html with navigation and have both templates extend it

Summary

Key Points

  • Templates are HTML files in app/templates/app/ folders
  • {{ variable }} displays data; {% tag %} runs logic
  • Filters transform data: |date, |truncatewords, |upper, |linebreaks
  • Use {% url 'name' %} to generate URLs from named URL patterns
  • Use template inheritance ({% extends %} / {% block %}) to avoid repeating HTML

In simple terms

Letting Users Add Data to Your Site

So far your blog can only show posts that you added through the admin panel. What if you want users to submit a contact form, write a comment, or create their own posts?

Django has a Forms system that makes this easy and safe. It handles:

  • Rendering the HTML form for you
  • Validating that the user filled it in correctly
  • Protecting against malicious input (CSRF attacks)
  • Saving the data to the database
Think of it like this: A Django Form is like a paper form at a doctor's office, but smarter. It checks that you filled in the required fields, that your date of birth is a real date, and that your phone number has the right number of digits - before the receptionist even looks at it.

Deep dive

Creating and Using Django Forms

Step 1: Create a Form

Create blog/forms.py:

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'content', 'author']
        widgets = {
            'title': forms.TextInput(attrs={'placeholder': 'Post title...'}),
            'content': forms.Textarea(attrs={'rows': 8}),
        }
ModelForm is magic - it automatically creates a form based on your model. You just specify which fields to include. No need to define each field again.

Step 2: Create the View

In blog/views.py:

from django.shortcuts import render, redirect
from .forms import PostForm

def create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save()
            return redirect('post_detail', post_id=post.id)
    else:
        form = PostForm()

    return render(request, 'blog/create_post.html', {'form': form})

This view pattern handles both showing the form (GET request) and processing it (POST request).

Step 3: Add the URL

In blog/urls.py:

path('new/', views.create_post, name='create_post'),

Step 4: Create the Template

Create blog/templates/blog/create_post.html:

<!DOCTYPE html>
<html>
<head><title>New Post</title></head>
<body>
    <h1>Write a New Post</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Publish</button>
    </form>
    <a href="{% url 'post_list' %}">Cancel</a>
</body>
</html>
{% csrf_token %} is mandatory inside every form. It adds a hidden security token that proves the form was submitted from your site and not by a hacker. Django will reject forms without it.

Form Validation

Django validates forms automatically. You can add custom rules:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'content', 'author']

    def clean_title(self):
        title = self.cleaned_data['title']
        if len(title) < 5:
            raise forms.ValidationError("Title must be at least 5 characters.")
        return title

Challenge

Your Task

  1. Create blog/forms.py with a PostForm ModelForm for the Post model
  2. Create a create_post view that shows the form on GET and saves on POST
  3. Add a URL pattern path('new/', ...) in your blog URLs
  4. Create the template with {% csrf_token %} and {{ form.as_p }}
  5. Add a "Write New Post" link on your post list page
  6. Test it: submit a new post and confirm it appears on the list

Bonus: Add an "Edit" button on the post detail page. Create an edit_post view that pre-fills the form with existing post data using PostForm(instance=post).

Summary

Key Points

  • ModelForm creates a form automatically from a model - just list the fields
  • Views handle both GET (show form) and POST (process form) requests
  • Always include {% csrf_token %} inside every HTML form
  • form.is_valid() validates all fields; form.save() saves to the database
  • redirect() sends the user to a different URL after successful form submission

In simple terms

Let Users Have Their Own Accounts

Almost every real website has user accounts - you log in, you have your own profile, and you can only see or edit your own data.

The great news: Django includes a full authentication system out of the box. Login, logout, password management - it's all already written for you. You just need to hook it up.

Think of it like this: Django's auth system is like a hotel key card system that's already installed in the building. You don't need to build the key card reader - you just register guests (users), give them a card (account), and the system knows who's allowed through which door (which pages they can access).

What Django gives you for free:

  • User model with username, email, password (hashed, not stored as plain text)
  • Login and logout views
  • Password change and password reset via email
  • @login_required decorator to protect pages
  • request.user to know who is currently logged in

Deep dive

Setting Up User Authentication

Step 1: Add Auth URLs

Django already has login/logout views. Just add them to your main urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
    path('accounts/', include('django.contrib.auth.urls')),  # Add this
]

This gives you these URLs for free: /accounts/login/, /accounts/logout/, /accounts/password_change/, etc.

Step 2: Create the Login Template

Create templates/registration/login.html (note: this goes in a top-level templates folder, not inside the app):

<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
    <h1>Login</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Login</button>
    </form>
    <p>Don''t have an account? <a href="{% url ''register'' %}">Register here</a></p>
</body>
</html>

Step 3: Configure Login Redirect

In settings.py, tell Django where to redirect after login:

LOGIN_REDIRECT_URL = '/blog/'
LOGOUT_REDIRECT_URL = '/blog/'

Step 4: Add Registration

Django doesn''t include a registration view, so we create one. In blog/views.py:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)  # Log them in automatically
            return redirect('post_list')
    else:
        form = UserCreationForm()
    return render(request, 'registration/register.html', {'form': form})

Step 5: Protect Views with @login_required

from django.contrib.auth.decorators import login_required

@login_required
def create_post(request):
    # Only logged-in users can reach this
    ...

Step 6: Show User Info in Templates

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
    <a href="{% url 'logout' %}">Logout</a>
{% else %}
    <a href="{% url 'login' %}">Login</a>
    <a href="{% url 'register' %}">Register</a>
{% endif %}

Linking Posts to Users

from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.ForeignKey(User,
    created_at = models.DateTimeField(auto_now_add=True)

Now each post belongs to a user. In your view, set the author automatically:

@login_required
def create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user  # Set the current user
            post.save()
            return redirect('post_detail', post_id=post.id)

Challenge

Your Final Challenge: A Complete Blog

Put everything together to build a complete blog website:

  1. Add django.contrib.auth.urls to your project URLs
  2. Create login and register templates
  3. Add LOGIN_REDIRECT_URL and LOGOUT_REDIRECT_URL to settings.py
  4. Create a register view and URL
  5. Protect the create_post view with @login_required
  6. Show "Welcome, username! | Logout" when logged in, and "Login | Register" when not
  7. Test the full flow: register → login → create post → logout

When this works, you have a real, fully functional blog website with user accounts - built entirely in Python. That is a huge milestone!

Summary

What You've Learned in the Django Section

  • Django is a Python framework for building complete websites
  • Models - define your data as Python classes, Django creates the database
  • Views - functions that handle requests and return responses
  • URLs - connect URL paths to view functions
  • Templates - HTML with Django tags for dynamic content
  • Forms - collect and validate user input safely
  • Auth - login, logout, registration, and page protection

You now have the skills to build a real website with Python. Keep building, keep learning - and remember, every professional developer started exactly where you are right now.

Questions while you work through the steps? The Course Coach (bottom right) knows this course inside out.
Browse more courses →
Ask the coachAI guide for this course