PYTHON FUNCTIONS

Encapsulate reusable blocks of logic, handle modular parameters, and return calculated data efficiently in Python programs.

⚙️ What is a Function in Python?

A function is a block of organized, reusable code defined using the def keyword followed by a function name and parentheses (). Functions accept inputs as parameters, execute statements, and optionally return results using the return keyword, promoting modularity and cleaner code architecture.

1. Basic Function Declaration and Invocation
Define a simple greeting function and invoke it with a developer name argument.
Python
# Defining a basic function
def greet_developer(name):
    return f"Hello, {name}! Welcome to Python development."

# Calling the function
message = greet_developer("Nikita")
print(message)
Output: Hello, Nikita! Welcome to Python development.
Real-Time Example 1: E-Commerce Total Bill Calculator
Calculate final cart totals with optional tax rates and promotional discount percentages.
Python
def calculate_invoice_total(subtotal, tax_rate=0.05, discount=0.0):
    tax_amount = subtotal * tax_rate
    discount_amount = subtotal * discount
    total = (subtotal + tax_amount) - discount_amount
    return round(total, 2)

# Compute bill with default 5% tax and 10% discount
final_amount = calculate_invoice_total(subtotal=2500, discount=0.10)
print(f"Calculated Invoice Total: ₹{final_amount}")
Output: Calculated Invoice Total: ₹2375.0
Real-Time Example 2: User Authentication Handler
Validate user login credentials against a mock database dictionary record.
Python
def authenticate_user(username, password):
    database = {"admin_root": "SecurePass123", "nikita_dev": "WebCode99"}
    
    if username in database and database[username] == password:
        return f"Access Granted: Welcome back, {username}!"
    return "Access Denied: Invalid credentials."

print(authenticate_user("nikita_dev", "WebCode99"))
print(authenticate_user("admin_root", "WrongPassword"))
Output: Access Granted: Welcome back, nikita_dev! Access Denied: Invalid credentials.
Real-Time Example 3: Password Strength Validator
Inspect string length and requirements to ensure user password compliance.
Python
def validate_password_strength(password):
    if len(password) < 8:
        return "Weak: Password must be at least 8 characters long."
    if not any(char.isdigit() for char in password):
        return "Medium: Password should include at least one number."
    return "Strong: Password meets all security guidelines."

print(validate_password_strength("abc12345"))
print(validate_password_strength("short"))
Output: Strong: Password meets all security guidelines. Weak: Password must be at least 8 characters long.
Real-Time Example 4: Flexible Arguments (*args) for Log Messages
Accept a variable number of transactional items or log lines using *args.
Python
def generate_audit_trail(*log_events):
    print("--- Security Audit Report ---")
    for index, event in enumerate(log_events, start=1):
        print(f" [{index}] {event}")

generate_audit_trail("Server booted", "Database connected", "User login verified")
Output: --- Security Audit Report --- [1] Server booted [2] Database connected [3] User login verified
Real-Time Example 5: Keyword Arguments (**kwargs) for Profile Config
Capture flexible dynamic configuration settings using **kwargs dictionary packing.
Python
def configure_user_profile(username, **settings):
    profile = {"username": username}
    profile.update(settings)
    return profile

user_config = configure_user_profile("nikita_infotech", theme="dark", notifications=True, role="Admin")
print("Generated Profile Configuration:", user_config)
Output: Generated Profile Configuration: {'username': 'nikita_infotech', 'theme': 'dark', 'notifications': True, 'role': 'Admin'}
Real-Time Example 6: Anonymous Lambda Functions
Create small, anonymous inline functions for quick data transformations.
Python
# Lambda function to calculate square of a number
compute_square = lambda x: x ** 2

# Lambda function to compute retail tax markup
add_tax = lambda price: price * 1.18

print("Square of 6:", compute_square(6))
print("Price with 18% GST added:", add_tax(500))
Output: Square of 6: 36 Price with 18% GST added: 590.0
Real-Time Example 7: Data Formatting Helper Function
Format raw database phone numbers into standard readable telephone extensions.
Python
def format_phone_number(digits):
    if len(digits) == 10:
        return f"+91 ({digits[0:3]}) {digits[3:6]}-{digits[6:]}"
    return "Invalid phone number length."

formatted = format_phone_number("9876543210")
print("Formatted Telephone Record:", formatted)
Output: Formatted Telephone Record: +91 (987) 654-3210
Real-Time Example 8: Returning Multiple Values as a Tuple
Return statistical metrics (minimum, maximum, and average) from a list of inventory scores in a single return call.
Python
def calculate_statistics(numbers):
    low = min(numbers)
    high = max(numbers)
    avg = sum(numbers) / len(numbers)
    return low, high, avg

ratings = [4, 5, 3, 5, 4, 4]
minimum, maximum, average = calculate_statistics(ratings)

print(f"Ratings Stats -> Min: {minimum}, Max: {maximum}, Average: {average:.2f}")
Output: Ratings Stats -> Min: 3, Max: 5, Average: 4.17
Real-Time Example 9: Recursive Function for Directory Depth
Calculate factorial or recursive values to solve hierarchical arithmetic problems.
Python
def compute_factorial(n):
    if n == 0 or n == 1:
        return 1
    return n * compute_factorial(n - 1)

factorial_result = compute_factorial(5)
print("Factorial of 5 (5!):", factorial_result)
Output: Factorial of 5 (5!): 120

Summary of Python Functions

  • Code Reusability: Wrap repetitive logic into modular, maintainable blocks using the def keyword.
  • Flexible Parameters: Support default arguments, positional lists (*args), and keyword dictionaries (**kwargs).
  • Data Return: Send processed results back to the caller cleanly using return statements or inline lambda expressions.