Functions
A function is an organized, reusable block of code. Python uses the def keyword to define functions.
With functions, you don't need to rewrite the same code over and over. Just call the function's name with the appropriate arguments. Functions also make code easier to read, test, and fix, because each piece of logic is isolated in its own block.
Python supports various kinds of parameters that make functions very flexible. You can combine positional, default, *args, **kwargs, and keyword-only parameters in a single function. Lambda or anonymous functions are also available for simple operations that need just a one-line expression. In addition, functions can have return type hints for documenting the returned data type.
Parameter Types:
- Positional — by order
- Default — has a built-in value
- *args — extra positional arguments (tuple)
- **kwargs — extra keyword arguments (dict)
- Keyword-only — must be named
Code Example
# Basic function
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("John")) # Hello, John!
print(greet("Alice", "Welcome")) # Welcome, Alice!
# *args and **kwargs
def total(*args):
return sum(args)
print(total(1, 2, 3, 4)) # 10
# Lambda (anonymous function)
square = lambda x: x ** 2
print(square(5)) # 25
# Used with map/filter
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares) # [1, 4, 9, 16]
Code Explanation
- Basic function:
def greet(name, greeting="Hello")— thenameparameter is required, whilegreetinghas the default value"Hello". If not provided, the default value is used. - Return value: The
returnkeyword returns a value to the function caller. A function withoutreturnreturnsNone. - *args:
def total(*args)— the asterisk captures all extra positional arguments into the tupleargs.sum(args)sums all the elements. - Lambda:
lambda x: x ** 2is a one-line anonymous function. Equivalent todef square(x): return x ** 2but more concise. - map():
map(lambda x: x**2, numbers)applies the lambda function to each element ofnumbers.list()converts the map result into a list.
Everyday Example
A cash register application needs to calculate the purchase total with discount and tax. Functions make this calculation easy without repeating code.
def calc_total(prices, discount_pct=0, tax_pct=11):
subtotal = sum(prices)
discount = subtotal * discount_pct / 100
after_discount = subtotal - discount
tax = after_discount * tax_pct / 100
total = after_discount + tax
return total
cart = [50000, 75000, 30000]
print(f"Total: ${calc_total(cart, discount_pct=10):,.0f}")
# Total: $154,550
Summary
Functions are the primary foundation of code organization in Python. With support for various parameter types and lambdas, functions can be used from the simplest to the most complex. Use functions to reduce code duplication, improve readability, and make testing easier.