Functions in Python - Detailed Explanation
Definition:
A function is a block of reusable code that performs a specific task. Functions help divide a large program
into smaller, organized sections, improving readability and reusability.
Types of Functions:
1. Built-in Functions: These are functions provided by Python, such as print(), len(), type(), input(), etc.
Example:
print(len("Hello")) # Output: 5
2. User-defined Functions: These are functions created by the programmer using the def keyword.
Example:
def greet(name):
print("Hello", name)
greet("Alice") # Output: Hello Alice
Benefits of Functions:
- Reduces code duplication
- Improves readability
- Supports modular programming
- Makes debugging easier
- Encourages reuse of code
Function Syntax:
def function_name(parameters):
# function body
return result
Types of Function Arguments in Python:
Functions in Python - Detailed Explanation
Python supports several types of function arguments to provide flexibility in function calls.
1. Positional Arguments:
- Values are assigned to parameters in the order they are passed.
Example:
def add(a, b):
return a + b
print(add(10, 5)) # Output: 15
2. Keyword Arguments:
- Arguments are passed with parameter names, allowing flexibility in order.
Example:
def student(name, age):
print("Name:", name)
print("Age:", age)
student(age=21, name="Tom")
Output:
Name: Tom
Age: 21
3. Default Arguments:
- Parameters with default values used if no value is provided.
Example:
def greet(name="Guest"):
print("Hello", name)
greet() # Output: Hello Guest
greet("John") # Output: Hello John
Functions in Python - Detailed Explanation
4. Variable-length Arguments:
a) *args (Non-keyword variable arguments):
- Accepts any number of positional arguments as a tuple.
Example:
def total(*numbers):
sum = 0
for n in numbers:
sum += n
print("Sum:", sum)
total(1, 2, 3, 4) # Output: Sum: 10
b) **kwargs (Keyword variable arguments):
- Accepts any number of keyword arguments as a dictionary.
Example:
def profile(**details):
for key, value in details.items():
print(f"{key}: {value}")
profile(name="Alice", age=25, city="Chennai")
Output:
name: Alice
age: 25
city: Chennai
5. Mixed Argument Types:
- You can combine all argument types in one function (with proper order).
Example:
def display(a, b=10, *args, **kwargs):
Functions in Python - Detailed Explanation
print("a:", a)
print("b:", b)
print("args:", args)
print("kwargs:", kwargs)
display(1, 2, 3, 4, name="Tom", age=30)
Conclusion:
Functions are a core part of Python programming. They improve code modularity and reusability.
Understanding different types of function arguments allows developers to write flexible and powerful functions
for a wide range of applications.