Robert Johns | 12 Feb, 2025
Fact checked by Jim Markus

Python Define Function | Docs With Examples

Functions in Python are reusable blocks of code that perform a specific task. They improve code readability, reusability, and organization.

Defining a Function with def

In Python, you define a function using the def keyword:

def greet():
    print("Hello, World!")

Explanation:

  • def is the keyword used to define a function.
  • greet is the function name.
  • The parentheses () can hold parameters (discussed next).
  • The function body is indented and contains the logic to be executed.

Calling a Function

Once a function is defined, call it by using its name followed by parentheses:

greet()

Output:

Hello, World!

Function Parameters

You can pass values to a function using parameters:

def greet_user(name):
    print(f"Hello, {name}!")

greet_user("Alice")

Output:

Hello, Alice!

Explanation: The function takes one parameter, name, and uses an f-string to personalize the greeting.

Default Parameters

You can provide default values for parameters:

def greet_user(name="Guest"):
    print(f"Hello, {name}!")

greet_user()

Output:

Hello, Guest!

Returning Values

Functions can return values using return:

def add(a, b):
    return a + b

result = add(3, 5)
print(result)

Output:

8

Multiple Return Values

Functions can return multiple values as a tuple:

def get_coordinates():
    return 10, 20

x, y = get_coordinates()
print(x, y)

Output:

10 20

Keyword Arguments

You can specify arguments using keywords for clarity:

def introduce(name, age):
    print(f"My name is {name} and I am {age} years old.")

introduce(age=30, name="Bob")

Output:

My name is Bob and I am 30 years old.

Variable-Length Arguments

*args (Multiple Positional Arguments)

Use *args to accept a variable number of arguments:

def sum_numbers(*args):
    return sum(args)

print(sum_numbers(1, 2, 3, 4, 5))

Output:

15

**kwargs (Multiple Keyword Arguments)

Use **kwargs to accept multiple keyword arguments:

def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

display_info(name="Alice", age=25, city="New York")

Output:

name: Alice
age: 25
city: New York

Nested Functions

Functions can be defined inside other functions:

def outer_function():
    def inner_function():
        print("This is an inner function.")
    inner_function()

outer_function()

Output:

This is an inner function.

Lambda Functions (Anonymous Functions)

A lambda function is a short function with no name:

square = lambda x: x ** 2
print(square(4))

Output:

16

Key Takeaways

  • Use def to define functions for reusable logic in your Python projects.
  • Functions can accept parameters, return values, and handle flexible arguments.
  • *args allows multiple positional arguments.
  • **kwargs allows multiple keyword arguments.
  • Use lambda functions for short, anonymous operations.

Practice Exercise

Here's a simple challenge, open up your Python editor and try to write a function that takes two numbers and returns their product:

def multiply(a, b):
    return a * b

print(multiply(6, 7))

Wrapping Up

Understanding how to define and use functions is crucial for writing efficient and organized Python code. Functions enhance modularity, making code easier to read and maintain. Happy coding!

By Robert Johns

Technical Editor for Hackr.io | 15+ Years in Python, Java, SQL, C++, C#, JavaScript, Ruby, PHP, .NET, MATLAB, HTML & CSS, and more... 10+ Years in Networking, Cloud, APIs, Linux | 5+ Years in Data Science | 2x PhDs in Structural & Blast Engineering

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments