Python Functions – A Complete Guide with Examples
Introduction – Why Functions Are Vital in Python
Functions are the building blocks of reusable and organized code. Whether you’re building a calculator, web app, or machine learning model, Python functions help break down problems into manageable pieces.
Python makes it simple to define, call, and manage functions. With support for default arguments, keyword arguments, arbitrary parameters, and recursion—functions empower developers to write DRY (Don’t Repeat Yourself) and modular code.
What You’ll Learn:
- How to define and call functions in Python
- Parameters: positional, keyword, default,
*args,**kwargs - Returning values, scope, and recursion
- Best practices, FAQs, and real-world usage
Defining Functions in Python
Syntax:
def function_name(parameters):
# code block
return result
def: Keyword to define a functionfunction_name: The name of your functionparameters: Optional argumentsreturn: Sends a result back to the caller
Example 1: Basic Function
def greet():
print("Hello, Python!")
greet()
Output:
Hello, Python!
Explanation:
The greet() function prints a message. It doesn’t accept parameters or return anything.
Function with Parameters
Example 2:
def add(a, b):
return a + b
print(add(3, 5))Output:
8Tip: Use parameters to pass data into your function and return output for reuse.
Default Arguments
Example 3:
def power(base, exponent=2):
return base ** exponent
print(power(3)) # Uses default exponent
print(power(3, 3)) # Overrides default
Output:
9
27
Use Case: Provide fallback values when arguments are not passed.
Keyword Arguments
def person(name, age):
print(f"Name: {name}, Age: {age}")
person(age=30, name="Alice")
Output:
Name: Alice, Age: 30
Tip: Keyword arguments improve readability and flexibility.
Variable-Length Arguments – *args and **kwargs
Example 4: *args (Non-keyword Arguments)
def total(*numbers):
return sum(numbers)
print(total(5, 10, 15))
Output:
30
Example 5: **kwargs (Keyword Arguments)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Bob", age=25, city="Paris")
Output:
name: Bob
age: 25
city: Paris
Best Practice: Use *args for tuples and **kwargs for dictionaries.
Recursive Functions
Example 6: Factorial
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Output:
120
Warning: Recursion must have a base case to avoid infinite loops.
Variable Scope in Functions
Example 7:
x = 10
def show():
x = 5
print("Inside:", x)
show()
print("Outside:", x)
Output:
Inside: 5
Outside: 10
Explanation: x inside the function is local; outside it’s global.
Real-World Example: Temperature Converter
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
print(celsius_to_fahrenheit(25)) # Output: 77.0
Use Case: Functions are ideal for common reusable tasks.
Summary – Key Takeaways
- Define functions with
defand call them by name - Use parameters to pass data and
returnto send results back - Handle optional parameters with default values
- Use
*args/**kwargsfor flexible argument handling - Understand variable scope to avoid bugs
- Master recursion carefully with a base case
FAQ Section
What is the difference between a function and a method?
A function is standalone, while a method is associated with an object (like list.append()).
Can Python functions return multiple values?
Yes. Return them as a tuple:
def calc(a, b):
return a + b, a * b
What is a lambda function?
A small anonymous function:
square = lambda x: x * x
Is return mandatory in Python functions?
No. If omitted, the function returns None by default.
Can functions be nested in Python?
Yes. Functions can be defined within other functions and used for closures.
Share Now :
