Python Functions Explained with Examples

Python Function is a block of code that can be executed multiple times from different parts of your program. It’s a way to group a set of statements together to perform a specific task.

Syntax

A Python function is defined using the def keyword, followed by the function name and parentheses ().

def function_name(parameters):
    # function body
# statements to be executed when the function is called

Example:

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

In this example:

  • greet: the function name.
  • name: it is a parameter, which is a value passed to the function when it’s called.

Rules for Naming Python Functions

  • Function names must adhere to certain rules to ensure they are valid and can be used correctly in your code.
  • Function names can contain letters (both uppercase and lowercase), digits, and underscores.
  • They must start with a letter or an underscore.
  • Python is case-sensitive, so my_function and My_Function are considered different function names.
  • You cannot use Python keywords as function names as they have special meanings in Python.

Example:

# This is invalid
def def():
    print("Invalid function name")

This def function is invalid.

Use meaningful and descriptive names for functions to make your code more readable and understandable.

def calculate_area(radius):
return 3.14 * radius ** 2

Python conventionally uses snake_case for function names where words are lowercase and separated by underscores.

def calculate_total_cost(price, quantity):
    return price * quantity

Function names should not contain special characters other than underscores.

# This is invalid
def calculate$cost():
    print("Invalid function name")

Function names cannot start with a digit.

# This is invalid
def 123_function():
    print("Invalid function name")

Parameters

Python functions can accept parameters to receive inputs that can be used inside the function.

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

greet("Alice")  # Output: Hello, Alice!

Return Value

Functions can return values using the return statement.

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

result = add_numbers(5, 3)
print(result)  # Output: 8

Function Calling

To call a function, you need to use its name followed by parentheses () and pass any required arguments (parameters) inside the parentheses.

greet("John")  # Output: Hello, John!

Function Documentation (Docstrings)

It’s good practice to document functions using docstrings for clear documentation.

def square(n):
    """
    This function returns the square of a number.
    """
return n ** 2