Functions, Modules and Errors

20 min read

A function is a small machine: you put something in, and a result comes out. In AI work, you write functions to build prompts, count tokens and clean up model answers. In this lesson you will write your own functions and borrow ready-made ones. You will also learn to read an error message without fear.

New words

function
A named recipe of code that you can use again and again.
parameter
A name in the function definition that waits for a value.
argument
The real value you give to a function when you call it.
return value
The answer that a function hands back to the code that called it.
module
A file of ready-made Python code that you borrow with import.
exception
The Python word for an error that you can catch and handle.
traceback
The report Python prints when an error stops your program.

What you will learn

  1. Why do you need functions?
  2. Write a function: def, parameters and return
  3. Default and keyword arguments
  4. Docstrings and scope
  5. Modules: borrow ready-made code
  6. Errors, tracebacks and try/except
  7. Raise your own errors
  8. Try it: the function machine
  9. Common mistakes
  10. Explain it to a friend
  11. Key takeaways

10 quiz questions at the end.

Start this lesson

The full lesson, with interactive demos and the quiz, opens after you sign in with Google. It is free.

All lessons · Back to the roadmap