Skip to content

Functions

🎯 Core Concept

A Function is a reusable block of code that performs a specific task. Functions help organize code, reduce repetition, and improve maintainability by encapsulating logic into named, callable units.

🔄 Function Types

Built-in Functions

Pre-defined functions provided by programming languages.

# Python built-ins
print("Hello")        # Output
len("string")         # Length
type(variable)        # Type checking
// Java built-ins
System.out.println();  // Output
Math.max(a, b);        // Math operations
String.valueOf(num);   // Type conversion

User-defined Functions

Custom functions created by programmers.

# Python function
def greet(name):
    return f"Hello, {name}!"

# Call the function
message = greet("Student")
print(message)  # Output: Hello, Student!
// Java method
public static String greet(String name) {
    return "Hello, " + name + "!";
}

// Call the method
String message = greet("Student");
System.out.println(message);  // Output: Hello, Student!

🏗️ Function Components

Function Signature

Defines the function's name, parameters, and return type.

# Python signature
def function_name(parameter1, parameter2):
    # function body
    return result
// Java signature
return_type function_name(type parameter1, type parameter2) {
    // method body
    return result;
}

Parameters

Input values passed to functions.

Positional Parameters

def calculate_area(length, width):
    return length * width

area = calculate_area(5, 3)  # length=5, width=3

Keyword Parameters

def calculate_area(length, width):
    return length * width

area = calculate_area(width=3, length=5)  # Order doesn't matter

Default Parameters

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))           # Hello, Alice!
print(greet("Bob", "Hi"))       # Hi, Bob!

Return Values

Output values from functions.

Single Return

def add(a, b):
    return a + b

result = add(5, 3)  # result = 8

Multiple Returns

def get_name_parts(full_name):
    parts = full_name.split()
    return parts[0], parts[-1]

first, last = get_name_parts("John Doe")  # first="John", last="Doe"

No Return (Void)

def print_message(message):
    print(message)
    # No return statement

print_message("Hello")  # Just prints, no return value

🎓 Academic Context

Exam Focus Points

  • Definition: Reusable code block with specific purpose
  • Components: Name, parameters, return value, body
  • Types: Built-in vs User-defined
  • Benefits: Code reuse, organization, maintainability

Viva Questions

  • Why do we need functions?
  • What is the difference between parameters and arguments?
  • When would you use a function with no return value?
  • What are default parameters and when are they useful?

Mark Distribution

  • Short Answers: 2-3 marks (definition, components)
  • Long Questions: 5 marks (examples, benefits)
  • Practical: Writing functions for specific problems

💻 Professional Context

Best Practices

  1. Function Naming
  2. Use descriptive, action-oriented names
  3. Follow naming conventions (camelCase, snake_case)
  4. Avoid abbreviations unless widely understood

  5. Single Responsibility

  6. Each function should do one thing well
  7. Keep functions focused and small
  8. Complex logic should be broken into smaller functions

  9. Parameter Design

  10. Limit number of parameters (ideally ≤ 3-4)
  11. Use meaningful parameter names
  12. Consider using objects for many parameters

  13. Error Handling

  14. Validate input parameters
  15. Handle edge cases gracefully
  16. Provide meaningful error messages

Production Examples

# Professional function with validation
def calculate_discount(price, discount_percent, customer_type="regular"):
    """
    Calculate discounted price with validation

    Args:
        price (float): Original price (must be positive)
        discount_percent (float): Discount percentage (0-100)
        customer_type (str): Customer type for additional discounts

    Returns:
        float: Final discounted price

    Raises:
        ValueError: If inputs are invalid
    """
    if price <= 0:
        raise ValueError("Price must be positive")
    if not 0 <= discount_percent <= 100:
        raise ValueError("Discount must be between 0 and 100")

    # Apply base discount
    discounted_price = price * (1 - discount_percent / 100)

    # Apply additional customer discount
    if customer_type == "premium":
        discounted_price *= 0.95  # Additional 5% off

    return round(discounted_price, 2)
// Professional method with documentation
/**
 * Calculates discounted price with validation and customer type discounts.
 * 
 * @param price Original price (must be positive)
 * @param discountPercent Discount percentage (0-100)
 * @param customerType Customer type for additional discounts
 * @return Final discounted price
 * @throws IllegalArgumentException If inputs are invalid
 */
public static double calculateDiscount(double price, double discountPercent, 
                                      String customerType) {
    if (price <= 0) {
        throw new IllegalArgumentException("Price must be positive");
    }
    if (discountPercent < 0 || discountPercent > 100) {
        throw new IllegalArgumentException("Discount must be between 0 and 100");
    }

    // Apply base discount
    double discountedPrice = price * (1 - discountPercent / 100);

    // Apply additional customer discount
    if ("premium".equals(customerType)) {
        discountedPrice *= 0.95;  // Additional 5% off
    }

    return Math.round(discountedPrice * 100.0) / 100.0;
}
  • Methods: Functions associated with objects/classes
  • Procedures: Functions without return values
  • Recursion: Functions that call themselves
  • Lambda Functions: Anonymous, inline functions
  • Higher-Order Functions: Functions that take other functions as parameters

This atomic content bridges academic function theory with professional programming practices, emphasizing code reusability and maintainability.