RBDBlog

Python Functions Tutorial

Functions in Python allow you to group code into reusable blocks, making your code more modular and easier to maintain. This Python tutorial covers the basics of defining and using functions in Python.

1. Function Definition

You can define a Python function using the def keyword, followed by the function name and a pair of parentheses. The function body is indented.

def greet():
    print("Hello, world!")

# Call the function
greet()

2. Function Parameters

Functions can take parameters, allowing you to pass values to the function. Parameters are specified within the parentheses.

def greet(name):
    print("Hello, " + name + "!")

# Call the function with an argument
greet("Alice")

3. Default Parameters

You can provide default values for parameters, making them optional.

def greet(name="Guest"):
    print("Hello, " + name + "!")

# Call the function without providing an argument
greet()

# Call the function with an argument
greet("Bob")

4. Return Statement

Functions can return values using the return statement.

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

result = add_numbers(3, 5)
print(result)

5. Multiple Return Values

A function can return multiple values as a tuple.

def square_and_cube(x):
    square = x ** 2
    cube = x ** 3
    return square, cube

result = square_and_cube(4)
print(result)  # Output: (16, 64)

6. Scope of Variables

Variables defined inside a function have local scope and are only accessible within that function.

def my_function():
    local_variable = "I am local"
    print(local_variable)

my_function()
# print(local_variable)  # This would result in an error

7. Docstrings

You can add documentation to your functions using docstrings.

def multiply(a, b):
    """
    Multiply two numbers and return the result.
    
    Parameters:
    a (int): The first number.
    b (int): The second number.
    
    Returns:
    int: The product of a and b.
    """
    return a * b

8. Lambda Functions

Lambda functions in python are anonymous functions defined using the lambda keyword.

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

9. Recursion

Functions can call themselves, enabling recursion.

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

This Python tutorial covers the basics of functions. As you continue learning, explore more advanced tutorials on topics such as function decorators, closures, and higher-order functions to enhance your understanding of Python’s powerful function capabilities. Practice writing and using Python functions to improve your programming skills. This is the most advanced Python tutorial on the site for now.

Return to homepage