Functions in Python
1. Introduction to Functions
A function is a reusable block of code that performs a specific task. It helps in modular
programming by dividing code into smaller, manageable parts.
Advantages of Using Functions:
● Code Reusability: Avoids repetition by reusing code.
● Modularity: Makes the program more organized and readable.
● Scalability: Makes complex programs easy to manage.
● Debugging: Simplifies error detection and fixing.
● Improved Collaboration: Easier to work in teams by dividing tasks.
● Reduces Redundancy: Commonly used code can be written once and used multiple
times.
2. Defining and Calling Functions
Syntax of a Function:
# Function definition
def function_name(parameters):
"""Optional docstring to describe function"""
# Function body
return result # Optional
# Function call
function_name(arguments)
Example: Simple Function
def greet():
print("Hello, Welcome to Python Functions!")
greet() # Calling the function
Output:
Hello, Welcome to Python Functions!
3. Function Parameters and Arguments
Functions can take parameters (input values) to work dynamically.
Types of Function Parameters:
1. Positional Arguments (Passed in order)
2. Default Arguments (Predefined default values)
3. Keyword Arguments (Explicitly specifying arguments by name)
4. Arbitrary Arguments (*args for multiple values)
5. Keyword Arbitrary Arguments (**kwargs for multiple key-value pairs)
Example: Positional Arguments
def add(a, b):
return a + b
print(add(5, 3)) # Output: 8
Example: Default Arguments
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
Example: Arbitrary Arguments (*args)
def total_sum(*numbers):
return sum(numbers)
print(total_sum(1, 2, 3, 4, 5)) # Output: 15
Example: Keyword Arguments (**kwargs)
def display_info(**details):
for key, value in details.items():
print(f"{key}: {value}")
display_info(name="John", age=25, city="New York")
4. Return Statement
A function can return a value using the return statement.
Example: Function with Return Value
def square(num):
return num ** 2
print(square(4)) # Output: 16
5. Lambda Functions (Anonymous Functions)
A lambda function is a small anonymous function that can take any number of arguments
but has only one expression.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x ** 2
print(square(5)) # Output: 25
6. Recursive Functions
A recursive function is a function that calls itself to solve a problem.
Example: Factorial Using Recursion
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
7. Scope of Variables in Functions
Types of Variable Scope:
1. Local Scope (Defined inside a function, accessible only inside it)
2. Global Scope (Defined outside a function, accessible everywhere)
3. Nonlocal Scope (Used inside nested functions)
Example: Global vs Local Scope
global_var = "I am global"
def my_function():
local_var = "I am local"
print(local_var) # Accessible inside function
print(global_var) # Accessible anywhere
my_function()
8. Function Documentation (Docstrings)
Docstrings describe what a function does and improve readability.
Example:
def add(a, b):
"""This function returns the sum of two numbers."""
return a + b
print(add.__doc__)
Output:
This function returns the sum of two numbers.
9. Built-in Functions vs User-defined Functions
● Built-in Functions: Functions provided by Python (e.g., print(), len(), sum()).
● User-defined Functions: Functions created by programmers as needed.
10. Higher-Order Functions
A function that takes another function as an argument or returns a function.
Example: Using map() Function
def square(n):
return n ** 2
numbers = [1, 2, 3, 4]
squared_numbers = list(map(square, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16]
11. Function Decorators
A decorator is a function that modifies another function’s behavior without changing its
structure.
Example:
def decorator_function(original_function):
def wrapper_function():
print("Function is being called!")
original_function()
return wrapper_function
@decorator_function
def greet():
print("Hello, World!")
greet()
12. Real-Time Examples of Functions
1. ATM Cash Withdrawal System
def withdraw_cash(balance, amount):
if amount > balance:
return "Insufficient funds"
balance -= amount
return f"Withdrawal successful. Remaining balance: {balance}"
print(withdraw_cash(5000, 1500)) # Example usage
2. E-commerce Discount Calculation
def calculate_discount(price, discount_percent):
discount = (discount_percent / 100) * price
final_price = price - discount
return final_price
print(calculate_discount(1000, 10)) # Output: 900.0
3. User Authentication System
def authenticate_user(username, password):
stored_username = "admin"
stored_password = "password123"
if username == stored_username and password == stored_password:
return "Login Successful"
return "Invalid Credentials"
print(authenticate_user("admin", "password123"))
4. Sending Automated Emails
import smtplib
def send_email(to_email, subject, message):
print(f"Sending email to {to_email} with subject '{subject}' and message '{message}'")
# Actual email sending code would go here
send_email("[email protected]", "Welcome", "Thank you for signing up!")