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 lets you 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
def function_name():
# Code to execute
passExample
def greet():
print("Welcome to DevBrainBox!")
greet()Output
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.
def greet(name):
print("Hello,", name)
greet("Alice")
greet("John")Output
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.
def add_numbers(a, b):
print(a + b)
add_numbers(10, 5)Output
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.
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result)Output
20
Default Parameters
Assign a default value to a parameter when the function should work even if that argument is omitted.
def greet(name="Guest"):
print("Hello,", name)
greet()
greet("Emma")Output
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.
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.
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.
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.
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.
def countdown(number):
if number == 0:
return
print(number)
countdown(number - 1)
countdown(5)Output
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().
square = lambda x: x * x
print(square(6))Output
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.