As we saw in previous chapters, you can write sequences of Python statements to perform tasks. However, when you find yourself writing the same sequence of steps repeatedly, or when a particular task becomes complex, it's beneficial to package that sequence into a named block of code. This block is called a function. Defining functions allows you to give a name to a specific computation or action, making your code more organized, readable, and reusable. Instead of rewriting the same logic multiple times, you simply "call" the function by its name whenever you need to perform that action.
def
StatementIn Python, you define a function using the def
keyword, followed by the function's name, a pair of parentheses ()
, and a colon :
. The actual code that the function will execute is placed in an indented block immediately following the def
line. This indentation is mandatory and signifies the function's body.
Here's the basic syntax:
def function_name():
# Indented block of code
# This is the function body
statement1
statement2
# ... more statements
Let's define a simple function that prints a greeting message:
def greet_user():
print("Hello there!")
print("Welcome to the world of Python functions.")
Breaking this down:
def
: The keyword that signals the start of a function definition.greet_user
: This is the name we've chosen for our function. Function names follow the same rules as variable names (must start with a letter or underscore, can contain letters, numbers, and underscores). The convention is to use lowercase letters with underscores separating words (this style is called snake_case).()
: The parentheses are required. Later, we'll see how they are used to accept input data (arguments) for the function. For now, they are empty, indicating this function doesn't take any input.:
: The colon marks the end of the function header line.print("Hello there!")
and print("Welcome to the world of Python functions.")
form the body of the function. They are indented (typically by 4 spaces) to show they belong to the greet_user
function. Python uses this indentation to determine the scope of the function's code.It's important to understand that defining a function doesn't execute its code immediately. The def
statement simply creates the function object and assigns it the name greet_user
. Think of it like writing down a recipe; you've defined the steps, but you haven't actually cooked anything yet.
To execute the code inside the function body, you need to call the function. You call a function by using its name followed by parentheses:
# Define the function
def greet_user():
print("Hello there!")
print("Welcome to the world of Python functions.")
# Now, call the function
print("Let's call the function:")
greet_user()
print("Function call finished.")
Running this script would produce the following output:
Let's call the function:
Hello there!
Welcome to the world of Python functions.
Function call finished.
Notice how the lines inside greet_user
were only executed when greet_user()
was called. You can call this function multiple times from different parts of your program, achieving code reuse.
# Define the function (usually done near the top of a script)
def greet_user():
print("Hello there!")
print("Welcome to the world of Python functions.")
# Call it once
print("First greeting:")
greet_user()
# Maybe do some other work here...
x = 10
y = 5
print(f"Performing a calculation: {x} * {y} = {x*y}")
# Call it again
print("\nSecond greeting:")
greet_user()
Output:
First greeting:
Hello there!
Welcome to the world of Python functions.
Performing a calculation: 10 * 5 = 50
Second greeting:
Hello there!
Welcome to the world of Python functions.
Defining functions is a fundamental step towards writing structured and manageable Python programs. By encapsulating logic within named blocks, you make your code easier to understand, test, and modify. In the following sections, we will explore how to make functions more flexible by passing data into them and getting results back out.
© 2025 ApX Machine Learning