0% found this document useful (0 votes)
6 views10 pages

python_functions_guide_10_pages

This document is a practical guide to Python functions, covering their definition, parameters, return values, and design principles. It explains key concepts such as local and global scope, lambda expressions, and recursion, while emphasizing the importance of documentation and testing. The guide provides best practices for creating well-structured and maintainable functions in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views10 pages

python_functions_guide_10_pages

This document is a practical guide to Python functions, covering their definition, parameters, return values, and design principles. It explains key concepts such as local and global scope, lambda expressions, and recursion, while emphasizing the importance of documentation and testing. The guide provides best practices for creating well-structured and maintainable functions in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Functions - Practical Guide

A concise 10-page introduction to defining, calling, documenting, and designing functions in Python.

1. What a Python function is


A function is a named block of reusable code that performs a specific task. Functions help organize a
program into small units that can be tested, reused, and understood independently. Python defines a
function with the def keyword, followed by the function name, parentheses, and a colon.

def greet():
print("Hello from Python")

greet()

The call greet() transfers control to the function body. When the body finishes, execution continues after
the call. A function should ideally have one clear responsibility so that its behavior is easy to reason
about.

Page 1
2. Parameters and arguments
Parameters are names listed in a function definition. Arguments are the actual values supplied when the
function is called. Parameters make one function useful for many different inputs.

def add(a, b):


return a + b

result = add(5, 7)
print(result)

In this example, a and b are parameters, while 5 and 7 are arguments. Python passes object references
into the function, which means mutable objects can be changed by code inside the function.

Page 2
3. Return values
The return statement sends a result back to the caller and immediately ends the current function call. A
function can return any Python object, including numbers, strings, lists, dictionaries, tuples, functions, or
custom objects.

def rectangle_area(width, height):


if width < 0 or height < 0:
return 0
return width * height

If no explicit return statement is reached, Python returns None. Returning a value is usually more
flexible than printing inside a function because the caller can store, transform, validate, or display the
result later.

Page 3
4. Default and keyword arguments
A parameter can have a default value. The caller may omit that argument and Python will use the
default. Keyword arguments also let the caller specify an argument by parameter name, which can
make calls easier to read.

def connect(host, port=5432, timeout=10):


print(host, port, timeout)

connect("[Link]")
connect("[Link]", timeout=30)

Parameters with defaults normally follow required parameters. Keyword arguments are especially useful
when a function has several optional settings and the caller only wants to change one or two of them.

Page 4
5. Variable-length arguments
Python supports *args for extra positional arguments and **kwargs for extra keyword arguments.
These features are useful when a function must accept a flexible number of inputs.

def show_values(*args, **kwargs):


print("Positional:", args)
print("Keyword:", kwargs)

show_values(10, 20, unit="kg", active=True)

Inside the function, args is a tuple and kwargs is a dictionary. Flexible signatures should be used
carefully because very open interfaces can make code harder to validate and document.

Page 5
6. Local and global scope
Names created inside a function are usually local to that function. Python resolves names using the
LEGB rule: Local, Enclosing, Global, and Built-in scopes. This rule determines which value a name
refers to.

rate = 1.05

def calculate(price):
tax = 0.10
return price * rate * (1 + tax)

Local variables reduce accidental interference between different parts of a program. Directly modifying
global variables is usually discouraged because it introduces hidden state and makes testing more
difficult.

Page 6
7. Lambda expressions
A lambda expression creates a small anonymous function using a single expression. Lambdas are
commonly used as short callback functions or as key functions in sorting operations.

items = [("apple", 3), ("banana", 1), ("mango", 2)]


[Link](key=lambda item: item[1])
print(items)

A lambda cannot contain ordinary statements such as for, try, or assignment statements. For anything
non-trivial, a regular def function is usually clearer.

Page 7
8. Docstrings and type hints
A docstring documents what a function does, while type hints describe expected parameter and return
types. Type hints are not runtime type enforcement by default, but they improve editor support and
static analysis.

def total(values: list[float]) -> float:


"""Return the sum of numeric values."""
return sum(values)

Good documentation explains the purpose of the function, important assumptions, edge cases, and any
exceptions that callers should expect.

Page 8
9. Recursion and base cases
Recursion occurs when a function calls itself. Every recursive algorithm needs a base case that stops
further calls. Without a valid base case, the program eventually raises a recursion depth error.

def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)

Recursive solutions can be elegant for tree structures and divide-and-conquer algorithms. For simple
counting loops, iteration is often easier to understand and avoids recursion overhead.

Page 9
10. Practical design guidelines
Well-designed functions are small enough to understand quickly, have meaningful names, accept only
the inputs they need, and return predictable outputs. Avoid functions that silently depend on unrelated
global state.

• Prefer descriptive names such as calculate_total instead of ct.

• Separate data retrieval, business logic, and output when practical.

• Validate important inputs and document assumptions.

• Write tests for normal cases, boundary cases, and invalid inputs.

Functions are one of the main tools for structuring Python programs. Once a program is decomposed
into clear functions, maintenance and testing become much easier.

Page 10

You might also like