Python functions: write code once and reuse it

A function in Python is a named block of code that runs when it is called, and can be called again from other parts of a program. You define a function once, give it a name, and then use that name wherever the same job is needed. That saves copying the same lines, and it means a fix in one place applies everywhere the function is used.
A function can take inputs, called parameters, and it can give back a result, called a return value. A function that only prints a message needs neither, while a function that calculates a total needs both. Learning the difference between defining a function and calling it is the key step in this guide, because a defined function does nothing until it is called.
Define a function and call it
The example below defines a function called greet, then calls it twice with different names. The def line names the function, lists its parameter in brackets, and ends with a colon. The indented lines under it are the function body, and they run only when the function is called. The calls sit after the definition, at the same indentation as the def line, because they are part of the main program, not part of the function.
def greet(name):
print("Hello,", name)
greet("Sara")
greet("Ali")
Parameter and argument are two words for two sides of the same exchange. The parameter is the name inside the definition, in this case name. The argument is the value passed at the call, in this case Sara or Ali. When the function runs, the parameter takes the argument value, and the body uses that value. Different calls can pass different arguments, which is why one function can serve many cases.
Return a value instead of printing it
Printing inside a function shows a value, but it does not give that value to the rest of the program. Returning a value does. The add example below returns the sum, and the caller stores that sum in a variable. That stored result can then be printed, added to another value, or passed to another function. If the function had only printed the sum, the caller would have nothing to work with after the call.
def add(a, b):
return a + b
total = add(10, 20)
print(total)
print(add(5, 7))
The output is 30, then 12. The first call stores its result, and the second call prints its result directly without storing it. Both are valid, and the choice depends on whether the result is needed later. A function can return text, numbers, true or false values, and other types covered in the variables and data types guide. It can also return more than one value in a tuple, though that pattern is best left for a later guide on data structures.
Code after a return line in the same block does not run, because return ends the function at once and hands the value back. That is useful for early exits, such as returning a default when an input fails a test, but it can also hide a mistake if a return line sits above code you meant to run. Read a function from top to bottom and check where each return sits, especially in a function with a condition inside it.
def is_adult(age):
if age >= 18:
return True
return False
print(is_adult(20))
print(is_adult(15))
Give parameters default values
A parameter can have a default value, which is used when the caller does not pass that argument. That makes a function easier to call in the common case, while still allowing a different value when needed. The greeting below uses a default of guest, so a call with no argument greets a guest, and a call with a name greets that person. Defaults are listed after parameters without defaults, because Python needs to know which arguments are required and which are optional.
def greet(name="guest"):
print("Hello,", name)
greet()
greet("Sara")
| Part of a function | What it does | Example |
|---|---|---|
| def line | Names the function and lists its parameters | def greet(name): |
| Body | The indented block that runs on each call | print("Hello,", name) |
| Call | Runs the function with specific arguments | greet("Sara") |
| Return | Sends a value back to the caller | return a + b |
Keep functions small and readable
A good function does one job and has a name that says what that job is. Calculate total, format message, and is adult are names that tell a reader what to expect. A function called do stuff tells a reader nothing, and a function that calculates a total, prints a report, and saves a file is doing three jobs under one name. Splitting that function into three smaller functions makes each one easier to test, easier to reuse, and easier to fix when one part breaks.
Variables created inside a function are local to that function, which means code outside the function cannot see them. That is a useful boundary, because it stops a function from accidentally changing a variable used elsewhere. If a function needs a value from outside, pass it as a parameter. If the caller needs a value from inside, return it. Passing values in and returning values out, instead of reaching for shared variables, keeps functions predictable and reusable in other programs.
Common mistakes to watch for
Forgetting to call a function is the most common first mistake. The definition runs with no error and no output, and the program ends quietly. Check the end of the file for the call, and check that the call name matches the definition name exactly, including case. A spelling difference creates a new name that Python reports as unknown, which is the same NameError covered in the first program guide.
Confusing print and return is the next mistake. A function that prints a result looks correct on screen, but a caller that tries to store that result gets None instead. If you need the result later, return it and let the caller decide whether to print it. If you only need to show a message, printing inside the function is fine, and no return is needed.
Passing the wrong number of arguments is a clear error that Python reports at the call. A function with two parameters needs two arguments, unless one has a default. Count the parameters in the def line, count the arguments at the call, and check the order, because arguments are matched by position unless they are named. Passing arguments in the wrong order gives a wrong result without an error, which is harder to spot than a missing argument.
Using a variable from inside a function outside it is another scope mistake. The variable exists only while the function runs, and after the function returns, that name is gone from the outside view. The fix is to return the value and store it in a variable at the call site, rather than trying to read the inner name from outside. That pattern of return and store is the normal way functions share results.
Limits of this guide
This guide covers defining, calling, parameters, defaults, and return values for simple functions. It does not cover functions that take a variable number of arguments, keyword only arguments, or functions passed as values to other functions, all of which are useful in larger programs but add complexity before the basics are solid. It also does not cover recursion in depth, or how to organise functions into modules and packages, which are covered in later guides in this series.
Worked example: a function that builds a message
A function that returns a value is more flexible than one that only prints, because the caller can use the returned value in a message, a calculation, or another function. The example below takes a name and a score, builds a message from them, and returns the message. The caller decides what to do with the result, which keeps the function useful in more than one place.
def report(name, score):
message = name + " scored " + str(score)
return message
result = report("Maya", 18)
print(result)
Follow the call step by step. The call report("Maya", 18) gives the name parameter the value "Maya" and the score parameter the value 18. Inside the function, str turns the score into text so it can join with the other pieces. The return line hands the finished message back, and the caller stores it under result, then prints it. The function itself prints nothing, which is why it can be reused wherever a message is needed.
Try calling the function a second time with different values and storing that result under a different name. Each call runs the same body with its own values, and the two results stay separate. That separation is the point of parameters. One body, many calls, each call with its own data, and no shared state to confuse the results.
Parameters, arguments, and default values in a table
Two words cause confusion here, so the table below keeps them apart. A parameter is the name written in the function definition, and an argument is the value given in a call. A default value is a value a parameter takes when the caller gives no argument for it, which lets a function work with a short call while still allowing a longer call when needed.
| Term | Where it appears | Example |
|---|---|---|
| Parameter | In the definition | def greet(name): |
| Argument | In the call | greet("Maya") |
| Default value | In the definition, after = | def greet(name="Guest"): |
| Return value | Handed back with return | return message |
Default values suit settings that rarely change, such as a greeting word or a page size. They make the common call short, while a caller that needs a different value can still pass it. One caution applies. A default that is a list or dictionary is shared across calls, because the default object is created once when the function is defined, so a list default can collect items from earlier calls in a surprising way. For beginners, the safe habit is to use simple values, such as numbers or text, as defaults.
Keyword arguments let a caller name the parameters in the call, which helps when a function takes several values of the same type. Writing report(name="Maya", score=18) makes the meaning of each value visible at the call site, and it lets the caller give arguments in a different order from the definition. That clarity is worth the extra typing when a call has more than two arguments.
Scope: what a function can see
Variables created inside a function belong to that function, and code outside cannot see them. That rule is called scope, and it keeps functions separate from each other. A variable named total inside one function does not clash with a variable named total in another function, because each function has its own set of local names.
def double(value):
result = value * 2
return result
print(double(5))
The name result exists only inside double, so trying to print result outside the function would fail with a name error. That failure is not a flaw. It shows that the function kept its working values private, and that the only value meant to leave the function is the one handed back with return. When a value is needed outside, return it, rather than reaching into the function from outside.
A function can read a variable defined outside it, yet changing that outside variable from inside needs a deliberate statement, and beginner code rarely needs it. The clearer pattern is to pass values in as parameters and hand results back with return, so the flow of data is visible in the call itself. That pattern also makes the function easier to test, because a test can call it with known inputs and check the returned output.
Small functions, tested one at a time
A function that does one job is easier to name, easier to test, and easier to reuse. A function that calculates a total, formats a message, and writes a file is doing three jobs, and a bug in any one of them hides inside a block that does too much. Splitting that block into three small functions gives each job a name and a test of its own, and the main flow then reads as a short list of named steps.
Testing a small function is straightforward. Call it with a simple input, print the result, and compare the result with the value expected by hand. Do that for a normal input, for an empty input, and for a boundary input, and the function earns trust before it is used in a larger program. That habit also makes later debugging faster, because a failing test points at one small function rather than a whole program.
When a function grows past about twenty lines, it is worth asking whether it holds more than one job. That line count is a guide, rather than a rule, and some jobs genuinely need more lines. The question to ask is whether the function can be described in one short sentence. If the description needs several clauses, the function probably holds several jobs, and splitting it will help the next reader.
Frequently asked questions
When should code become a function?
When the same block is needed twice, or when a block has a clear job with a clear name. A function also helps when a long program becomes hard to read, because it lets you hide details behind a name and read the main flow at a higher level.
Does a function need a return value?
No. Some functions only do something, such as printing a message, and they return None by default. A function needs return only when the caller needs a value back to use later, such as a total or a formatted string.
Can a function take no parameters?
Yes. A function with empty brackets takes no input and runs the same way each time, or it reads values set elsewhere. Parameters are for values that change between calls; no parameters means no changing input.
What is the difference between a parameter and an argument?
A parameter is the name written in the function definition, while an argument is the value given in a call. The call fills each parameter with its argument, and the function body then works with those values.
Why return a value instead of printing it?
A returned value can be stored, compared, or passed to another function, while a printed value can only be read on screen. Returning keeps the function useful in more places, and printing is left to the caller.
Can a function use a variable from outside it?
It can read a variable defined outside, yet the clearer pattern is to pass values in as parameters and hand results back with return. That pattern makes the flow of data visible in the call and keeps the function easy to test.


