Skip to content
Python for Data Science
Python Fundamentals 8 min read

Functions

Package logic into reusable functions — parameters, return values, defaults, scope, docstrings, and a first look at lambdas.

Download notebook Open Google ColabIn Colab: File → Upload notebook → pick the downloaded file.

You've already used plenty of functions — print(), len(), type() — without writing one yourself. In this lesson you'll learn to define your own: how inputs (parameters) and outputs (return values) work, why return is not the same as print, and how small, well-named functions turn a messy notebook into readable analysis.

Functions you already know

Python ships with dozens of built-in functions. Each one takes input, does a job, and hands back output:

Python — runs in your browser

That input → work → output pattern is the whole idea. Writing your own function just means defining what happens in the "work" step.

Defining your own: def and return

The anatomy of a function definition:

  • def starts the definition, followed by the name and parentheses
  • names inside the parentheses are parameters — placeholders for inputs
  • the indented body is the work
  • return sends a value back to whoever called the function
Python — runs in your browser

One definition, unlimited reuses — that's the payoff. A quick vocabulary note: parameters are the names in the definition (numbers); arguments are the actual values you pass when calling (student1).

return vs print

This distinction confuses every beginner, so let's nail it down. print displays a value on screen; return hands the value back so the rest of your program can use it. A function that only prints gives you nothing to work with:

Python — runs in your browser

A function without a return statement implicitly returns None. Rule of thumb: compute with return, display with print — and do the printing at the call site, not inside the function.

Default parameters and keyword arguments

Sometimes a parameter has a sensible usual value. Give it a default in the definition and callers can omit it. Here's a function that computes the n-th term of an arithmetic sequence (first term a, common difference d, term formula a + (n - 1) * d):

Python — runs in your browser

Keyword arguments (n=300) name the parameter at the call site. They make calls self-documenting and let you skip over defaults you don't want to change — you'll see them everywhere in pandas and scikit-learn, where functions have ten or more optional parameters.

Returning multiple values

return can send back several values separated by commas — Python bundles them into a tuple, and you can unpack them into separate variables on the receiving end:

Python — runs in your browser

Scope: what happens in a function stays in a function

Variables created inside a function are local — they exist only while the function runs, then vanish. This is a feature: functions can't accidentally trample your notebook's variables, and vice versa:

Python — runs in your browser

Functions can read outer variables, but relying on that makes code fragile. Best practice: pass everything a function needs in as parameters, and get everything out via return.

Docstrings: explain your function

A string right under the def line is a docstring — documentation baked into the function itself. Tools like help(), Jupyter's Shift+Tab, and your future teammates all read it:

Python — runs in your browser

Lambda: tiny anonymous functions

A lambda is a one-expression function with no name and no def. These two definitions behave identically:

Python — runs in your browser

For anything you'd call by name, prefer def — it gets a docstring and a readable name in error messages. Lambdas shine as short one-off arguments to functions like sorted, and later to pandas' .apply().

Functions compose

Well-factored code builds big functions out of small ones. If nth_term already computes a sequence's n-th term, a sum-of-sequence function can call it instead of repeating the formula. Small, single-purpose, well-named functions are the difference between a notebook you can revisit in six months and one you rewrite from scratch.

Check your understanding

5 questions · free
  1. Q1.What is the difference between a parameter and an argument?

  2. Q2.A function ends with print(result) instead of return result. What does x = my_func() store in x?

  3. Q3.Given def nth_term(seq, n=10), which call is INVALID?

  4. Q4.What does return mean, lowest, highest actually return?

  5. Q5.A variable created inside a function body is...

Exercise: Write a trimmed mean function

A trimmed mean is an average computed after cutting off the extremes — a robust statistic that outliers can't drag around. Write trimmed_mean(numbers, trim=0) that drops trim items from the front and back of the list, then averages what remains. For example, with [1, 2, 3, 4, 10] and trim=1 you average [2, 3, 4] and get 3.0. Verify: trimmed_mean([1, 2, 3, 4, 10]) → 4.0, trimmed_mean([1, 2, 3, 4, 10], 1) → 3.0, and trimmed_mean([1, 2, 3, 4, 4, 4, 4, 4, 10], 2) → 3.8. Include a docstring.

Next up: conditionals — teaching your code to make decisions with if, elif, and else.