10. Combining Concepts
def trace(func):
"""A decorator that traces function calls."""
def wrapper(*args, **kwargs):
print(f"TRACE: calling {func.__name__}() with {args}, {kwargs}")
result = func(*args, **kwargs)
print(f"TRACE: {func.__name__}() returned {result}")
return result
return wrapper
@trace
def compute_area(length: float, width: float) -> float:
"""Compute the area of a rectangle."""
return length * width
area = compute_area(3.0, 4.5)
# clcoding.com
TRACE: calling compute_area() with (3.0, 4.5), {}
TRACE: compute_area() returned 13.5
9. Decorators
def debug(func):
"""A decorator that prints the function
signature and return value."""
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with {args} and {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@debug
def add(a, b):
"""Add two numbers."""
return a + b
add(3, 4)
# clcoding.com
Calling add with (3, 4) and {}
add returned 7
7
8. Lambda Functions
square = lambda x: x * x
print(square(5))
# clcoding.com
25
7. First-Class Functions
def square(x):
"""Return the square of x."""
return x * x
def apply_function(func, value):
"""Apply a function to a value
and return the result."""
return func(value)
result = apply_function(square, 4)
print(result)
# clcoding.com
16
6. Docstrings
def divide(x, y):
"""
Divide x by y and return the result.
:param x: numerator
:param y: denominator
:return: division result
"""
return x / y
result = divide(10, 2)
print(result)
# clcoding.com
5.0
5. Function Annotations
def multiply(x: int, y: int) -> int:
"""Multiply two integers
and return the result."""
return x * y
result = multiply(3, 4)
print(result)
# clcoding.com
12
4. Arbitrary Keyword Parameters
def print_info(**kwargs):
"""Print key-value pairs
from keyword arguments."""
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Clcoding", age=30, city="Earth")
# clcoding.com
name: Clcoding
age: 30
city: Earth
3. Arbitrary Positional Parameters
def sum_all(*args):
"""Sum all given arguments."""
return sum(args)
total = sum_all(1, 2, 3, 4, 5)
print(total)
# clcoding.com
15
2. Keyword Parameters
def greet(name, greeting="Hello"):
"""Greet someone with a provided
greeting or a default greeting."""
return f"{greeting}, {name}!"
message = greet("Clcoding")
print(message)
message = greet("Python", "Hi")
print(message)
# clcoding.com
Hello, Clcoding!
Hi, Python!
1. Basic Function Definition
def add(a, b):
"""Add two numbers and
return the result."""
return a + b
result = add(3, 5)
print(result)
# clcoding.com
8
0 Comments:
Post a Comment