FunctionsBeginner8 min32 / 63

Defining Functions

Learn how to create your own reusable functions in Python — the building blocks that keep your code clean, organized, and DRY.

Imagine you need to wrap a gift. You could tape, fold, and ribbon every single present from scratch each time — or you could follow a written set of steps once and repeat it whenever you need. Functions are exactly that: a named set of instructions you write once and use as many times as you want.

In Python, defining a function is how you teach the language a brand-new trick. Once taught, you can use that trick anywhere in your program with a single line.

See it in action

Visual walkthrough1 / 5
1

Write Once, Use Anywhere

A function is a named set of instructions you define once and run whenever you need. It's how you teach Python a brand-new trick — no copy-pasting required.

This idea has a name: DRY — Don't Repeat Yourself.

#Why Functions Matter

Without functions, you end up copying and pasting the same code over and over. That's a problem because:

  • It wastes time. More typing, more chances to make a mistake.
  • It breaks easily. If you need to fix something, you have to find every copy.
  • It's hard to read. A wall of repeated code doesn't tell you what it does.

Functions solve all three problems. This idea has a name in programming: DRY — Don't Repeat Yourself.

Think of it like

A Function Is Like a Recipe

A recipe has a name ("Chocolate Cake"), ingredients you pass in (flour, eggs, sugar), and steps to follow. You don't re-invent the recipe every time — you just call it by name and supply the ingredients. Python functions work the same way.

#Defining Your First Function

Use the keyword def (short for define) followed by a name, parentheses, and a colon. Everything indented underneath belongs to the function.

The simplest possible function — no inputs, just a task to perform.
def greet():
    print("Hello, world!")

greet()

Breaking down the syntax:

  • def — tells Python you are defining a function
  • greet — the name you choose (same rules as variable names)
  • () — the parentheses hold any inputs; empty means no inputs
  • : — the colon opens the function body
  • Indented lines — the body of the function (Python requires consistent indentation, typically 4 spaces)

#Calling a Function

Defining a function does not run it. Think of it as writing the recipe down. To actually bake the cake, you have to call the function — write its name followed by ().

Define once, call as many times as you like.
def greet():
    print("Hello, world!")

# Nothing has happened yet — we only defined the function.

greet()   # NOW it runs
greet()   # Run it again — for free!

#Parameters and Arguments

A function becomes much more useful when it can accept inputs. The variable names listed inside the parentheses in the def line are called parameters. The actual values you pass when calling the function are called arguments.

  • Parameter — the placeholder variable in the definition
  • Argument — the real value you supply when calling
The parameter `name` receives whatever argument you pass in.
def greet(name):
    print("Hello,", name)

greet("Alice")
greet("Bob")

You can have multiple parameters, separated by commas.

Two parameters: `a` and `b`. The caller decides what numbers to add.
def add(a, b):
    result = a + b
    print(a, "+", b, "=", result)

add(3, 5)
add(10, 20)

#Documenting with Docstrings

It's good practice to explain what your function does. Python has a built-in way to do this: a docstring — a triple-quoted string placed as the very first line of the function body.

Docstrings act as built-in documentation. Tools and teammates will thank you.
def greet(name):
    """Print a friendly greeting for the given name."""
    print("Hello,", name)

def add(a, b):
    """Return the sum of a and b."""
    result = a + b
    print(a, "+", b, "=", result)

greet("Priya")
Tip

Always Write a Docstring

Even one short sentence is enough. Future-you (reading the code in six months) will be very grateful. Write it in plain English: "Do X given Y."

#Functions Without a Return Value Give None

Every function in Python returns something. If you don't use the return keyword, Python quietly returns a special value called None — a way of saying "nothing here". You will learn more about return in the next lesson; for now, just know it exists.

The function runs and prints, but its return value is None because we never used `return`.
def greet(name):
    """Print a friendly greeting."""
    print("Hello,", name)

result = greet("Sam")
print("Return value:", result)
Common mistake

Don't Forget the Colon — or the Indent

Two of the most common beginner mistakes:

  1. Missing colon after the parentheses: def greet(name) instead of def greet(name):
  2. Wrong indentation inside the body — Python will raise an IndentationError.

If Python complains, check those two things first.

Watch out

Calling Before Defining

You must define a function before you call it. If you try to call greet() on line 1 but the def greet is on line 5, Python will raise a NameError. Always define first, call second.

Quick check

What is the difference between a *parameter* and an *argument*?

Key takeaways

  • Use `def name(params):` followed by an indented body to define a function.
  • Functions let you reuse code — write once, call many times (the DRY principle).
  • Parameters are placeholders in the definition; arguments are the values you pass when calling.
  • Add a docstring (triple-quoted string) as the first line of a function to document what it does.
  • A function with no `return` statement automatically returns `None`.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
def greet(name):
    print("Hello,", name)

greet("Alice")
greet("Bob")
Fix the bug#2

This code has a bug. What is wrong?

fix-bug
def add(a, b)
    result = a + b
    print(a, "+", b, "=", result)

add(3, 5)
Fill in the blank#3

Complete the code so it defines a function called `welcome` that prints "Welcome!".

 welcome():
    print("Welcome!")

welcome()
Reorder the lines#4

Put these lines in the right order to define and call a function that greets a user by name.

1
greet("Sam")
2
def greet(name):
3
    """Print a greeting for the given name."""
4
    print("Hello,", name)
Your turn
Practice exercise

Write a function called introduce that takes two parameters: name and age. It should print a sentence like: "Hi, I'm Alice and I'm 30 years old." Add a docstring. Then call your function twice with different names and ages.

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable