Functions are foundational building blocks in Python programming, enabling developers to encapsulate logic, improve readability, and encourage code reuse. This comprehensive guide delves into every aspect of defining and using functions in Python—from basics to advanced patterns— providing clear explanations, practical examples, and best practices for writing clean, maintainable code.
A function is a self-contained block of code that performs a specific task or calculates a value. In Python, functions help break complex problems into smaller, reusable components. Core benefits include:
A typical function includes:
def add(a, b):
"""Return sum of a and b."""
return a + b
result = add(5, 7)
print(result) # Output: 12
This example shows parameter passing, return values, and basic docstring usage.
Python allows:
def divide(a, b):
return a / b
x = divide(10, 2) # Positional
y = divide(b=5, a=25) # Keyword
def greet(name, msg="Hello"):
return f"{msg}, {name}!"
print(greet("Alice")) # "Hello, Alice!"
print(greet("Bob", msg="Hi")) # "Hi, Bob!"
Avoid mutable defaults like lists or dicts; they persist across calls:
def append_item(value, lst=[]):
lst.append(value)
return lst
print(append_item(1)) # [1]
print(append_item(2)) # [1, 2] ← Unexpected
Correct pattern:
def append_item(value, lst=None):
if lst is None:
lst = []
lst.append(value)
return lst
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3, 4)) # 10
def describe_person(**kwargs):
for key, val in kwargs.items():
print(f"{key}: {val}")
describe_person(name="Alice", age=30, city="Paris")
def func(a, b=2, *args, **kwargs):
print(a, b, args, kwargs)
func(1, 3, 4, 5, x=100, y=200)
# 1 3 (4, 5) {'x':100, 'y':200}
def double(x):
return x * 2
print(double(7)) # 14
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 9, 4])
print(low, high) # 1 9
Functions without return produce None by default.
def multiply(a, b):
"""
Multiply two numbers and return the result.
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: Product of a and b.
"""
return a * b
print(multiply.__doc__)
def greet(name: str, age: int = 0) -> str:
return f"{name} is {age} years old."
from typing import Optional, Union
def to_int(s: str) -> Optional[int]:
try:
return int(s)
except ValueError:
return None
def process(val: Union[int, float]) -> float:
return val * 2.5
square = lambda x: x * x
print(square(6)) # 36
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x*x, nums))
evens = list(filter(lambda x: x%2 == 0, nums))
Limited to single expressions – no statements, loops, or multi-line logic. For complex processing, prefer named functions.
def apply(func, x):
return func(x)
print(apply(lambda x: x + 10, 5)) # 15
def make_multiplier(n):
def multiplier(x):
return x * n
return multiplier
double = make_multiplier(2)
print(double(8)) # 16
def greet(name):
return f"Hello {name}"
say_hello = greet
print(say_hello("Alice")) # Hello Alice
def outer():
def inner():
print("Inner here")
inner()
outer()
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before")
result = func(*args, **kwargs)
print("After")
return result
return wrapper
@my_decorator
def say_hi():
print("Hi!")
say_hi()
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet():
print("Hello!")
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # 120
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
print([fib(i) for i in range(10)])
Python doesn’t optimize tail calls; iterative loops are preferred for deep recursion.
x = 10
def func():
x = 5 # local
print(x)
func() # 5
print(x) # 10
x = 5
def modify():
global x
x = 20
modify()
print(x) # 20
def outer():
x = 5
def inner():
nonlocal x
x = 10
inner()
return x
print(outer()) # 10
from functools import partial
def power(base, exp):
return pow(base, exp)
square = partial(power, exp=2)
print(square(5)) # 25
def func(a, b=2):
"""Example doc."""
pass
print(func.__name__) # "func"
print(func.__doc__) # "Example doc."
print(func.__defaults__) # (2,)
import inspect
sig = inspect.signature(func)
print(sig) # (a, b=2)
print(sig.parameters) # mapping of params
Functions should do one thing, not multiple. Keep them short and focused.
Name functions clearly: calculate_total is better than ct.
Document purpose, arguments, return types, and exceptions. Use type hints for clarity and tool support.
Ideally under ~50 lines–encourage reuse and improve testing.
# calc.py
def add(a: float, b: float) -> float:
"""Add two numbers."""
return a + b
def sub(a: float, b: float) -> float:
return a - b
def mul(a: float, b: float) -> float:
return a * b
def div(a: float, b: float) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# main.py
import calc
print(calc.add(4, 5))
print(calc.div(10, 0)) # triggers ValueError
Defining functions in Python is more than just grouping statements—it’s about capturing intent, ensuring clarity, supporting reuse, and designing maintainable code. This guide covered:
Armed with these techniques, you can write functions that are readable, efficient, robust, and ready for real-world Python applications.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is ₹5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from ₹3,000 - ₹1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved