Python Functions

posted 11 min read

A function is a fundamental building block that encapsulates specific actions or computations. As in mathematics, where functions take inputs and produce outputs, programming functions perform similarly. They take inputs, execute predefined actions or calculations, and then return an output. They are crucial for modular programming.
You will learn how to master function-based programming with the help of this tutorial, which covers everything from basic concepts to complex approaches. Discover how functions improve readability, structure code, and encourage productive development methods. This course enables you to use Python functions efficiently, keeping your codebase stable and manageable.

Understanding the Functions

A designated block of code that carries out a particular purpose is called a function. It typically takes inputs, processes them, and returns a result. Here's an example of a simple function:

def greet(name):
    return f"Hello, {name}!"
message = greet("Alice")
print(message)  # Output: Hello, Alice!

They can take inputs, known as parameters, and produce outputs, known as return values. Parameters are specified in the function definition, while arguments are the values passed to the function when it's called.

Structure of Functions

The structure of function includes its syntax, naming conventions, parameters and docstrings for clarity:

1. Syntax

Functions are defined using the 'def' keyword followed by the function name and parameters enclosed in parentheses. The code to be performed is included in the function body, which is nested. Here is the syntax:

def calculate_area(radius):
    return 3.14 * radius ** 2
Tip: For Naming Conventions, choose meaningful names for your functions that describe what they do. Use lowercase letters and underscores to separate words for better readability.

2. Parameters and Arguments

Parameters are like inputs for functions. When defining the function, they are enclosed in parenthesis. They can have multiple parameters.

A. Positional Arguments

Positional arguments are passed to a function in the order they're defined in the function signature. The function uses the order of arguments to determine which value corresponds to which parameter.

def greet(name, greeting):
    return f"{greeting}, {name}!"
# Positional arguments
message = greet("Alice", "Hello")
print(message)  # Output: Hello, Alice!


In this example, "Alice" is assigned to the 'name' parameter, and "Hello" is assigned to the 'greeting' parameter based on their positions.

B. Keyword Arguments

Keyword arguments are explicitly assigned to parameters by specifying the parameter name followed by the value during function invocation. This allows for flexibility in the order of arguments.

def greet(name, greeting):
    return f"{greeting}, {name}!"
# Keyword arguments
message = greet(greeting="Hi", name="Bob")
print(message)  # Output: Hi, Bob!


Here, arguments are given values according to their names, not where they appear in the function signature.

C. Default Values

The function definition specifies default values for the arguments. In the event that a parameter during function call is called without an argument, the default value is used.

def greet_with_default(name, greeting="Hello"):
    return f"{greeting}, {name}!"
# Using default value
message = greet_with_default("Charlie")
print(message)  # Output: Hello, Charlie!
In this example, "Hello" is the default value for the 'greeting' parameter. When no value is provided for 'greeting', it defaults to "Hello".

3. Docstrings

Docstrings explain what a function does. They are placed inside triple quotes under the function definition. They help other developers understand your function.

def multiply(a, b):
    This function multiplies two numbers.
    Input: a (number), b (number)
    print(a * b)

Calling the Functions

To call a function, simply write its name followed by parentheses and any required arguments.

multiply(a, b)

Arguments are values passed to a function when it's called. They can be passed by position or by keyword.

multiply(2, 6)

Functions can return values using the return statement. You can capture the return value of a function and use it in your code.

result = multiply(2, 6)
print(result)  # Output: 12

The returned value is then stored in the variable result and printed.

Scope and Variables

Scope refers to the accessibility of variables within a program. Variables in Python can be local or global in scope.

1. LEGB Rule

The LEGB rule defines the order in which Python searches for variable names. Let's explore each level of the LEGB rule with explanations and code examples:

local: Variables defined inside a function are only available inside that function and have a local scope.

Enclosing: If a variable is not found in the local scope, Python searches the enclosing scope, typically the enclosing function.

Global: Variables defined at the top level of a module or explicitly declared as global have global scope and are accessible throughout the module.

Built-in: If a variable is not found in the local, enclosing, or global scope, Python finally searches the built-in scope, which contains names like 'print', 'len', etc., provided by the Python built-in modules.

The code is as followed:

# Local scope
def my_function():
    local_variable = "I am local"
my_function()  # Output: I am local
# Enclosing scope
def outer_function():
    enclosing_variable = "I am enclosing"
    def inner_function():  # Corrected indentation
    inner_function()  # Output: I am enclosing
# Global scope
global_variable = "I am global"
def my_function():
my_function()  # Output: I am global
# Built-in scope
print("Hello, world!")  # Output: Hello, world!

2. Handling Variable Access

You can use the global keyword to access and modify global variables from within a function.

x = 10
def increment():
    global x
    x += 1
    return x
print(increment())  # Output: 11
Caution: Consistently check for and rectify indentation errors to prevent unexpected behavior or syntax issues in your code.

Advanced Functions and Concepts

 There are some advanced functions and concepts in functions.

1. Anonymous Functions(LAMBDA)

Lambda functions are anonymous, tiny functions with a single expression and any number of arguments. They are often used for quick, easy tasks.

double = lambda x: x * 2
print(double(5))  # Output: 10

2. Recursion: Basics and Examples

A function that calls itself is known as recursion in programming. It's often used to solve problems that can be broken down into smaller, similar subproblems.

def factorial(n):
    if n == 0:
        return 1
        return n * factorial(n - 1)
print(factorial(5))  # Output: 120

Best Practices and Tips

Here are some best practices to follow when working with functions in Python:

  1. Minimize the use of global variables as they can lead to unexpected behaviour and make code harder to understand and debug. Instead, pass variables as arguments to functions or use local variables where possible.
  2. Functions that use default argument values may be simpler to use, but take caution when using them excessively. Use them minimally, and only where they enhance the functions' usefulness and clarity.
Q: How do I handle errors in Python functions?
A: Error handling in Python functions can be done using try-except blocks to catch and handle exceptions. This allows you to gracefully handle errors and prevent your program from crashing unexpectedly.


In conclusion, You are able to create functions that efficiently encapsulate functionality and encourage code reuse by understanding the basic ideas of function declaration, argument passing, and variable scoping. The readability and dependability of your codebase are further improved by adhering to best practices, which include giving meaningful names to functions, documenting them, and gracefully resolving failures. You'll be well-prepared to take on a variety of programming jobs and create reliable, scalable Python apps if you have a firm grasp of functions and adhere to accepted rules.


Here are some recommended links for more reference:

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Python Lambda Functions

Muzzamil Abbas - Mar 5

Mastering Lambda Functions in Python: A comprehensive Guide

Abdul Daim - May 6

Python Return Statement

Muzzamil Abbas - Mar 6

Python Parameters and Arguments

Muzzamil Abbas - Feb 25

Understanding the Functions: Return Statement

Muzzamil Abbas - Mar 3