As your programs get bigger, you’ll find yourself repeating the same blocks of code. A great way to make your code more organized, reusable, and easier to debug is by creating your own functions. A function is a named block of statements that you can run (or “call”) whenever you need it.
✍️ Defining Your First Function
You define a function using the def
keyword, followed by the function’s name, a pair of parentheses ()
, and a colon :
. The code that belongs to the function is indented underneath this line. For example, here’s a simple function that prints a greeting:def say_hello():
print("Hello, there!")
This code defines the function but doesn’t run it yet.
📞 Calling a Function to Execute It
Defining a function just sets it aside for later use. To actually run the code inside, you need to call the function. You do this by typing its name followed by parentheses. So, to run our example function, you would simply add this line to your script:say_hello()
Every time you call it, it will execute the print statement inside. You can call it as many times as you want from different parts of your program.
✅ The Benefits of Using Functions
Why bother with functions? They offer several key advantages. They promote code reuse, so you don’t have to write the same logic over and over. They help with organization by breaking down a large program into smaller, manageable pieces. This also makes debugging easier, as you can test each function individually to make sure it works correctly. Once a function is working perfectly, you can treat it like a black box and not worry about its internal details anymore.
Learning to write your own functions is a major step in moving from writing simple scripts to building complex and well-structured applications.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python