Introduction to Python

User Defined Functions

Lesson 5: Functions in Python

What is a User-Defined Function?

As your programs grow larger, you will find yourself writing the same code over and over. User-defined functions let you group a block of code under a name, then call it whenever you need it — avoiding repetition and making your code organized and reusable.

Illustration of a machine with an input slot on the left, a process box in the middle labeled function, and an output slot on the right — showing how functions take input and return output
A user-defined function is a reusable block of code that you define yourself using the def keyword. You call the function by its name whenever you need it to run.

Defining a Function

# Basic function with no parameters def greet(): print("Hello! Welcome to Python.") # Call the function greet()

Functions with Parameters

Functions can accept inputs called parameters. This makes them flexible and reusable with different values.

# Function with parameters def greet(name): print("Hello, " + name + "!") # Call with different arguments greet("Tobi") greet("Sara")

Diagram showing the greet function with name as the parameter going in and Hello Tobi and Hello Sara as outputs when called with different arguments

Functions with Return Values

Functions can also compute a value and send it back to the caller using the return keyword.

# Function that returns a value def add(a, b): result = a + b return result # Use the returned value sum = add(5, 3) print(sum) # 8

Parts of a Function

PartDescriptionExample
def keywordDeclares the start of a functiondef my_function():
Function nameThe name used to call the functiondef calculate_area():
ParametersInputs the function acceptsdef greet(name):
Function bodyThe indented code that runs print("Hello")
return statementSends a value back to the callerreturn result
An annotated Python function definition with colored labels pointing to the def keyword, function name, parameters, body, and return statement
Always define a function before calling it in your script. Python reads code from top to bottom — if you call a function before it is defined, you will get an error!

Subscribe to our newsletter.

Get updates to news and events.