Python Functions – Organize and Reuse Your Code

Last updated 5 months, 1 week ago | 375 views 75     5

Tags:- Python

Functions are fundamental to writing clean, efficient, and reusable code in Python. They allow you to group code into logical blocks that can be called multiple times, with or without inputs, and can return outputs.

This tutorial includes:

  • What functions are and why they’re useful

  • Defining and calling functions

  • Parameters vs arguments

  • Return values

  • Default, keyword, and variable-length arguments

  • Scope and lifetime

  • Lambda functions

  • Common pitfalls and tips

  • A complete example at the end


✅ What is a Function?

A function is a block of code that only runs when called. It can take inputs (parameters) and return outputs.

Benefits of Using Functions

  • Avoid repetition (DRY principle)

  • Improve readability and structure

  • Easy debugging and testing

  • Promote code reusability


Defining a Function

def greet():
    print("Hello, welcome to Python!")

Calling the Function

greet()

Output:

Hello, welcome to Python!

Function with Parameters

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

Output:

Hello, Alice!

Returning Values with return

def square(number):
    return number * number

result = square(4)
print(result)

Output:

16

Multiple Parameters

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

print(add(5, 3))

⚙️ Default Parameters

def greet(name="Guest"):
    print(f"Hello, {name}!")
greet()         # Hello, Guest!
greet("John")   # Hello, John!

Keyword Arguments

def describe_pet(animal, name):
    print(f"{name} is a {animal}.")

describe_pet(animal="dog", name="Buddy")

Variable-Length Arguments

✳️ *args – Multiple Positional Arguments

def add_all(*numbers):
    return sum(numbers)

print(add_all(1, 2, 3, 4))  # 10

✳️ **kwargs – Multiple Keyword Arguments

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

print_user_info(name="Alice", age=30)

Scope: Local vs Global

x = 10  # Global variable

def show():
    x = 5  # Local variable
    print("Inside:", x)

show()
print("Outside:", x)

Output:

Inside: 5
Outside: 10

Lambda Functions – Anonymous One-Liners

square = lambda x: x * x
print(square(5))  # 25

Another Example

add = lambda a, b: a + b
print(add(3, 4))  # 7

Use lambdas for small, throwaway functions — not complex logic.


Complete Example: Calculator

def calculator(a, b, operation):
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    else:
        return "Unknown operation"

print(calculator(10, 5, "add"))        # 15
print(calculator(10, 0, "divide"))     # Cannot divide by zero

Common Pitfalls

Mistake Description Fix
Forgetting to call function def func(): does nothing unless called Use func() to call it
Confusing parameters vs args Parameters are declared, arguments are passed Understand function signatures
Modifying global variables Can cause bugs Use global keyword carefully
No return where expected Function returns None Add a return statement

Tips and Best Practices

  • ✅ Use functions to break large tasks into small steps

  • ✅ Use meaningful names for functions and parameters

  • ✅ Add docstrings for documentation

def greet(name):
    """Prints a greeting to the user."""
    print(f"Hello, {name}")
  • ✅ Keep functions short and focused on a single task

  • ✅ Use type hints (Python 3.5+):

def add(a: int, b: int) -> int:
    return a + b

Summary Table

Concept Example
Basic function def func():
With parameters def func(x):
Return value return x * x
Default values def greet(name="Guest")
Variable args *args, **kwargs
Lambda function lambda x: x + 1
Docstring """Function doc."""

What’s Next?

After mastering functions, explore:

  • Recursion (functions calling themselves)

  • Function decorators

  • First-class functions & closures

  • Generators & yield