# Example: Basic function
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
# Example: Default argument
def power(base, exponent=2):
return base ** exponent
print(power(3)) # Output: 9
print(power(3, 3)) # Output: 27
# Example: *args for variable-length positional arguments
def add(*args):
return sum(args)
print(add(1, 2, 3)) # Output: 6
# Example: **kwargs for variable-length keyword arguments
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_details(name="Alice", age=30)
# Output:
# name: Alice
# age: 30
# Example: Lambda function
square = lambda x: x ** 2
print(square(4)) # Output: 16
# Example: Lambda with map
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared) # Output: [1, 4, 9, 16]
# Example: Scope
def outer():
x = 10 # Enclosing scope
def inner():
nonlocal x
x += 5
return x
return inner()
print(outer()) # Output: 15
# Example: A simple decorator
def decorator(func):
def wrapper():
print("Before the function call")
func()
print("After the function call")
return wrapper
@decorator
def say_hello():
print("Hello!")
# Example: Higher-order function
def apply_function(func, value):
return func(value)
print(apply_function(lambda x: x * 2, 5)) # Output: 10
def multiply(a, b):
"""Returns the product of two numbers."""
return a * b
print(multiply.__doc__) # Output: Returns the product of two numbers.
def generate_numbers(n):
for i in range(n):
yield i
for num in generate_numbers(3):
print(num)
# Output:
#0
#1
#2
def greet(name: str) -> str:
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
print(greet.__annotations__) # Output: {'name': <class 'str'>, 'return': <class 'str'>}