Python Basics

Python Functions: def, Parameters and return

Write code once and reuse it everywhere. Define functions with parameters, default values and return values.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • Defining a function with def
  • Parameters, arguments and default values
  • Returning results
greet("Grace")
  1. 1"Grace"The argument goes in
  2. 2def greet(name):The body runs with name = "Grace"
  3. 3return f"Hello, {name}!"The result comes back

Input, work, output

The problem

The same steps often appear in many places: greeting a user, calculating tax, checking an email address. Copying the code means fixing a bug in every copy, and long programs become hard to read. A function writes the steps once and gives them a name.

Think of it like this

A function is like a coffee machine. You put something in (the beans and your choice), it does the same work every time, and hands you a result (the cup). You do not need to know how it works inside to use it, and you can use it as often as you like.

From a coffee machine to code
def greet(name, language="Python"):☕ Build the machine once
name🫘 What you put in
language="Python"⚙️ A setting with a default
return🥤 What comes out
greet("Grace")▶️ Press the button: use the machine
Define it once, use it many times with different inputs.
In one sentence

A function is a named block of code defined with def; it receives values through parameters and sends a result back with return.

Key points

  1. def greet(name, language="Python"): defines the function; nothing runs until it is called.
  2. greet("Grace") calls it: name becomes "Grace" and language keeps its default.
  3. return sends the finished text back to the caller instead of printing it inside the function.
  4. message = greet("Grace") stores the result, so it can be printed, saved or reused.

When should you use it?

  • Any step you repeat, such as formatting a price or validating input.
  • Splitting a long program into small named pieces that are easy to read and test.
  • Giving a calculation a name, so average(scores) explains what the code does.

When not to use it

  • A single line used once: wrapping it in a function adds noise.
  • Data and the actions on it always go together, such as an account and its deposits: a class may fit better.

Example code

Run code →
main.py
def greet(name, language="Python"):
    return f"Hello, {name}! Welcome to {language}."

message = greet("Grace")
print(message)
Get a Run button for this example

Result of running the code

Hello, Grace! Welcome to Python.

Code explanation

greet has a parameter name and a parameter language with the default value Python, so the call greet("Grace") only needs one argument. The function builds the text and returns it instead of printing it. Because the result comes back to the caller, message can be printed here, but it could just as well be saved to a file or shown in a web page.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in the Python compiler →

Python function syntax at a glance

def greet(name):Define a function with one parameter
return valueSend a value back (without return, the function returns None)
def greet(name="world"):Default value for a parameter
greet(name="Ada")Pass an argument by name
def total(*numbers):Accept any number of positional arguments as a tuple
def setup(**options):Accept any number of keyword arguments as a dictionary
return low, highReturn several values (as a tuple)
square = lambda x: x * xSmall one-expression function
def add(a: int, b: int) -> int:Type hints for parameters and the return value
"""Explain what the function does."""Docstring: the first line inside the function

Common mistakes with Python functions

A list as a default value

Default values are created once, so the same list is shared by every call. Use None and create the list inside.

Problem
def add_item(item, items=[]):
    items.append(item)
    return items

add_item("a")
print(add_item("b"))  # ['a', 'b']
Fix
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

add_item("a")
print(add_item("b"))  # ['b']

Printing instead of returning

print() only shows a value. If the caller needs the result, the function must return it.

Problem
def double(n):
    print(n * 2)

result = double(4)
print(result)  # 8, then None
Fix
def double(n):
    return n * 2

result = double(4)
print(result)  # 8

Calling a function before it is defined

Python runs a script from top to bottom, so the def must run before the first call.

Problem
print(square(3))  # NameError

def square(n):
    return n * n
Fix
def square(n):
    return n * n

print(square(3))  # 9

Frequently asked questions

What is the difference between a parameter and an argument?

A parameter is the name in the function definition, such as name in def greet(name). An argument is the value you pass when you call it, such as "Ada" in greet("Ada").

How do I return multiple values from a Python function?

Separate them with commas: return low, high. Python returns a tuple, which you can unpack with low, high = find_range(numbers).

What do *args and **kwargs mean?

*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. The names are a convention; the * and ** do the work.

When should I use a lambda?

Use a lambda for a short function you pass to another function, such as sorted(words, key=lambda w: len(w)). For anything longer, a normal def is easier to read and test.

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges