Functions are reusable blocks of code that perform a specific task.
Python Functions
Functions allow you to write reusable, organized code. A function is defined once and called many times.
Benefits
DRY (Don't Repeat Yourself)
Modularity
Easier testing and debugging
Better readability
Syntax
<pre><code># Defining a function
def greet(name):
"""Greet a person by name.""" # docstring
return f"Hello, {name}!"
# Calling a function
print(greet("Alice")) # Hello, Alice!
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Bob")) # Hello, Bob!
print(greet("Bob", "Hi")) # Hi, Bob!
# Keyword arguments
def create_profile(name, age, city):
return f"{name}, {age}, from {city}"
print(create_profile(age=25, name="Alice", city="NYC"))
# *args — variable positional arguments
def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3, 4, 5)) # 15
# **kwargs — variable keyword arguments
def display_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, city="NYC")
# Returning multiple values
def min_max(numbers):
return min(numbers), max(numbers)
small, large = min_max([3, 1, 4, 1, 5, 9])
</code></pre>
Revision Notes
• def function_name(params): to define
• return to send back a value
• Docstring """ """ documents the function
• Default params: def f(x=10)
• *args for variable positional args
• **kwargs for variable keyword args
• Return multiple values as tuple
def is_palindrome(s):
cleaned = s.lower().replace(" ", "")
return cleaned == cleaned[::-1]
test_cases = ["racecar", "A man a plan a canal Panama", "hello", "Was it a car or a cat I saw"]
for test in test_cases:
print(f"{test!r}: {is_palindrome(test)})