7 min read
ā¢Question 9 of 41easyFunctions in Python
Defining and using functions.
What You'll Learn
- How to define and call functions
- Parameters: positional, keyword, default, *args, **kwargs
- Return values and multiple returns
- Lambda functions and functional programming
- Scope and closures
Understanding Functions
Functions are reusable blocks of code that perform a specific task. They help organize code, reduce repetition, and make programs easier to maintain.
Defining and Calling Functions
code.pyPython
# Basic function
def greet(name):
"""Greet a person by name."""
return f"Hello, {name}!"
# Calling the function
message = greet("Alice")
print(message) # "Hello, Alice!"
# Function without return (returns None)
def say_hello():
print("Hello!")
result = say_hello() # Prints "Hello!"
print(result) # NoneFunction Parameters
Positional and Keyword Arguments
code.pyPython
def describe_person(name, age, city):
print(f"{name} is {age} from {city}")
# Positional arguments (order matters)
describe_person("Alice", 25, "NYC")
# Keyword arguments (order doesn't matter)
describe_person(age=25, city="NYC", name="Alice")
# Mixed (positional first, then keyword)
describe_person("Alice", city="NYC", age=25)Default Parameters
code.pyPython
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Bob", "Hi") # "Hi, Bob!"
greet("Charlie", greeting="Hey") # "Hey, Charlie!"
# CAUTION: Mutable default arguments
def add_item(item, items=[]): # BAD! List persists
items.append(item)
return items
# Correct way:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items*args - Variable Positional Arguments
code.pyPython
def sum_all(*args):
"""Sum any number of arguments."""
print(f"Received: {args}") # Tuple
return sum(args)
sum_all(1, 2, 3) # 6
sum_all(1, 2, 3, 4, 5) # 15
# Combine with regular params
def greet_all(greeting, *names):
for name in names:
print(f"{greeting}, {name}!")
greet_all("Hello", "Alice", "Bob", "Charlie")**kwargs - Variable Keyword Arguments
code.pyPython
def print_info(**kwargs):
"""Print key-value pairs."""
print(f"Received: {kwargs}") # Dictionary
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="John", age=30, city="NYC")
# Combine all parameter types
def complex_func(a, b, *args, option=True, **kwargs):
print(f"a={a}, b={b}")
print(f"args={args}")
print(f"option={option}")
print(f"kwargs={kwargs}")
complex_func(1, 2, 3, 4, option=False, x=10, y=20)Return Values
code.pyPython
# Single return
def square(x):
return x ** 2
# Multiple returns (returns tuple)
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers)
low, high, total = get_stats([1, 2, 3, 4, 5])
print(low, high, total) # 1 5 15
# Early return
def is_adult(age):
if age < 0:
return None # Invalid
return age >= 18Lambda Functions
Anonymous, single-expression functions:
code.pyPython
# Syntax: lambda arguments: expression
square = lambda x: x ** 2
print(square(5)) # 25
# Multiple arguments
add = lambda a, b: a + b
print(add(3, 4)) # 7
# Common use: sorting
people = [("Alice", 25), ("Bob", 30), ("Charlie", 20)]
people.sort(key=lambda p: p[1]) # Sort by age
# With map, filter, reduce
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums)) # [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x%2==0, nums)) # [2, 4]
from functools import reduce
total = reduce(lambda a, b: a + b, nums) # 15Scope: Local, Global, Nonlocal
code.pyPython
global_var = "I'm global"
def outer():
outer_var = "I'm in outer"
def inner():
local_var = "I'm local"
print(global_var) # Access global
print(outer_var) # Access enclosing scope
print(local_var) # Access local
inner()
# Modifying global
count = 0
def increment():
global count
count += 1
# Modifying enclosing scope
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return incrementDocstrings
code.pyPython
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Args:
length: The length of the rectangle
width: The width of the rectangle
Returns:
The area (length * width)
"""
return length * width
# Access docstring
print(calculate_area.__doc__)
help(calculate_area)Interview Tip
When asked about Python functions:
defkeyword defines functions- Parameters: positional, keyword, default, *args, **kwargs
- Functions return None if no return statement
- Lambda for simple, single-expression functions
- Understand scope: local, global, nonlocal
- Don't use mutable default arguments