Introduction
In Python, a function is a reusable block of code that performs a specific task. Functions help organize code, improve readability, and allow code reuse without rewriting the same logic.
Need for Functions
Functions provide several benefits:
- Efficiency: Reuse code multiple times without duplication.
- Modularity: Break large programs into smaller, manageable parts.
- Debugging: Easier to test and fix smaller blocks of code.
- Readability: Makes programs easier to understand and maintain.
Defining Functions
Functions are defined using the def keyword followed by the function name, parentheses, and a colon. The function body is indented.
def function_name(parameters):
# function body
statements
Example without parameters:
def greet():
print("Hello, World!")
Example with parameters:
def square(a):
return a * a
Calling a Function
To execute a function, call it by its name followed by parentheses and arguments if required:
def add(x, y):
return x + y
print(add(3, 7))
Arguments and Parameters
Parameters are variables inside a function, while arguments are values passed when calling the function.
def multiply(x, y):
return x * y
multiply(4, 5)
Types of Arguments
- Positional arguments: Based on order.
- Keyword arguments: Use names explicitly →
multiply(y=5, x=4). - Default arguments: Predefined values if not passed.
- Variable-length arguments: Using
*argsand**kwargs.
def greet(name="Guest"):
print("Hello,", name)
greet()
greet("Alice")
Hello, Alice
The return Statement
The return statement sends a value back to the caller and ends function execution.
def power(base, exp):
return base ** exp
print(power(2, 3))
The pass Statement
The pass statement acts as a placeholder when code is not ready.
def future_function():
pass
Anonymous Functions (lambda)
Lambda functions are single-line anonymous functions using the lambda keyword.
square = lambda x: x * x
print(square(6))
Variable Scope
Variables inside a function are local. Variables outside are global. Use the global keyword to modify a global variable inside a function.
x = 10
def change():
global x
x = 20
change()
print(x)
Recursion
A function can call itself—this is called recursion. It is useful for problems like factorials, Fibonacci, etc.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
Conclusion
Functions are powerful tools in Python for structuring code. They help in reusability, modularity, readability, and maintainability. Understanding different types of arguments, return values, and advanced concepts like recursion makes you a more effective Python programmer.
