If you have written a few lines of Python, you have probably noticed that some pieces of code get repeated again and again. Functions are the tool that solves this problem. They let you package a block of code, give it a name, and reuse it whenever you need it. In this article, you will learn what functions are, how to create them, and how they make your programs cleaner and easier to maintain.
What is a function?
A function is a named block of code that performs a specific task. Instead of writing the same instructions over and over, you define them once inside a function and then “call” that function whenever you want the task to run. This idea is often summarized by the principle “Don’t Repeat Yourself” (DRY), which is one of the foundations of good programming.
Python already includes many built-in functions, such as print(), len(), and input(). When you write your own, you create custom functions tailored to your program’s needs.
Defining your first function
In Python, you define a function using the def keyword, followed by the function name and a pair of parentheses. The code that belongs to the function is indented below it. Here is a simple example:
def greet():
print("Hello, welcome to Python!")
greet()
The first three lines define the function, and the last line calls it. Every time you write greet(), the message is printed. Notice that defining a function does not run it; you must call the function by its name to execute the code inside.
Using parameters
Functions become much more powerful when they accept information from the outside. These inputs are called parameters. They act as placeholders that receive values, known as arguments, when the function is called. Look at this example:
def greet(name):
print("Hello, " + name + "!")
greet("Ana")
greet("Carlos")
Here, name is a parameter. When we call greet("Ana"), the function prints “Hello, Ana!”, and when we call greet("Carlos"), it prints “Hello, Carlos!”. The same function adapts to different inputs, which is exactly what makes it reusable.
Returning values
Many functions do more than print something on the screen; they calculate a result and hand it back to the rest of the program. This is done with the return keyword. A returned value can be stored in a variable and used later.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # displays 8
The difference between printing and returning is important. Printing only shows a value, while returning gives it back so your program can keep working with it. As a rule, functions that calculate something should usually return the result rather than print it.
Default parameter values
Sometimes you want a parameter to have a value even if the caller does not provide one. Python lets you set default values directly in the definition:
def greet(name="friend"):
print("Hello, " + name + "!")
greet() # Hello, friend!
greet("Marina") # Hello, Marina!
If no argument is given, the function uses the default value. This makes your functions more flexible and forgiving.
Why functions matter
Beyond avoiding repetition, functions bring several practical benefits to your code:
- Organization: your program is split into small, understandable pieces, each with a clear purpose.
- Reusability: once written, a function can be used in many places or even in other projects.
- Easier maintenance: if something needs to change, you update the function in one place instead of everywhere.
- Fewer errors: less duplicated code means fewer opportunities for mistakes.
Good practices for writing functions
As you start writing your own functions, a few habits will help you produce clean and professional code. Give each function a descriptive name that explains what it does, such as calculate_total or send_email. Keep functions focused on a single task; if a function is doing too many things, consider splitting it. Finally, add a short comment or docstring explaining what the function expects and what it returns, which helps others (and your future self) understand it quickly.
Understanding variable scope
A concept closely tied to functions is scope, which defines where a variable can be used. A variable created inside a function is called a local variable, and it exists only while that function runs. Once the function finishes, the variable disappears. This behavior is helpful because it keeps the inner workings of a function separate from the rest of your program, preventing accidental conflicts.
def calculate_area(width, height):
area = width * height # local variable
return area
print(calculate_area(4, 5)) # displays 20
# print(area) would cause an error here
In the example above, the variable area only exists inside the function. Trying to use it outside would raise an error, because Python does not recognize it there. Understanding scope early helps you avoid confusing bugs as your programs grow.
A practical example
To see how functions come together, imagine a small program that converts temperatures from Celsius to Fahrenheit. Instead of repeating the formula every time, you write it once:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
print(celsius_to_fahrenheit(0)) # 32.0
print(celsius_to_fahrenheit(100)) # 212.0
Now the conversion logic lives in a single place. If you ever need to adjust it, you change one function and every part of your program benefits from the update. This is the essence of reusable code.
Keep learning
Functions are a turning point in learning to program, because they open the door to writing organized and scalable software. Once you feel comfortable with them, you can explore more advanced topics such as arguments with keywords, functions that call other functions, and modules. If you want to build a solid foundation step by step, take a look at the free programming and Python courses available on Cursa, where you can practice at your own pace and grow as a developer.



























