FAQ Part 5: Functions and Scope

How do I define a function?

def greet(name):
    return "Hello " + name

What is the difference between local and global variables?

Local variables exist inside functions. Use global to modify global variables inside functions.

Can functions have default parameters?

Yes: def greet(name="Guest").

Can a function return multiple values?

Yes, by returning a tuple:

def stats(x, y):
    return x + y, x * y

sum_, product = stats(3, 4)

What is a keyword argument?

It allows you to specify arguments by name:

def greet(name, msg="Hello"):
    print(f"{msg}, {name}!")

greet(name="Alice", msg="Hi")

What is *args and **kwargs?

  • *args: Passes a variable number of positional arguments.
  • **kwargs: Passes a variable number of keyword arguments.
def demo(*args, **kwargs):
    print(args)
    print(kwargs)

demo(1, 2, a="apple", b="banana")

What is a lambda function and how is it different from a regular function?

A lambda function is an anonymous, one-line function:

square = lambda x: x * x
print(square(5))  # Outputs: 25

It’s used for short operations, often as arguments to functions like map() and filter().

What is a closure in Python?

A closure is a function that remembers the environment in which it was created:

def outer(x):
    def inner(y):
        return x + y
    return inner

add_five = outer(5)
print(add_five(3))  # Outputs: 8

What is a recursive function?

A function that calls itself. Useful for tasks like calculating factorials or traversing trees:

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

What is the difference between return and print()?

  • return sends a result back to the caller.
  • print() displays output on the screen.

Example:

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

result = add(3, 4)
print(result)  # Outputs: 7

How do nested functions work in Python?

Functions defined inside other functions can access variables from the outer scope:

def outer():
    x = "outer"
    def inner():
        print(x)
    inner()