Functions in Python Detailed Explanation
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
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)
Benefits of Functions:
- Improves readability
Function Syntax:
def function_name(parameters):
# function body
return result
Python supports several types of function arguments to provide flexibility in function calls.
1. Positional Arguments:
Example:
return a + b
2. Keyword Arguments:
Example:
print("Name:", name)
print("Age:", age)
student(age=21, name="Tom")
Output:
Name: Tom
Age: 21
3. Default Arguments:
Example:
def greet(name="Guest"):
print("Hello", name)
4. Variable-length Arguments:
Example:
def total(*numbers):
sum = 0
for n in numbers:
sum += n
print("Sum:", sum)
Example:
def profile(**details):
print(f"{key}: {value}")
Output:
name: Alice
age: 25
city: Chennai
- You can combine all argument types in one function (with proper order).
Example:
print("a:", a)
print("b:", b)
print("args:", args)
print("kwargs:", kwargs)
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