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