What are Functions in Python?
- Functions in Python are reusable blocks of code designed to perform a specific task. They make programs modular, readable, and efficient by reducing code duplication.
Types of Functions in Python
- Built-in Functions: Functions provided by Python (e.g.,
print()
,len()
,sum()
). - User-Defined Functions: Functions created by the programmer.
Defining a Function
Syntax:
def function_name(parameters):
# Code block
return result
Key Components:
def
: Keyword to define a function.function_name
: Name of the function (should be descriptive).parameters
: Optional inputs passed to the function.return
: Optional statement to return a value.
Creating Your First Function
Example:
def greet():
print("Hello, World!")
greet()
Output:
Hello, World!
Using Parameters in Functions
Parameters allow you to pass data into a function.
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Output:
Hello, Alice!
Return Values from Functions
Functions can return results for further use.
Example:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # Output: 8
Default Parameters
You can provide default values for parameters.
Example:
def greet(name="Guest"):
print(f"Welcome, {name}!")
greet() # Output: Welcome, Guest!
greet("Alice") # Output: Welcome, Alice!
Variable Scope in Functions
- Local Scope: Variables defined inside a function.
- Global Scope: Variables defined outside all functions.
Example:
global_var = 10 # Global variable
def my_function():
local_var = 5 # Local variable
print(local_var)
my_function()
print(global_var)
Output:
5
10
Types of Arguments
- Positional Arguments: Based on position in the function call.
- Keyword Arguments: Specify arguments by name.
- Arbitrary Arguments: Accept multiple arguments using
*args
or**kwargs
.
Example:
def describe_pet(name, species="dog"):
print(f"{name} is a {species}.")
# Positional and default arguments
describe_pet("Buddy") # Output: Buddy is a dog.
describe_pet("Whiskers", "cat") # Output: Whiskers is a cat.
# Arbitrary arguments
def print_numbers(*numbers):
for number in numbers:
print(number)
print_numbers(1, 2, 3) # Output: 1 2 3
Anonymous Functions (lambda)
Python allows you to create small, anonymous functions using the lambda
keyword.
Syntax:
lambda arguments: expression
Example:
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
Best Practices for Functions
Use Descriptive Names:
- Choose function names that describe their purpose.
def calculate_area(radius): # Descriptive
Keep Functions Short:
- Limit the length of a function to improve readability.
Use Comments:
- Document complex functions with comments or docstrings.
def add_numbers(a, b):
"""Adds two numbers and returns the result."""
return a + b
Avoid Global Variables:
- Use local variables or pass arguments to functions.
Test Your Functions:
- Write test cases to verify the functionality of each function.
Practice Exercise
Task: Write a function to calculate the factorial of a number.
Solution:
def factorial(n):
"""Calculate the factorial of a number."""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120