Functions and Scope

Creating Reusable Code Blocks

Functions are blocks of organized, reusable code that are used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Defining and Calling Functions

You define a function using the def keyword, followed by a function name, parentheses (), and a colon :. The code block within every function starts with an indentation.

# Define a function named 'greet'
def greet(name):
  """This is a docstring. It explains what the function does."""
  message = f"Hello, {name}!"
  return message

Call the function and store its return value

greeting = greet("World") print(greeting)

Parameters and Arguments

Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

You can also define default values for parameters. If a value for that parameter is not provided when the function is called, the default value is used.

def power(base, exponent=2):
  return base ** exponent

Calling with both arguments

print(power(3, 3)) # Output: 27

Calling with only the required argument

print(power(4)) # Output: 16 (uses default exponent of 2)

Lambda Functions

A lambda function is a small, anonymous function. It can take any number of arguments but can only have one expression. They are syntactically restricted to a single expression and are often used when you need a simple, one-off function.

# A lambda function that adds 10 to the number passed in
add_ten = lambda a : a + 10
print(add_ten(5)) # Outputs 15

Often used with functions like map(), filter(), or sorted()

points = [(1, 2), (4, 1), (5, -4)]

Sort points based on their second value (the y-coordinate)

points.sort(key=lambda point: point[1]) print(points) # [(5, -4), (4, 1), (1, 2)]

Scope

Scope refers to the region of a program where a variable is accessible. Python follows the LEGB rule for scope:

  • L (Local): Variables defined inside the current function.
  • E (Enclosing): Variables in the local scope of enclosing functions (for nested functions).
  • G (Global): Variables defined at the top level of a module or declared global with the global keyword.
  • B (Built-in): Names pre-assigned in Python (e.g., print, len).

x = "global"

def my_func(): x = "local" # This is a new local variable, it does not change the global one. print(f"Inside function: {x}")

my_func() print(f"Outside function: {x}")