Defining your own functions

Functions, lesson 1 of 6

🧩 Functions, lesson 1 of 6

Defining your own functions

Name a block of code with def and run it whenever you need it.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

A function is a named, reusable block of code. You've already used plenty: print, len, input. Now you'll write your own with def:

def name(parameters):
    body

Defining a function only stores it. The body runs when you call it: name(...).

Example

Your first function

Delete both calls and run it: nothing is printed, because the body never runs.

Parameters are the input names in the def line. Arguments are the actual values you pass when calling. Arguments fill parameters in order.

Example

Parameters

Call greet with your own name.

Example

Receipt line

One function, many receipts. Change the format once and every line follows.

Quiz

What does this print?

Example

Missing an argument

The error message names the missing parameter: height.

Exercise

Birthday card

Define a function birthday_card(name, age) that prints two lines:

Happy birthday, Ana!
You are 30 today.

Then call it once to try it out.

Quiz

What happens when Python reaches a def statement?