Python Functions Basics

October 7, 2025

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 function
  • add_numbers โ†’ function name
  • a, 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:

TypeDescriptionExample
Positional ArgumentsValues are passed in orderadd(2, 3)
Keyword ArgumentsUse parameter names when passing valuesadd(a=2, b=3)
Default ArgumentsParameters have default valuesadd(a=2, b=5)
Variable-Length ArgumentsCan 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

TypeDescriptionExample
Built-in FunctionsAlready provided by Pythonprint(), len(), sum(), max()
User-defined FunctionsCreated by programmersdef 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

ConceptDescriptionExample
Function DefinitionDefine a functiondef func():
Calling FunctionExecute functionfunc()
Return ValueSend data backreturn value
Default ArgumentUse default valuedef func(x=10)
Keyword ArgumentSpecify by namefunc(y=5)
Variable-LengthAccept multiple values*args, **kwargs
LambdaOne-line anonymous functionlambda 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

ยฉ Copyright 2025 โ€” Fessorpro

Terms of Service / Privacy Policy