Python Functions

Organize reusable logic with parameters and return values.

As programs grow larger, you may find yourself writing the same code multiple times. Repeating code makes programs longer, harder to read, and more difficult to maintain. A better approach is to group related code into reusable blocks called functions.

A function allows you to write a block of code once and use it whenever needed. This makes programs cleaner, more organized, and easier to update.

In this lesson, you will learn what functions are, why they are useful, how to create them, pass information to them, return values, and work with different types of function arguments.

What is a Function?

A function is a named block of code that performs a specific task. Instead of writing the same instructions repeatedly, call the function whenever that task is needed. Python provides built-in functions such as print(), input(), and len(), and you can create your own functions.

Creating a Function

Python functions are created using the def keyword.

Syntax

python
def function_name():
    # Code to execute
    pass

Example

python
def greet():
    print("Welcome to DevBrainBox!")

greet()

Output

text
Welcome to DevBrainBox!

The greet() function is defined first and then called. Code inside a function runs only when the function is called.

Why Use Functions?

  • Reduce code duplication.
  • Make programs easier to read.
  • Improve code organization.
  • Simplify testing and debugging.
  • Allow code to be reused in different parts of a program.

Using functions is good programming practice, especially in larger applications.

Function Parameters

Sometimes a function needs information to perform its task. A parameter defines an input that the function expects, while an argument is the value supplied during a particular call.

python
def greet(name):
    print("Hello,", name)

greet("Alice")
greet("John")

Output

text
Hello, Alice
Hello, John

The name parameter receives each argument passed during a function call.

Multiple Parameters

A function can accept more than one parameter, making it flexible enough to work with different combinations of values.

python
def add_numbers(a, b):
    print(a + b)

add_numbers(10, 5)

Output

text
15

Returning Values

Many functions calculate a result and send it back to the caller with return. A return statement ends the current function call and provides its result.

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

result = multiply(4, 5)

print(result)

Output

text
20

Default Parameters

Assign a default value to a parameter when the function should work even if that argument is omitted.

python
def greet(name="Guest"):
    print("Hello,", name)

greet()
greet("Emma")

Output

text
Hello, Guest
Hello, Emma

Default parameters make functions convenient in different situations while still allowing callers to provide a custom value.

Keyword Arguments

Keyword arguments specify parameter names during a call. They improve readability and allow arguments to be supplied in a different order.

python
def student(name, age):
    print(name, age)

student(age=21, name="David")

Variable-Length Arguments

Variable-length arguments are useful when you do not know in advance how many values a function will receive.

Using *args

The *args syntax collects any number of positional arguments into a tuple. The name args is conventional but can be changed.

python
def total(*numbers):
    print(sum(numbers))

total(10, 20)
total(5, 10, 15, 20)

Using **kwargs

The **kwargs syntax collects any number of keyword arguments into a dictionary. The name kwargs is conventional but can also be changed.

python
def show_details(**info):
    print(info["name"])
    print(info["city"])

show_details(name="John", city="Delhi")

Variable Scope

Variables created inside a function are local variables and can normally be used only within that function.

python
def show():
    message = "Hello"
    print(message)

show()

Trying to access message outside show() causes an error because it exists only in that local scope. Variables defined at the top level are global variables and can generally be read throughout the module. Prefer passing values through parameters and return values when possible because it makes dependencies clearer.

Recursive Functions

A recursive function calls itself. Every recursive solution needs a base case that stops further calls.

python
def countdown(number):
    if number == 0:
        return

    print(number)
    countdown(number - 1)

countdown(5)

Output

text
5
4
3
2
1

Recursion is useful for certain naturally recursive problems, although beginners should first become comfortable with ordinary functions and loops.

Lambda Functions

A lambda is a small anonymous function limited to a single expression. Lambdas are useful for short operations and are often supplied to tools such as sorted(), map(), and filter().

python
square = lambda x: x * x

print(square(6))

Output

text
36

Best Practices

  • Give functions meaningful names.
  • Keep each function focused on one task.
  • Avoid making functions too long.
  • Use parameters instead of relying on global variables.
  • Return values when a result will be used later.

Following these practices makes code easier to understand, test, reuse, and maintain.

Key Takeaways

  • A function is a reusable block of code that performs a specific task.
  • Functions are created with the def keyword.
  • Parameters allow functions to receive input values.
  • The return statement sends a result back to the caller.
  • Default parameters provide values when an argument is omitted.
  • Keyword arguments improve readability and flexibility.
  • *args and **kwargs accept variable numbers of arguments.
  • Variables inside a function have local scope, while top-level variables are global.
  • Recursive functions call themselves and must include a stopping condition.
  • Lambda functions are short anonymous functions for simple operations.
  • Functions help create cleaner, reusable, and well-organized Python programs.
Let's learn with DevBrainBox AI