Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 149 ยท Functions

Functions

Learn to write your own Python functions with def. Pass in parameters, return results, document them with docstrings, and organize programs into small reusable pieces.

A function is a named block of code that does one job. You've been calling functions since your first line of Python: print(), len(), input() and sorted() are all functions someone else wrote. In this lesson you'll write your own.

Functions are how programs stay manageable as they grow. Instead of copying the same ten lines to three places, you write them once, give them a clear name and call that name wherever you need it. When something needs fixing, you fix it in one spot. And a well-named function makes the code that uses it read like a description of what's happening: send_reminder(user) explains itself.

Defining and calling a function

You create a function with the def keyword, a name, parentheses and a colon. The indented lines below form the function's body:

Python Your first function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Defining a function doesn't run it. def only creates the function and stores it under the name greet. The body runs each time you call the function by writing its name followed by parentheses. Without the parentheses, greet is just a reference to the function object, which is why the last line prints something like <function greet at 0x...>.

Function names follow the same rules as variables: lowercase words joined by underscores. Good names usually start with a verb, because functions do things: calculate_total, load_settings, is_valid_email.

Note: Python runs a file from top to bottom, so a function must be defined before the line that calls it runs. Calling greet() above its def raises a NameError.

Parameters and arguments

Functions get really useful when you can hand them data. Inside the parentheses of def, list parameters: names that will receive the values passed in. The values you pass when calling are called arguments:

Python Parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Arguments are matched to parameters by position ("notebook" goes to item, 2.40 to price) or by name, as in the last call. Naming arguments makes calls easier to read when there are several of them. Parameters behave like ordinary variables inside the body, and they exist only while the function runs.

Calling a function with the wrong number of arguments raises a TypeError that names the missing or extra argument. The next lesson, Arguments: Defaults, *args and **kwargs, shows how to make parameters optional and accept any number of values.

Returning a value

So far the functions have printed things. Most functions should instead return a result, so the caller can decide what to do with it: print it, store it, or pass it to another function. The return statement ends the function and sends a value back:

Python return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A call like to_fahrenheit(100) is an expression: Python runs the function and the call is replaced by the returned value. That's why you can use calls inside f-strings, list comprehensions and other calls.

Beginners often mix these up, so it's worth seeing the difference directly:

Python print is not return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A function without a return statement (or with a bare return) gives back None. print() shows a value to a human; return hands a value to the code that called the function. Prefer returning, and let the caller print. You'll explore early returns and returning several values in Return Values.

Docstrings

A docstring is a string literal placed as the very first statement in a function body. It describes what the function does, and Python stores it on the function so tools and the built-in help() can show it:

Python Docstrings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Conventions for docstrings:

  • Use triple double quotes, even for one line: """Return the total price."""
  • Start with a short summary sentence that says what the function does or returns.
  • For longer docstrings, add a blank line after the summary, then the details.

Docstring styles for longer functions

Once a function has several parameters, teams usually agree on one layout for describing them. Three layouts are common, and all of them are plain strings that Python stores unchanged:

  • reStructuredText (Sphinx) style uses field lines such as :param x: and :returns:.
  • Google style uses headed blocks called Args:, Returns: and Raises:.
  • NumPy style (numpydoc) uses underlined section titles (Parameters, Returns) followed by name : type lines. It is the favorite of the scientific Python libraries.

Pick one style per project and stick with it, because documentation tools parse them differently.

Python The same docstring in three styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The weight_kg: float and -> float parts are type hints. They document what types the function expects and returns. Python doesn't enforce them while running, but editors and checkers use them to catch mistakes early. You'll learn more in Type Hints.

Placeholder bodies with pass

A function body can't be empty. While you're sketching a program, you can use pass, a statement that does nothing, or ... (the Ellipsis) as a placeholder:

Python
def export_report(data):
    pass          # TODO: write this later

def send_email(to, subject):
    ...           # also valid, common in examples and type stubs

Both let the rest of your program run while you fill in the details later. Calling either function simply returns None.

Breaking a problem into functions

The real power of functions shows when you combine them. Each small function does one clear thing, and a higher-level function reads like a recipe:

Python Small functions working together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how grade() uses several return statements: the function stops at the first one that runs, so there's no need for elif chains. Each piece can be tested on its own, reused elsewhere and replaced without touching the others.

Tip: A good rule of thumb is "one function, one job". If you struggle to name a function without using "and", it probably does two things and should be split.

Functions are objects

In Python, a function is a value like any other. You can store it in a variable, put it in a list or dictionary, and pass it to another function:

Python Functions as values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This idea, treating functions as data, unlocks powerful patterns such as lambda functions, higher-order functions and decorators, which you'll learn later in this chapter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A script contains only def hi(): print("hi"). What does it print when you run it?

    def only creates the function. Its body runs when you call it with hi().
  2. 2. In def area(width, height):, what are width and height?

    Names listed in the definition are parameters. The values passed when calling, like area(3, 4), are arguments.
  3. 3. What does a function return if it has no return statement?

    Python functions without an explicit return value return None.
  4. 4. Given def double(n): print(n * 2), what is result after result = double(4)?

    The function prints 8 but doesn't return anything, so result is None. Use return n * 2 to get the value back.
  5. 5. Where must a docstring go?

    Only a string literal written as the first statement becomes the docstring, stored in __doc__ and shown by help().

Summary

  • Define a function with def name(parameters): and an indented body; call it with name(arguments).
  • Defining a function doesn't run it; each call runs the body again.
  • Parameters are the names in the definition; arguments are the values passed in, by position or by keyword.
  • return sends a value back and ends the function; without it, the function returns None.
  • A docstring (triple-quoted string as the first statement) documents the function for readers and help().
  • Use pass or ... as a placeholder body; split programs into small, well-named functions that do one job each.

Next: Arguments: Defaults, *args and **kwargs, where you'll make parameters optional and accept flexible numbers of arguments.