Functions
Functions
Functions are reusable blocks of code that perform specific tasks. They
help:
Syntax:
def function_name(parameters):
# Code to execute
return value
Example:
def greet(name):
print(f"Hello, {name}!")
2. Defining Functions
result = add(3, 5)
print(result) # Output: 8
Key Notes:
values = [4, 2, 9]
smallest, largest = min_max(values)
Example:
Types of Parameters:
Example:
global_var = 10
def my_function():
local_var = 5
print(global_var + local_var) # Output: 15
my_function()
print(local_var) # NameError: 'local_var' is not defined
count = 0
def increment():
global count
count += 1
increment()
print(count) # Output: 1
5. Common Function Errors
2. Incorrect Indentation:
def wrong():
print("Hello") # IndentationError
4. Unused Parameters:
def greet(name):
print("Hello!") # 'name' is defined but never used
6. Lambda Functions
Example:
square = lambda x: x ** 2
print(square(4)) # Output: 16
Use Cases:
Example (Factorial):
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
Key Notes:
8. Docstrings
Example:
Args:
a (float): Numerator
b (float): Denominator
Returns:
float: Result of division, or None if b is 0.
"""
if b == 0:
return None
return a / b
Accessing Docstrings:
print(divide.__doc__)
9. Real-World Applications
1. Data Processing:
def clean_data(data):
# Remove duplicates, handle missing values
return cleaned_data
2. Input Validation:
def validate_age(age):
return age >= 18
3. Modularizing Code:
def send_email(recipient, message):
# Connect to server, send email
print("Email sent!")