VMware ESXi and vSphere Cluster Management
What Are Functions in Python?
Learn how to define and call Python functions, use parameters and arguments, return values, and organize repetitive tasks into reusable code.
What Is a Function?
A function is a named, reusable block of code that performs a task when it is called. Functions help you divide a larger program into smaller, manageable parts.
Functions also provide reusability: you can write a task once and use it many times instead of copying the same statements throughout your program.
A function has two separate stages:
- Definition: creating the function and describing the code it should run.
- Call: running the function's body.
Defining a function does not automatically run its code.
Defining a Function with def
Python uses the def keyword to begin a function definition. The basic structure is:
def function_name():
# statements in the function bodyThis structure contains a function name, parentheses, a colon, and an indented function body. The body contains the statements that run when the function is called.
Choose a name that describes the task. For example, greet is clearer than a vague name such as do_task.
Indentation means the leading whitespace at the beginning of a line. In Python, indentation determines which statements belong to a function body.
def greet():
print("Hello, Python learner!")
print("Welcome to the lesson.")Both print() statements are indented, so both belong to greet. Consistent indentation is required.
Calling a Function
A function call runs a function. Write the function name followed by parentheses:
greet()When Python reaches this call, it executes the indented statements inside greet.
A function must be defined before execution reaches a call to it:
def greet():
print("Hello!")
greet()You can call the same function repeatedly. Each call runs the body again:
def greet():
print("Hello!")
greet()
greet()
greet()This displays the greeting three times while keeping the implementation in one place.
| Concept | Typical syntax | What it does | Colon required? |
|---|---|---|---|
| Function definition | def function_name(): | Creates a function and stores its body for later execution. | Yes, after the parentheses. |
| Function call | function_name() | Runs the function body. | No. |
Parameters and Arguments
A function can receive input through its parentheses. A parameter is a variable listed in a function definition that receives an input value.
def greet_person(name):
print("Hello, " + name + "!")Here, name is a parameter. It acts as a placeholder for a value supplied when the function is called.
An argument is the actual value supplied to a function call:
greet_person("Mina")
greet_person("Alex")During the first call, the argument "Mina" is assigned to the parameter name. During the second call, name receives "Alex". The same function can therefore work with different data.
| Term | Where it appears | Example role |
|---|---|---|
| Parameter | In a function definition | name in def greet_person(name): is a variable ready to receive input. |
| Argument | In a function call | "Mina" in greet_person("Mina") is the supplied value. |
| Value received inside the function | During execution | The parameter name refers to "Mina" while that call runs. |
Numerical Conversion Example
Parameters are useful for calculations. This function converts an amount in dollars to euros using a fixed example rate:
def dollars_to_euros(amount):
return amount * 0.92
print(dollars_to_euros(10))
print(dollars_to_euros(25))
print(dollars_to_euros(100))The parameter is amount. The calls supply 10, 25, and 100 as arguments. Each argument is assigned to amount for its own call, so the function performs the calculation with a different value each time.
The rate in this example is only an illustrative value. Real exchange rates change and should come from an appropriate current source in a real application.
print() Versus return
print() displays information immediately. The return statement sends a value from a function back to the code that called it.
| Action | Displays text immediately? | Makes a value available to calling code? | Typical use |
|---|---|---|---|
print() | Yes | Not as a reusable result | Showing a message or result to a user. |
return | No, by itself | Yes | Producing a result that other code can store, print, or calculate with. |
Returning a Result
Use return when the calling code needs to work with the result:
def dollars_to_euros(amount):
return amount * 0.92
converted = dollars_to_euros(50)
print("50 dollars is", converted, "euros")
larger_amount = dollars_to_euros(50) + dollars_to_euros(25)
print("The combined conversion is", larger_amount, "euros")The function performs the conversion and returns the number. The calling code decides how to display or use that number. The returned value can be stored in a variable, used in an expression, or passed to print().
Compare this with a function that only prints:
def show_conversion(amount):
print(amount * 0.92)
show_conversion(50)This version displays the result, but it does not provide a result that the caller can conveniently assign to another variable or combine with another calculation.
Practical Function Decomposition
Function decomposition means dividing a larger task into focused functions. A good function usually has one clear responsibility and a meaningful name.
For example, reading all lines from a file is a focused task that can be placed in its own function:
def read_lines(file_path):
with open(file_path, "r", encoding="utf-8") as file:
lines = list(file)
return lines
lines = read_lines("notes.txt")
print(lines)The read_lines function accepts a file path, opens the file, creates a list containing its lines, and returns that list. The code outside the function can decide what to do with the returned lines.
Moving this operation into a function avoids repeating file-opening and line-reading code whenever another part of the program needs the same task.
Common Function Syntax
def function_name():
# no parameters
function_name()
def function_name(parameter_name):
# use parameter_name here
return value
function_name(argument_value)Remember these roles:
defbegins a function definition.- Parentheses in a definition contain zero or more parameters.
- The colon begins the indented function body.
- A function call uses the function name and parentheses.
- Arguments are placed inside the parentheses of a call.
returnsends a value back to the caller.
Troubleshooting Functions
The Function Is Defined but Nothing Is Displayed
Cause: The function was created but never called.
def greet():
print("Hello!")
greet()Add a call after the definition.
A SyntaxError Occurs on a Function Call
Cause: A colon was added after the parentheses in the call.
# Correct
greet()
# Incorrect
greet():Use the colon only on the def line.
A NameError Occurs
Possible causes: Python reached the call before executing the definition, or the function name was misspelled.
def greet():
print("Hello!")
greet()Place the definition before the call and use exactly the same name in both places.
An IndentationError Occurs
Cause: A statement in the function body is not indented consistently.
def greet():
print("Hello!")
print("Welcome!")Indent every statement belonging to the body by the same amount. Four spaces are the usual convention.
A Calculation Is Displayed but Cannot Be Reused
Cause: The function prints the calculation instead of returning it.
Fix: Replace the display-only behavior with return, then print or otherwise use the returned value in the calling code.
A Required Input Is Missing
If a function has a required parameter, the call needs a corresponding argument:
def greet_person(name):
print("Hello, " + name)
# Correct
greet_person("Mina")
# Incorrect: name is missing
greet_person()Pass one argument for each required parameter.
Key Points to Remember
- A function is a named block of reusable code that performs a task when called.
- Defining a function creates it; calling the function runs it.
def, a function name, parentheses, a colon, and an indented body form the basic definition.- A parameter is a variable in a definition; an argument is the value supplied in a call.
- One function can produce different results when called with different arguments.
print()displays output, whilereturnmakes a result available to calling code.- Focused functions with meaningful names make larger programs easier to understand and maintain.
Continue practicing with Python functions by changing the examples to accept your own values and return results for other code to use.