Saturday 3 August 2024

7 Things I Should’ve Learnt Much Earlier For Python Functions

 

Closures

What: Functions that capture the local state of the environment in which they were created.


Why: Useful for creating function factories or decorators.


def outer(x):

    def inner(y):

        return x + y

    return inner


add_five = outer(5)

print(add_five(10))  

#clcoding.com

Function Annotations

What: Provides a way to attach metadata to function arguments and return values.


Why: Helps in providing hints about the expected data types, which improves code readability.


def add(a: int, b: int) -> int:

    return a + b


print(add(2, 3))  


#clcoding.com

Returning Multiple Values

What: Python allows functions to return multiple values as a tuple.


Why: Enables you to return complex data without creating a class or data structure.


def get_name_age():

    name = "clcoding"

    age = 30

    return name, age


name, age = get_name_age()

print(name, age)  

#clcoding.com

clcoding 30

Docstrings

What: Strings that describe what a function does, placed as the first line within the function body.


Why: Helps in documenting your code, making it more understandable.


def add(a, b):

    """Returns the sum of two numbers."""

    return a + b


print(add.__doc__)  


#clcoding.com

Returns the sum of two numbers.

Lambda Functions

What: Small, anonymous functions defined using lambda.


Why: Useful for short functions that are used once or passed as arguments to higher-order functions.


double = lambda x: x * 2

print(double(5))  


items = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x**2, items))

print(squared)  


#clcoding.com

10

[1, 4, 9, 16, 25]

***args and kwargs

What: args and *kwargs allow functions to accept an arbitrary number of positional and keyword arguments, respectively.


Why: Useful when you don’t know in advance how many arguments will be passed.


def print_args(*args):

    for arg in args:

        print(arg)


print_args(1, 2, 3)  


def print_kwargs(**kwargs):

    for key, value in kwargs.items():

        print(f"{key}: {value}")


print_kwargs(name="clcoding", age=30)

#clcoding.com

1

2

3

name: clcoding

age: 30

Default Arguments

What: Allows you to set default values for function parameters.


Why: Makes your functions more flexible and easier to use.


def greet(name="Guest"):

    print(f"Hello, {name}!")


greet()             

greet("clcoding")   


#clcoding.com

Hello, Guest!

Hello, clcoding!

0 Comments:

Post a Comment

Popular Posts

Categories

AI (29) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (122) C (77) C# (12) C++ (82) Course (67) Coursera (195) Cybersecurity (24) data management (11) Data Science (100) Data Strucures (7) Deep Learning (11) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (840) Python Coding Challenge (279) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses