Skip to main content
Text ready — video coming soon

Follow decisions and collections

Your first successful run gives us something to build on. In the terminal lesson, the function had one predictable result. A useful book lookup needs a decision: return a title that exists, and say when it does not.

We will follow that lookup in three Parts. First comes a choice, then the data to choose from, then a loop that visits it. Keep the question small as you read: which value does this line see, and what happens next?

You will practise:

  • Predicting which path a condition selects.
  • Choosing a collection for the question being asked.
  • Following a loop and spotting changes to shared data.

Part 1: Follow the choice Python makes​

An if statement runs its indented instructions when a condition is true:

def availability(lesson_count):
if lesson_count > 0:
return "Lessons are available"
else:
return "No lessons yet"

With lesson_count equal to 7, the comparison lesson_count > 0 is True. Python takes the first path and returns. With 0, the comparison is False, so it takes the else path.

elif, short for “else if”, adds another condition after the previous one was false. Order matters:

def count_label(count):
if count < 0:
return "Invalid count"
elif count == 0:
return "No lessons yet"
else:
return "Lessons are available"

Here == compares values. A single = assigns a value to a name; the two signs do different work. Other comparisons include != for unequal, <= for less than or equal and >= for greater than or equal.

Conditions can be combined. and requires both conditions to be truthy, or allows either, and not reverses a truth test. Zero, None, empty strings and empty collections are false in a condition; non-empty collections are true. This is called truthiness.

Do not confuse an empty value with every kind of missing value. if title: rejects both None and "". if title is None: checks specifically for None. Also, and and or can return one of their operands rather than a literal True or False. When the result is assigned to a name, inspect that value rather than assuming its type.

Part 2: Choose a collection for the question​

A collection holds several values. Imagine reading a university's merit list in row order, then looking up one application by its number. Those are different ways to access information. The Python collection type determines how you address values and which changes are allowed.

TypeExampleUseful property
List["Python and Roots", "Python and Branches"]An ordered sequence you can change
Tuple("title", "lessons")An ordered sequence whose slots cannot be reassigned
Dictionary{"title": "Python and Roots", "lessons": 7}Values addressed by keys
Set{"python", "mcp"}Unique members, without a dependable display order

Our chapter has two named facts, so a dictionary fits:

chapter = {"title": "Python and Roots", "lessons": 7}
print(chapter["title"])

"title" is a key. The value stored under it is "Python and Roots". The square brackets look up that key. A missing key raises KeyError, which can reveal a wrong assumption about the data.

If absence is expected, chapter.get("summary") returns None when the key is absent. You can give a default as the second argument. Choose that default carefully: a missing lesson count should not silently become a trustworthy zero unless the requirement says so.

A list is useful for chapters in reading order:

titles = ["Python and Roots", "Python and Branches"]
print(titles[0])
print(titles[-1])

Python starts sequence positions at zero. titles[0] selects the first title; titles[-1] selects the last. A slice selects a range: titles[0:1] contains the first item and stops before position 1. The result is another list.

Text supports indexing and slicing too: "Python"[0:2] produces "Py". A useful pair of string methods connects text and lists:

words = "Python and Roots".split()
print(words)
print(" ".join(words))

split() with no argument separates on whitespace and returns a list of words. " ".join(words) combines those strings with a space between them. The printed results are ['Python', 'and', 'Roots'] and Python and Roots. The separator belongs to the string before the dot.

len(titles) returns 2. "Python and Roots" in titles checks membership. A set is useful when only membership matters, for example whether a tag is allowed. {} creates an empty dictionary; use set() for an empty set. A one-item tuple needs a comma, as in ("python",).

Part 3: Visit the items without losing the order​

A loop repeats instructions. A for loop takes values from a collection one at a time:

titles = ["Python and Roots", "Python and Branches"]
for title in titles:
print(title)

The name title receives one item on each turn. Once that is clear, add the displayed counter:

titles = ["Python and Roots", "Python and Branches"]

for number, title in enumerate(titles, start=1):
print(f"{number}. {title}")

enumerate supplies a counter alongside each item. start=1 makes the displayed numbering begin at one, even though list positions begin at zero. The two names before in receive the counter and title for the current turn.

This prints the titles in list order. range(3) supplies 0, 1, 2; its ending value is excluded. A while loop instead repeats while its condition remains true. Check what changes that condition, or it may run forever.

Inside either loop, break ends the loop and continue moves to the next turn. A return inside a function leaves the function altogether, including its loop. A lookup can use that behaviour:

def find_title(titles, wanted):
for title in titles:
if title == wanted:
return title
return None

The final return None belongs after the loop. Put it inside the loop, and a non-matching first title would end the search before the second title was checked. Indentation changes behaviour, not only appearance.

Notice when two names share the same object​

An object is a value Python can refer to and operate on. Lists and dictionaries are objects whose contents can change; they are mutable. Assignment does not automatically make a separate copy:

original = ["Python and Roots"]
edited = original
edited.append("Python and Branches")
print(original)

The output contains both titles. original and edited refer to the same list. The append method adds an item to that list. This matters when an AI “prepares a response” by editing data that another part of a solution still needs unchanged.

original.copy() makes a new outer list. It is a shallow copy: inner objects are still shared.

original = [{"title": "Python and Roots"}]
edited = original.copy()
edited[0]["title"] = "Changed"
print(original[0]["title"])

This prints Changed. The outer list was copied; the inner dictionary was not. Before accepting a change, identify which object is modified and whether another name still refers to it. Avoid changing a collection while looping over that same collection unless the behaviour has been deliberately designed and checked.

The Python tutorial on control flow and data structures explain these mechanisms in detail.

Prove the result before accepting the loop​

Without looking back:

  1. Move return None inside find_title's loop. Which lookup now fails, and why?
  2. Why might a list be a better choice than a set for a book's reading order?
  3. What does copying the outer list fail to separate in the last example?
  4. Give the AI three checks for find_title: a first-item match, a later match and no match. Predict each result before it runs them.
Check the reasoning after your attempt

A lookup for a later title fails as soon as the first title does not match. A list preserves the intended reading order; a set is for membership and uniqueness. The inner dictionary remains shared after a shallow list copy. The three expected results are the matching title, the later matching title and None respectively.

Your code now has enough moving parts that a careless edit can change the answer. In the next root lesson, Git will show you exactly what changed, and an environment will show you which dependencies the code uses.