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.
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.
print is not return
A function that prints its answer looks right until you try to use the answer.
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
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.
- 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
categoriseof each.
Little by little, you're building something great.