Python Functions Basics
Functions are the heart of Python programming. They help you write cleaner, reusable, and more efficient code by grouping related statements together.
If you find yourself writing the same code multiple times, you probably need a function!
In this blog, weโll cover:
- What functions are
- Why we use them
- How to create and call functions
- Function arguments and return values
- Default, keyword, and variable-length arguments
- Lambda (anonymous) functions
- Built-in vs. user-defined functions
Letโs begin! ๐
๐งฉ What is a Function?
A function is a block of organized and reusable code that performs a specific task.
You define a function once, and you can call it anytime in your program.
โ Example:
def greet():
print("Hello, welcome to Python!")
To call the function:
greet()
Output:
Hello, welcome to Python!
๐งฑ Why Use Functions?
Functions make your code:
- ๐งน Clean & Readable โ breaks code into smaller, logical parts
- ๐ Reusable โ define once, use anywhere
- ๐งฎ Maintainable โ easier to debug or modify
- โ๏ธ Modular โ promotes structured programming
๐น Defining and Calling Functions
๐งฉ Syntax:
def function_name(parameters):
"""docstring (optional): explains what the function does"""
# code block
return value
โ Example:
def add_numbers(a, b):
"""This function adds two numbers."""
return a + b
result = add_numbers(5, 3)
print("Sum:", result)
Output:
Sum: 8
๐ Explanation:
def
โ keyword to define a functionadd_numbers
โ function namea, b
โ parameters (inputs)return
โ sends a result back to the caller
๐น Function Without Return Value
Functions donโt always need to return something.
They can just perform an action, like printing.
def display_message():
print("Learning Python Functions!")
Output:
Learning Python Functions!
๐น Function With Return Value
return
is used when you want to send data back to the point where the function was called.
def square(num):
return num * num
print(square(4))
Output:
16
If no return statement is given, Python automatically returns None
.
๐น Function Parameters and Arguments
Functions can take inputs (known as parameters) and can be called with arguments (actual values you pass).
๐งฉ Types of Function Arguments:
Type | Description | Example |
---|---|---|
Positional Arguments | Values are passed in order | add(2, 3) |
Keyword Arguments | Use parameter names when passing values | add(a=2, b=3) |
Default Arguments | Parameters have default values | add(a=2, b=5) |
Variable-Length Arguments | Can take multiple arguments | *args, **kwargs |
โ 1. Positional Arguments
def greet_user(name, age):
print(f"Hello {name}, you are {age} years old.")
greet_user("Alice", 25)
Output:
Hello Alice, you are 25 years old.
โ 2. Default Arguments
If you donโt pass an argument, the default value is used.
def greet(name="User"):
print("Hello", name)
greet() # Uses default
greet("Niel") # Uses passed value
Output:
Hello User
Hello Niel
โ 3. Keyword Arguments
You can specify which parameter each argument belongs to.
def display_info(name, city):
print(f"{name} lives in {city}.")
display_info(city="Mumbai", name="Ravi")
Output:
Ravi lives in Mumbai.
โ
4. Variable-Length Arguments (*args
and **kwargs
)
โค *args
โ Multiple positional arguments
def add_numbers(*args):
return sum(args)
print(add_numbers(1, 2, 3, 4))
Output:
10
โค **kwargs
โ Multiple keyword arguments
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_details(name="Anil", age=30, country="India")
Output:
name: Anil
age: 30
country: India
๐น Nested Functions (Function inside Function)
You can define a function inside another function.
def outer():
def inner():
print("Inner function executed.")
inner()
print("Outer function executed.")
outer()
Output:
Inner function executed.
Outer function executed.
๐น Lambda (Anonymous) Functions
A lambda function is a small, one-line anonymous function โ useful for short, temporary operations.
๐งฉ Syntax:
lambda arguments: expression
โ Example 1:
square = lambda x: x**2
print(square(5))
Output:
25
โ
Example 2: Using lambda with map()
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares)
Output:
[1, 4, 9, 16]
๐น Built-in vs. User-defined Functions
Type | Description | Example |
---|---|---|
Built-in Functions | Already provided by Python | print(), len(), sum(), max() |
User-defined Functions | Created by programmers | def greet():, def add(): |
Example using both:
def double(x):
return x * 2
nums = [1, 2, 3, 4]
print("Original:", nums)
print("Doubled:", list(map(double, nums)))
Output:
Original: [1, 2, 3, 4]
Doubled: [2, 4, 6, 8]
๐น The return
Statement in Detail
You can return:
- A single value
- Multiple values (as a tuple)
โ Example 1: Return multiple values
def calc(a, b):
add = a + b
sub = a - b
return add, sub
result = calc(10, 5)
print(result)
Output:
(15, 5)
๐งฉ Summary Table
Concept | Description | Example |
---|---|---|
Function Definition | Define a function | def func(): |
Calling Function | Execute function | func() |
Return Value | Send data back | return value |
Default Argument | Use default value | def func(x=10) |
Keyword Argument | Specify by name | func(y=5) |
Variable-Length | Accept multiple values | *args, **kwargs |
Lambda | One-line anonymous function | lambda x: x+1 |
๐ก Final Thoughts
Functions are the foundation of structured programming in Python.
They make your code modular, reusable, and easy to maintain.
๐ In summary:
- Use
def
to create a function - Use
return
to send results back - Use arguments to make functions dynamic
- Use
lambda
for short, quick tasks
Once you master functions, youโll be ready to build:
- Reusable data analysis tools
- Complex trading strategies
- Modular backend applications
- Clean automation scripts