Python Function Implementation with Decorators and Generators
def compute_value(input_num):
'''
Calculate 2*input_num + 1
:param input_num: integer value
:return: computation result
'''
result = 2 * input_num + 1
return result
output = compute_value(3)
print(output)
Function components:
def: keyword for function declaration- Function name: identifier used to call the function
- Function body: contains the logic and computations
- Parameters: values passed into the function
- Return value: data returned to the caller after execution
Benefits of Using Functinos
- Code reuse and reduction
- Consistent implementation
- Maintainability
Function Parameters
Python supports several parameter types:
Positional Parameters
def greet_user(username):
print(f"Hello {username}")
greet_user('john_doe')
Default Parameters
def user_profile(name, level=1):
print(f"{name}: Level {level}")
user_profile('alice', 5) # Custom level
user_profile('bob') # Default level
Note: Default parameters must follow non-default parameters
Variable Positional Arguments (*args)
def process_items(*items):
print(items)
process_items(10, 20, 30, 40)
numbers = [15, 25, 35]
process_items(*numbers)
Variable Keyword Arguments (**kwargs)
def build_profile(**attributes):
print(attributes)
build_profile(name='sarah', experience=3)
user_data = {'name': 'mike', 'age': 28}
build_profile(**user_data)
Variable Scopes
Global vs Local Variables
GLOBAL_NAME = 'admin' # Global variable
def modify_name():
local_name = 'user123' # Local variable
print('Inside function:', local_name)
modify_name()
print('Outside function:', GLOBAL_NAME)
Global and Nonlocal Declarations
counter = 100
def update_counter():
global counter
counter = 200
update_counter()
print(counter) # Output: 200
def outer_function():
value = 50
def inner_function():
nonlocal value
value = 75
inner_function()
print(value) # Output: 75
outer_function()
Recursive Functions
Recursive functions call themselves with modified parameters until reaching a base case.
def recursive_divide(number):
print(f"Current value: {number}")
if number // 2 == 0:
return number
result = recursive_divide(number // 2)
print(f"Backtracking: {number} -> {result}")
return result
recursive_divide(20)
Lambda Functions
Anonymous functions defined with lambda syntax:
# Immediate invocation
squares = [(lambda x: x**2)(x) for x in range(6)]
print(squares) # [0, 1, 4, 9, 16, 25]
# Single calculation
result = (lambda x: x*3)(5)
print(result) # 15
# Assign to variable
square_func = lambda x: x*x
print(square_func(7)) # 49
Basic Recursion Example
def recursive_call():
print("Recursive call")
recursive_call() # Self-invocation
# Note: Python has recursion depth limit (typically ~1000)