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.

0 Interaction
1.3K Views
Views
32 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home