What we're doing today
By the end of this session, you will have written a program that keeps a row of items together, walks through them one at a time, and runs a saved routine you wrote yourself. Three new tools, all in one sitting. On their own, each one feels half-finished. Together, they look like real programs.
Take your time. Read each block, type it, run it.
Holding several things with one label
So far, every label we made held one thing. One name. One age. One mood. But life is rarely one thing. You don't go to the market to buy a tomato. You go with a shopping list — tomatoes, onions, garlic, pepper, oil — five items, one piece of paper.
Python has the same idea. It's called a list — a way to keep several things together under a single label, like a shopping list. You make one by putting the items between square brackets, separated by commas:
shopping = ["tomatoes", "onions", "garlic", "pepper", "oil"]That one line stores five pieces of text in a single labelled jar called shopping. From now on, when you write shopping, Python knows you mean all five of those items, in that order.
A list can hold numbers too:
ages = [27, 34, 19, 52]
prices = [3.50, 4.00, 12.75]To see what's inside, you print it the same way you printed anything else:
print(shopping)Python shows the whole thing: ['tomatoes', 'onions', 'garlic', 'pepper', 'oil'].
If you want to know how many items are in the list, there's a small built-in tool called len — short for length:
print(len(shopping))That shows 5.
Reaching for one item
Sometimes you don't want the whole list, just the first item. Python lets you point at one item by writing the list name, then square brackets with a number inside:
names = ["Ama", "Kofi", "Yaa", "Kwame"]
print(names[0])That shows Ama.
Read that carefully. We asked for names[0] and got the first name. Not the zeroth. The first. This is the one quirk of Python you have to swallow early: counting starts at zero, not at one. The first item is at position 0, the second at 1, the third at 2, and so on.
print(names[0]) # Ama
print(names[1]) # Kofi
print(names[2]) # Yaa
print(names[3]) # KwameIt feels wrong the first few times. It will stop feeling wrong by next week.
Doing the same thing for every item
Here's the question that makes a list useful. You have five items on your shopping list and you want to do something with each one. You don't want to write five separate lines of code. You want to say it once and have Python repeat it for every item.
That idea is called a loop — doing the same step for every item, one at a time. Like washing dishes from the sink. You don't write a separate plan for each plate. You have one routine — pick up a plate, wash it, rinse it, put it on the rack — and you do that for every plate until the sink is empty.
In Python, the tool for that is a for loop. Here's the simplest one:
shopping = ["tomatoes", "onions", "garlic"]
for item in shopping:
print(item)Run it. You'll see three lines: tomatoes, onions, garlic.
Let me unpack each piece.
for item in shopping:— read it like English. "For each item in the shopping list, do the following." Python takes each thing in the list, one at a time, and puts it in a temporary jar calleditem.itemis a name you picked. You could have called itthingorx. Pick a name that reads well.- The colon at the end —
:— tells Python "the next bit is the routine I want you to repeat." - The indented line underneath is the routine. That's what gets done for every item.
So Python takes "tomatoes", puts it in the jar called item, runs print(item), and shows tomatoes. Then it takes "onions", puts it in the same jar, runs the print again, shows onions. And so on, until the list is empty.
You can put more than one line inside the loop. As long as the lines are indented the same way, they all belong to the routine:
shopping = ["tomatoes", "onions", "garlic"]
for item in shopping:
print("Buy:", item)
print("Check the price before paying.")That routine runs once for every item on the list.
Adding things up as you go
One common use of a loop is adding numbers together. Say you have a list of prices and you want the total:
prices = [3.50, 4.00, 12.75]
total = 0
for price in prices:
total = total + price
print("Total:", total)Start a jar called total at 0. Then for every price in the list, add it on top of what's already in the jar. By the time the loop is done, total holds the sum of everything. This pattern — start at zero, build it up one item at a time — you'll use over and over.
A different kind of loop — keep going until told to stop
for loops are perfect when you already know what you're looping over. But sometimes you don't have a list. You just want to keep doing something until a condition changes. Like a queue at the bank. The teller doesn't know how many customers will come today. She just keeps serving the next person while there is someone in the queue. When the queue is empty, she stops.
That's what a while loop does. It keeps repeating its routine for as long as some condition is still true. Here's one that keeps asking the user for input until they type q to quit:
answer = ""
while answer != "q":
answer = input("Type something (or 'q' to quit): ")
print("You typed:", answer)Read the condition out loud: "while answer is not equal to q." Every time around, Python checks — is answer still not q? If yes, run the routine again. The moment the user types q, the condition is no longer true, and the loop ends.
One thing to be careful of. If the condition never becomes false, the loop runs forever and your program gets stuck. If that happens in Colab, go to Runtime → Interrupt execution and Python will stop. Everyone writes one of these in their first month. Just remember: every while loop needs something inside it that will eventually flip the condition.
Rule of thumb:
- Use
forwhen you know what you're looping over — a list. - Use
whilewhen you don't know how many times — you're waiting for something to change.
A small saved routine you can run again later
Last big idea for today.
Imagine you've written down a recipe for jollof rice. You wrote it once, on paper. From now on, whenever you want jollof, you don't figure out the steps from scratch — you pull out the recipe and follow it. The recipe is saved. It has a name. You can run it as many times as you want.
A function is exactly that — a small saved routine you can run again later, like a jollof rice recipe you wrote once and cook many times.
Here's a function that greets someone:
def greet(name):
print("Welcome,", name)Let me unpack each piece.
defis the keyword that tells Python "I'm about to define a new routine." Short for define.greetis the name you're giving it. Pick a name that says what the routine does — usually a verb.- The brackets after the name —
(name)— list the ingredients the routine needs. They're called parameters. Inside the routine,nameworks like any other labelled jar. - The colon, then the indented line, is the routine itself.
Writing the recipe doesn't cook anything. To actually run the routine, you have to call it by writing its name with the ingredient inside the brackets:
greet("Ama")
greet("Kofi")That runs the routine twice. First with name set to "Ama", then "Kofi". Two lines print.
A function can take more than one ingredient. Just separate them with commas:
def add_prices(price_one, price_two):
total = price_one + price_two
print("Total:", total)
add_prices(3.50, 4.00)That prints Total: 7.5. You wrote the recipe once. You can call it with any two prices, any time.
Putting all three together
Now let's combine everything. A list of names, a function that greets one person, and a loop that runs the function for everyone:
def greet(name):
print("Welcome,", name)
guests = ["Ama", "Kofi", "Yaa", "Kwame"]
for guest in guests:
greet(guest)Read it top to bottom. We wrote a routine called greet that welcomes one person. We made a list of four guests. The loop took each guest, one at a time, and called the routine on them. Four lines come out at the bottom.
That little program is the shape of most of what you'll write this term. Save a routine. Keep a list of things. Run the routine on every item in the list.
Your exercise
Open a fresh Colab cell and write a program that does this:
- Makes a list of at least four foods you like.
- Writes a function called
say_i_likethat takes one food name and prints a sentence likeI like jollof. - Uses a
forloop to call that function on every food in the list.
Output should look like:
I like jollof.
I like waakye.
I like banku.
I like kelewele.If you finish early, write a small while loop that keeps asking the user for a food and prints it back, stopping when they type q.
Common slip-ups
- Forgetting the colon. Both
foranddefneed a colon at the end.for item in shoppingwithout:will not work. - Forgetting to indent. Lines inside a loop or function need four spaces in front. Flush with the left margin, Python won't see them as part of the routine.
- Counting from one instead of zero.
names[1]is the second name. The first isnames[0]. - Writing the function but never calling it.
def greet(name):is just the recipe. Nothing happens until you writegreet("Ama")somewhere underneath. - A
whileloop with no way out. If nothing inside the loop changes the condition, it runs forever. Always check that something will eventually flip it to false.
Run the exercise and bring questions to the next session. You now have the three pieces that make up most real programs.