Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

Functions: def and return

The if chain from lesson 5 sorts one ticket. To sort another, you would copy it. A function gives code a name so it can run again on different input.

Example
def categorise(text):
    text = text.lower()
    if "charged" in text or "refund" in text:
        return "billing"
    if "parcel" in text or "arrived" in text:
        return "shipping"
    return "other"

print(categorise("I was charged twice for one order"))
print(categorise("My parcel has not arrived"))
print(categorise("How do I change my password?"))

def starts a function. categorise is its name and text is its parameter: the name the input gets inside the function. The indented lines are what runs each time it is called.

return sends a value back to whoever called the function, and ends the function there. That is why the second if does not need an elif: once a return has run, nothing below it does.

A function that prints its answer looks right until you try to use the answer.

Example
def categorise_and_print(text):
    if "charged" in text:
        print("billing")

result = categorise_and_print("I was charged twice")
print("result is", result)

billing appears, but result is None. A function without return gives back None, so the program cannot use what was shown. Print for people; return for code.

A function that uses another

Example
def label(ticket):
    category = categorise(ticket["text"])
    return f"#{ticket['id']} {category}"

print(label({"id": 3, "text": "Can I get a refund for the blue mug?"}))

Once categorise exists, any later code can call it. Small functions that each do one thing are easier to test, and lesson 30 will test this exact one.

Try it yourself
  • Add a check for "password" that returns "account".
  • Call categorise() with nothing in the brackets and read the error.
  • Loop over a list of three ticket texts and print categorise of each.

Little by little, you're building something great.