How to define a function in Python
A guide on how to create and use a function in Python, so you can avoid copy-pasting your code, using a simple library management system as an example.
Dec 1, 2025 • 10 Minute Read
When you’re starting out, it can be thrilling to write your first piece of code that actually runs. And if it’s useful, you might want to run it in other places, too. As a beginner, it can be all too tempting to simply copy-paste what worked somewhere else wherever you need it, but this is a bad idea. In fact, whenever you get the urge to copy your old code, you should do something else instead: make a function!
What is a function?
A function is a block of reusable code you can call to perform a task. They’re one of the most fundamental concepts not just in Python, but in programming overall. In fact, you’ve probably used one without even realizing it, even as a beginner. Take this simple “Hello World” script, for example:
print("Hello world")
print() is a built-in function of Python. So, whenever you’ve been passing values after a name between two parentheses, you’ve been calling a function!
When working in Python, you’ll be creating functions multiple times a day and also using functions other people have created, so learning how they work is programming 101.
What functions are for
The best way to show the value of using functions is to show you how much harder things are when you don’t use them.
For a practical example, let's imagine we're building a simple library management system. In this scenario, we need to track books and display book information in several places: when someone searches for a book, when they check it out, and when they return it.
Here's what your code might look like across the application without functions:
# In the logic for searching for a book
print("Search results:")
print("=" * 40)
print(f"Title: Python Illustrated")
print(f"Authors: Maaike van Putten and Imke van Putten")
print(f"ISBN: 978-1836646334")
print(f"Available: Yes")
print("=" * 40)
# In the logic for checking out a book
print("Checking out:")
print("=" * 40)
print(f"Title: Python Illustrated")
print(f"Authors: Maaike van Putten and Imke van Putten")
print(f"ISBN: 978-1836646334")
print(f"Available: Yes")
print("=" * 40)
# In the logic for returning a book
print("Return results:")
print("=" * 40)
print(f"Title: Python Illustrated")
print(f"Authors: Maaike van Putten and Imke van Putten")
print(f"ISBN: 978-1836646334")
print(f"Available: Yes")
print("=" * 40)
Notice how we’re writing the exact same code three times, but just changing the values? This is called code duplication, and can create several issues. Now, imagine if we could get rid of all of that, and replace it with a single function, like:
display_book_info("Python Illustrated", "Maaike van Putten and Imke van Putten", "978-1836646334", True)
Much cleaner, right? We’ve taken dozens of lines and compressed them into one.
Why code duplication is bad
At first, you might go “but I don’t mind copy-pasting or typing a little bit more, especially since functions seem scary to learn.” And while having to type more is an issue with code duplication, it’s actually the least important one.
1. It’s hard to maintain
Let’s say there’s something you want to change with how you’re outputting those book results from earlier (E.g. You want to add a field for what format the book is in, like a hardcover.) To do that, you’ve got to update it in three places, and it’s very easy to miss one, which can result in bugs and errors.
For larger programs, you might reuse a piece of code dozens or hundreds of times. On a collaborative project, you’ll be sharing it with others as well. This makes it very important to have a single place to update the code wherever it’s used.
2. It’s difficult to read
To understand what the code above does, we have to go through it line by line to see what it’s actually meant to do and output. With a function, you can tell exactly what it’s going to do from the name: we know when we use display_book_info() that is going to display book information.
3. Copying and pasting is harder
Again, while it’s the least important issue, a function lets you write code once and use it many times. A lot of the time, you don’t even need to write the full function out, just the first few letters! Most coding programs have an auto-complete feature that detect any function you’ve made and offer to insert it in for you.
Now that we’ve gone over why functions are important, let’s go over how to create one in Python.
Defining a function in Python
Defining is when you let the computer know you’re creating something that it needs to remember, and giving it meaning. In Python, you define a function using the def keyword. You then give it a name and then add some parentheses, like this:
def name_of_the_function():
pass
Congratulations, you’ve just written your first function, even though it does nothing yet! pass is just a placeholder we’re using for now in place of future code, so the function works if you run it (instead of throwing up errors.) We’ll remove it later when we add more actual code.
Now, you can create functions that return nothing or something, and you can also create functions that use or don’t use parameters. All of these are useful in different scenarios, so we’ll walk through all four versions.
1. Creating a function without parameters that returns nothing
The simplest kind of function to start with is one that returns nothing and doesn’t require any input handling. Let’s apply this by creating one that displays a welcome message when someone opens our library application:
def display_welcome_message():
print("=" * 40)
print("Welcome to Pluralsight Library!")
print("Your gateway to endless coding info")
print("=" * 40)
Here’s how the above code works:
- The function name display_welcome_message follows Python's naming convention: lowercase words separated by underscores.
- The empty parentheses () indicate this function doesn't accept any inputs.
- In the function, we write four lines to the screen.
To use (or “call” or “invoke”) the function, you write its name followed by parentheses, like this:
display_welcome_message()
When you run this code, you'll see:
========================================
Welcome to Pluralsight Library!
Your gateway to endless coding info
========================================
Let's create another function to display menu options, here's how that can be done:
def show_main_menu():
print("\nMain Menu:")
print("1. Search for a book")
print("2. Check out a book")
print("3. Return a book")
print("4. View all books")
print("5. Exit")
And we can then use both functions together, like this:
display_welcome_message()
show_main_menu()
This outputs first the welcome message and then shows the menu. It's very common to have certain lines of code that will have to be repeated that can be grouped in a function. Sometimes a function will give back a result. That result could be anything, the result of a calculation, result of a database call, result of an API call and more.
2. Creating a function without parameters that returns something
When a function needs to give back a result rather than just performing some actions, we need to specify this with the return keyword. Let's create a function that counts how many books are currently available in our library:
def get_total_books():
# In a real application, we would query a database
# For now, we'll use a simple hardcoded value
total = 150
return total
# Store the result in a variable
book_count = get_total_books()
print(f"Our library has {book_count} books available")
Let's unpack what happened in this code snippet. We created a function with a return keyword. This return tells Python to send a value back to wherever the function was called. And that value can then be used to store in a variable or pass it to another function (something we'll learn soon). Without return, the actions would happen inside the function and we'd have no way to access the result outside of it.
However, without parameters our functions are pretty much doing the same thing over and over. Which can definitely be useful, but sometimes we need more flexibility.
3. Creating a function with parameters that returns nothing
Parameters are just what we need. As mentioned earlier, they make functions flexible by allowing us to pass in different values each time we call the function. Let's return to our book display problem from the beginning:
def display_book_info(title, authors, isbn, available):
print("=" * 40)
print(f"Title: {title}")
print(f"Authors: {authors}")
print(f"ISBN: {isbn}")
print(f"Available: {'Yes' if available else 'No'}")
print("=" * 40)
The parameters title, authors, isbn, and available act like placeholders. When you call the function, you provide actual values (called "arguments"), and Python substitutes them into the function's code. Here's how to do that:
# Now we can display any book
display_book_info("Python Illustrated", "Maaike van Putten and Imke van Putten", "978-1836646334", True)
display_book_info("Learn Java with Projects", "Dr. Seán Kennedy and Maaike van Putten", "978-1837637188", False)
display_book_info("JavaScript from Beginner to Professional", "Laurence Svekis and Maaike van Putten", "978-1800562523", True)
Recognize this code from earlier? This is much better than our original code. We wrote the display logic once, and now we can use it for any book in any block of code that needs to display a book. If we want to change the format, we only need to update it in the function body.
4, Creating a function with parameters that returns something
We've now seen that functions can accept parameters and that they can return a value, but we have not seen this combined. That's actually a very successful combination, it lets you create reusable calculations and transformations. Let's create a function that calculates when a book is due:
from datetime import datetime, timedelta
def calculate_due_date(checkout_date, loan_period_days):
due_date = checkout_date + timedelta(days=loan_period_days)
return due_date
# Use it
today = datetime.now()
standard_due = calculate_due_date(today, 14)
extended_due = calculate_due_date(today, 21)
print(f"Standard loan due date: {standard_due.strftime('%B %d, %Y')}")
print(f"Extended loan due date: {extended_due.strftime('%B %d, %Y')}")
Here's another example that checks if a book is overdue and if so calculates the fine:
def calculate_overdue_fine(days_overdue, book_type):
if book_type == "regular":
daily_rate = 0.50
elif book_type == "reference":
daily_rate = 1.00
else:
daily_rate = 0.25 # children's books
if days_overdue <= 0:
return 0
fine = days_overdue * daily_rate
max_fine = 10.00
return min(fine, max_fine)
In order to call this function, we need to pass in two arguments. The first argument is for the parameter days_overdue and the second argument is for the parameter book_type. We then check the type of book to determine the rate of the late fee. If the book is not overdue, we return 0. We set the max_fine to 10 and we return whatever is lower, the max fine or the actual fine.
We can now calculate fines for different scenarios, like this:
regular_fine = calculate_overdue_fine(7, "regular")
reference_fine = calculate_overdue_fine(7, "reference")
no_fine = calculate_overdue_fine(0, "regular")
print(f"7 days overdue (regular book): ${regular_fine:.2f}")
print(f"7 days overdue (reference book): ${reference_fine:.2f}")
print(f"Returned on time: ${no_fine:.2f}")
After that, we print the results and we'll get this output:
7 days overdue (regular book): $3.50
7 days overdue (reference book): $7.00
Returned on time: $0.00
Conclusion: Functions are amazing, so use them!
With functions we can transform repetitive code chaos into organized modular code. Each function should have a single purpose, if it's having two purposes, we should usually write two different functions for it. When we have functions with single responsibility and descriptive names this has the following benefits:
- Code that's easier to understand
- Code that's easier to test (because we can test the functions independently)
- Maintenance and modification will be easier
- Less duplicate code, because we can just call the function.
So whenever you feel the need to copy paste or you notice that you are writing the same logic twice, it should probably be a function. It can also help when a section is getting long, to split it up into functions with a specific name to make the code more readable. For our library application, every distinct action (checkout, return, search, display) could be a function.
This pattern of organizing code around actions and responsibilities takes some getting used to, but will really serve you well in every program you write.
Further reading
Want to start learning Python? Check out Pluralsight's Python 3 Learning path, which covers not only the fundamentals of python, but also advanced concepts such as object-orientated design and effective code organization. It includes hands-on learning labs and skill tests to measure your progress. Additionally, you can check out other Python tutorials on the Pluralsight blog by Maaike van Putten:
Advance your tech skills today
Access courses on AI, cloud, data, security, and more—all led by industry experts.