What is a Function in Python?
A function is a block of reusable code that performs a specific task. Functions allow you to write modular code by encapsulating functionality into separate blocks, which can then be called multiple times within your program.
Benefits of Using Functions
- Code Reusability: Write once, use many times.
- Improved Readability: Organize your program into meaningful blocks.
- Scalability: Simplifies debugging and updating.
- Ease of Testing: Functions can be tested independently.
Syntax of a Python Function
The def keyword is used to define a function in Python.
def function_name(parameters):
# Code block
return result
- def: Indicates the start of a function definition.
- function_name: The name of the function. It should be descriptive and follow naming conventions.
- parameters: Optional input values for the function (also called arguments).
- return: Optional statement that returns a value to the caller.
Example: Defining and Calling a Function
def greet(name):
return f"Hello, {name}!"
message = greet("John")
print(message)
Output:
Hello, John!
Types of Functions in Python
Python supports different types of functions:
- Built-in Functions: Predefined in Python (e.g., len(), print(), sum()).
- User-defined Functions: Created by the programmer.
- Lambda Functions: Anonymous, single-expression functions.
- Recursive Functions: Call themselves to solve problems.
Parameters and Arguments
Positional Arguments
The order of arguments matters.
def add(a, b):
return a + b
result = add(5, 3) # a = 5, b = 3
print(result)
Keyword Arguments
Specify arguments by name.
result = add(b=3, a=5)
print(result)
Default Arguments
Provide default values for parameters.
def greet(name="Guest"):
return f"Welcome, {name}!"
print(greet()) # Uses default value
print(greet("Alice")) # Overrides default
Arbitrary Arguments (*args)
Used to accept multiple positional arguments.
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4)) # Outputs 10
Arbitrary Keyword Arguments (**kwargs)
Used to accept multiple keyword arguments.
def describe_person(**details):
for key, value in details.items():
print(f"{key}: {value}")
describe_person(name="John", age=25, city="New York")
The Return Statement
The return statement sends a value back to the caller.
Example:
def square(num):
return num * num
result = square(4)
print(result)
Output:
16
If no return is used, the function returns None.
Scope and Lifetime of Variables
- Local Variables: Defined inside a function and accessible only within that function.
- Global Variables: Defined outside any function and accessible throughout the program.
Example:
x = 10 # Global variable
def my_function():
x = 5 # Local variable
print("Inside function:", x)
my_function()
print("Outside function:", x)
Output:
Inside function: 5
Outside function: 10
Lambda Functions
A lambda function is a small, anonymous function defined with the lambda keyword.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x ** 2
print(square(5)) # Outputs 25
Recursive Functions
A recursive function calls itself to solve problems.
Example: Factorial Calculation
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Outputs 120
Practical Examples of Functions
Example 1: Checking Even or Odd
def is_even(number):
return number % 2 == 0
print(is_even(4)) # Outputs True
print(is_even(7)) # Outputs False
Example 2: Finding Maximum of Three Numbers
def find_max(a, b, c):
return max(a, b, c)
print(find_max(10, 20, 15)) # Outputs 20
Example 3: Generating Fibonacci Sequence
def fibonacci(n):
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence
print(fibonacci(10)) # Outputs [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Common Errors in Functions
Forgetting to Call a Function: Simply defining a function does not execute it.
def greet():
print("Hello!")
# No output because the function wasn't called
Incorrect Argument Count: Mismatch in parameters and arguments.
def add(a, b):
return a + b
print(add(5)) # Raises TypeError
Scope Issues: Modifying global variables without declaring them explicitly.