Mastering Python Object-Oriented Programming
Functions and Lambda
Creating Reusable Code
So far, we've been writing code that runs from top to bottom. But what if you need to perform the same task multiple times? Writing the same lines of code over and over is tedious and makes your programs hard to read. This is where functions come in.
A function is a named, reusable block of code that performs a specific task. Think of it like a recipe. You write the recipe once (define the function), and then you can follow it whenever you want to make that dish (call the function).
Functions in Python are reusable blocks of code that allow you to organise tasks efficiently.
To define a function, you use the def keyword, followed by the function's name, parentheses (), and a colon :. The code that belongs to the function is indented underneath.
# Define a function named greet
def greet():
print("Hello, world!")
# Call the function to execute its code
greet()
greet()
This is a simple function, but functions become truly powerful when you can pass information to them. Data you pass into a function is called an argument. You can also have functions send data back to you. The value a function sends back is called a return value.
# This function accepts one argument, 'name'
def greet_person(name):
return f"Hello, {name}!"
# Call the function with an argument
message = greet_person("Alice")
print(message)
# Call it again with a different argument
print(greet_person("Bob"))
In the example above,
nameis a parameter, which is the variable in the function definition."Alice"is an argument, which is the actual value passed to the function when it's called.
Variable Scope
An important concept with functions is scope, which determines where a variable can be accessed. A variable created inside a function is only accessible within that function. This is called local scope.
A variable created outside of any function has a global scope and can be accessed from anywhere in your code, including inside functions.
global_var = "I'm outside!"
def my_function():
# This variable only exists inside this function
local_var = "I'm inside!"
print(local_var)
print(global_var) # We can access the global variable
my_function()
# This will cause an error because local_var is not defined here
# print(local_var)
Trying to access local_var outside of my_function would result in a NameError. This is a good thing! It prevents functions from accidentally modifying variables they shouldn't, keeping your code organized and predictable.
Quick and Simple Lambdas
Sometimes you need a simple, one-line function that you'll only use once. Defining a full function with def can feel a bit heavy for these situations. Python offers a shortcut for this: lambda expressions.
A lambda is a small, anonymous function. It's called "anonymous" because it doesn't have a name like a function defined with def.
Lambda expressions are a concise way to create functions on the fly.
The syntax is lambda arguments: expression. The expression is evaluated and returned. Let's see how a regular function compares to a lambda.
# A regular function to add two numbers
def add(x, y):
return x + y
# The same logic as a lambda expression
add_lambda = lambda x, y: x + y
print(add(5, 3)) # Output: 8
print(add_lambda(5, 3)) # Output: 8
While you can assign a lambda to a variable, their main power comes from being used with functions that take other functions as arguments, like map() and filter().
Lambdas with Map and Filter
The map() function applies a function to every item in an iterable (like a list) and returns a new iterable with the results. It's a perfect use case for a quick, anonymous lambda.
numbers = [1, 2, 3, 4, 5]
# Use map and a lambda to square each number
squared_numbers = map(lambda x: x * x, numbers)
# We need to convert the map object to a list to see the results
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
The filter() function works similarly, but instead of transforming items, it filters them out. It applies a function that returns True or False to each item. Only the items for which the function returns True are kept.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# Use filter and a lambda to get only the even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)
# Convert to a list to see the results
print(list(even_numbers)) # Output: [2, 4, 6, 8]
Using map and filter with lambdas allows you to write powerful, expressive code for processing lists and other data structures in just a single line.
Let's test your understanding of functions and lambdas.
What is the primary purpose of defining a function in programming?
Consider the following Python code snippet. What will be the output?
message = "Global"
def change_message():
message = "Local"
change_message()
print(message)
You've now learned how to bundle code into reusable functions and create simple, on-the-fly functions with lambdas. These are fundamental building blocks for writing clean and efficient Python programs.