Functions in Python

In Python, functions are reusable blocks of code that perform a specific task. They help in structuring code and promoting reusability, making it easier to read and maintain.

1. Basic Function Syntax

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

Example


    def greet(name):
    return "Hello, " + name

Explanation: The function greet takes a name parameter and returns a greeting message.

2. Lambda Functions

Lambda functions are small anonymous functions defined using the lambda keyword. They are useful for quick, single-use functions.

Example


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

Explanation: The lambda function takes an input x and returns x * 2.

3. Higher-Order Functions

Higher-order functions accept other functions as parameters or return functions. Functions like map, filter, and reduce are examples of higher-order functions in Python.

Using map


    numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # Output: [1, 4, 9, 16]

Explanation: map applies the lambda function to each item in the numbers list.

4. Decorators

Decorators allow you to modify the behavior of a function without changing its code. They are defined using the @ symbol above a function.

Example

def greet_decorator(func):
    def wrapper():
      print("Starting function:")
        func()
      print("Function completed.")
    return wrapper

@greet_decorator
def say_hello():
    print("Hello!")

say_hello()

Explanation: The @greet_decorator applies the greet_decorator function to say_hello, modifying its behavior to print additional messages before and after the function call.

Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.

top-home