Functions: def and return

What a function is; parameters, return, reuse.

1. What is this?

A function is a named block you can call. def greet(name): declares one with parameter name. The indented lines are its body. return sends a value back. Calling greet("Ava") runs the body with name = "Ava".

2. Why do we use it?

Reuse: one tested block, called with different inputs across your program.

3. Syntax breakdown

  • def greet(name):

    def starts a function definition. name is the parameter.

  •     return f"Hello, {name}"

    Body (indented). Builds and returns the greeting.

  • print(greet("Ava"))

    Calls the function, prints what it returned.

5. Common mistakes

  • Forgetting the colon after def ...():.
  • Forgetting return, so the call gives None.
  • Calling with the wrong number of arguments.

Practice task

Write double(n) returning n * 2, then print(double(7)).

Hint

def double(n): on line 1, indented return on line 2.

Try it below — tests run automatically when you press Run.

python

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. What keyword starts a function?

  2. 2. What does return do?

  3. 3. What is the value of a call with no return?

4. Example — edit and run

python

Output

Press Run to see output.

Expected output: Hello, Ava