๐ง 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:
8
๐ก Tip: 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
def
and call them by name - ๐ง Use parameters to pass data and
return
to send results back - ๐ฆ Handle optional parameters with default values
- ๐ Use
*args
/**kwargs
for 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 :