LanguagesCore FundamentalsFunctions & Methods

Functions & Methods

Core Fundamentals

What are Functions and Methods?

Functions and methods are the primary way programmers group code into reusable, logical blocks. They are essential for the Don't Repeat Yourself (DRY) principle and for creating modular, maintainable applications.

  • Function: A block of code that performs a specific task. It can be called by name, can accept data (as parameters), and can return a result. In many languages, functions are "first-class citizens," meaning they can be treated like any other variable (passed around, returned from other functions, etc.).

  • Method: A function that is associated with an object or a class. It is called on an instance of that object and often operates on the data contained within that object. The distinction is a key feature of Object-Oriented Programming (OOP).

# This is a FUNCTION. It's defined independently.
def add(a, b):
    return a + b

# 'append' is a METHOD. It belongs to the list object.
my_list = [1, 2, 3]
my_list.append(4)

Key Components of a Function

1. Function Signature

The function signature defines the function's name, its parameters, and (in statically-typed languages) its return type. It's the function's "contract" with the outside world.

// Signature: public static int add(int a, int b)
// - public: Access modifier
// - static: Belongs to the class, not an instance
// - int: Return type
// - add: Function name
// - (int a, int b): Parameters
public static int add(int a, int b) {
    return a + b;
}

2. Parameters and Arguments

  • Parameter: The variable listed inside the parentheses in the function definition. It's a placeholder.
  • Argument: The actual value that is sent to the function when it is called.
# 'a' and 'b' are PARAMETERS
def greet(name, message):
    print(f"{message}, {name}!")

# "Alice" and "Hello" are ARGUMENTS
greet("Alice", "Hello")

Interview Hot Point: Default, Named, and Variable Arguments

  • Default Arguments: Parameters can have default values, making them optional during the function call.
  • Named (or Keyword) Arguments: Arguments can be passed using the parameter name, which allows for changing their order.
  • Variable-length Arguments (*args, **kwargs): Functions can accept an arbitrary number of positional or keyword arguments. This is very common in Python.
# Default argument for 'message'
def greet(name, message="Hello"):
    print(f"{message}, {name}!")

greet("Bob") # Uses the default: "Hello, Bob!"
greet("Charlie", "Hi") # Overrides the default: "Hi, Charlie!"

# Named arguments improve clarity
greet(message="Goodbye", name="Dave") # "Goodbye, Dave!"

# Variable-length arguments
def summarize(name, *scores, **metadata):
    print(f"Student: {name}")
    # 'scores' is a tuple: (100, 95, 88)
    print(f"Scores: {scores}")
    # 'metadata' is a dictionary: {'year': 2023, 'subject': 'Math'}
    print(f"Metadata: {metadata}")

summarize("Eve", 100, 95, 88, year=2023, subject="Math")

3. Return Values

A function can pass data back to the calling code using the return statement.

  • A function can return at most one value. To return multiple values, they are often grouped into a data structure like a tuple, list, or object.
  • If a function has no return statement (or return is used with no value), it implicitly returns a special value (None in Python, undefined in JavaScript, void in Java/C++).
# Python can "unpack" a returned tuple into multiple variables
def get_user_info():
    return "Alice", 30, "Engineer" # Returns a tuple

name, age, job = get_user_info()
print(name) # Alice

4. Scope

Scope defines the visibility and lifetime of variables. Where you declare a variable determines where it can be accessed.

  • Local Scope: Variables declared inside a function are in its local scope. They can only be accessed from within that function and are destroyed when the function call ends.
  • Global Scope: Variables declared outside of any function are in the global scope. They can be accessed from anywhere in the program.
  • Enclosing (or Nonlocal) Scope: In nested functions, the inner function can access variables from the outer (enclosing) function. This is the principle behind closures.

Interview Hot Point: The global and nonlocal keywords in Python

By default, you can only read from a global variable inside a function. If you assign a value to it, Python creates a new local variable. To modify a global variable, you must use the global keyword. Similarly, nonlocal is used in nested functions to modify a variable from the enclosing scope.

count = 0 # Global scope

def increment():
    # To modify the global 'count', you must declare it
    global count
    count += 1

increment()
print(count) # 1

def outer():
    x = 10 # Enclosing scope
    def inner():
        # To modify the enclosing 'x', you must declare it
        nonlocal x
        x += 1
        print(x)
    inner() # 11
    print(x) # 11

outer()