Functions in Python
Functions in Python allow code reusability, modularity, and better readability. A function is a block of reusable code that performs a specific task.
Python supports two types of functions:
- Built-in Functions – Functions that come with Python. (e.g.,
print()
,len()
,input()
) - User-Defined Functions – Functions created by the programmer to perform specific tasks.
1. Defining a Function in Python
A function is defined using the def
keyword.
Syntax:
def function_name(parameters):
"""Optional docstring"""
# Function body
return value # (Optional)
Example: A Simple Function
def greet():
print("Hello, Welcome to Python!")
greet()
Output:
Hello, Welcome to Python!
2. Function with Parameters
Functions can take parameters as input.
Example: Function with a Single Parameter
def greet(name):
print("Hello", name, "Good Morning!")
greet("Alice")
Output:
Hello Alice Good Morning!
Example: Function to Calculate Square
def square(num):
print("Square of", num, "is", num * num)
square(5)
Output:
Square of 5 is 25
3. Return Statement in Functions
The return
statement is used to return a value from a function.
Example: Function that Returns a Value
def add(a, b):
return a + b
result = add(10, 20)
print("Sum:", result)
Output:
Sum: 30
4. Function with Default Parameters
You can define default values for parameters.
Example: Default Parameter Function
def greet(name="Guest"):
print("Hello", name)
greet() # Uses default value
greet("Bob")
Output:
Hello Guest
Hello Bob
5. Function with Keyword Arguments
Keyword arguments allow calling a function by specifying parameter names.
Example: Keyword Arguments
def student_info(name, age):
print("Name:", name)
print("Age:", age)
student_info(age=21, name="Alice")
Output:
Name: Alice
Age: 21
6. Function with Variable-Length Arguments
Python provides *args
and **kwargs
to pass multiple arguments.
Example: *args
for Multiple Positional Arguments
def add(*numbers):
total = sum(numbers)
print("Sum:", total)
add(10, 20, 30)
add(5, 15, 25, 35)
Output:
Sum: 60
Sum: 80
Example: **kwargs
for Multiple Keyword Arguments
def student_info(**details):
for key, value in details.items():
print(key, ":", value)
student_info(name="Alice", age=22, course="Python")
Output:
name : Alice
age : 22
course : Python
7. Recursive Functions
A recursive function is a function that calls itself.
Example: Factorial using Recursion
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print("Factorial of 5:", factorial(5))
Output:
Factorial of 5: 120
πΉ Advantages of Recursion:
- Helps in solving problems that can be broken down into smaller subproblems.
- Reduces code length and improves readability.
8. Anonymous (Lambda) Functions
A lambda function is a small, unnamed function that is defined using the lambda
keyword.
Syntax:
lambda arguments: expression
Example: Lambda Function for Square Calculation
square = lambda x: x * x
print("Square of 4:", square(4))
Output:
Square of 4: 16
Example: Lambda Function for Adding Two Numbers
add = lambda a, b: a + b
print("Sum:", add(5, 10))
Output:
Sum: 15
πΉ Why Use Lambda Functions?
- Used for quick operations without defining full functions.
- Often used with functions like
map()
,filter()
, andreduce()
.
9. map()
, filter()
, and reduce()
Functions
map()
– Applies a Function to All Elements in a List
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x * x, numbers))
print(squared_numbers)
Output:
[1, 4, 9, 16, 25]
filter()
– Filters Elements Based on a Condition
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Output:
[2, 4, 6]
reduce()
– Reduces a List to a Single Value
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_numbers)
Output:
15
10. Nested Functions
A function defined inside another function is called a nested function.
Example: Nested Function
def outer():
print("Outer function started")
def inner():
print("Inner function executed")
inner()
outer()
Output:
Outer function started
Inner function executed
11. Function Decorators
A decorator is a function that modifies another function's behavior.
Example: Function Decorator
def decorator(func):
def wrapper():
print("Function is being called")
func()
print("Function execution completed")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Function is being called
Hello!
Function execution completed
12. Global and Local Variables in Functions
Example: Local Variable
def demo():
x = 10 # Local variable
print("Local x:", x)
demo()
# print(x) # Error: x is not accessible outside the function
Example: Global Variable
x = 10 # Global variable
def demo():
print("Global x:", x)
demo()
Output:
Global x: 10
Conclusion
- Functions make code reusable and modular.
def
keyword defines a function, andreturn
can return values.- Parameters allow dynamic inputs.
- Lambda functions provide concise anonymous functions.
- Recursion helps solve complex problems.
- Decorators and nested functions enhance functionality.