Functions are the building blocks of any Python program. They allow you to organize your code into reusable pieces, making it more modular and easier to read. In this chapter, weโll explore how to define and call functions, handle function arguments, and work with return values. Weโll also dive into the world of lambda functions, which are useful for writing concise, anonymous functions. By the end of this chapter, youโll be equipped to write efficient and clean code using functions.
Functions in Python
Defining and Calling Functions
A function is a block of reusable code that performs a specific task. Defining a function allows you to group statements together and execute them whenever needed.
Defining a Function
To define a function, use the def keyword followed by the function name and parentheses:
Here, greet is a simple function that prints a message.
def greet():
print("Hello, world!")
Calling a Function
To execute the code inside a function, you need to call it by its name followed by parentheses:
greet() # Output: Hello, world!
Function Arguments
Functions often need input values to perform their tasks. These input values are called arguments or parameters.
Functions in Python
Positional Arguments
Positional arguments are the most common type of arguments. The order in which you pass them matters:
You can also pass arguments using the keyword format, which makes the function calls clearer:
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet(name="Alice", age=30) # Output: Hello, Alice! You are 30 years old.
Default Arguments
Default arguments allow you to specify default values for parameters:
def greet(name, age=18):
print(f"Hello, {name}! You are {age} years old.")
greet("Alice") # Output: Hello, Alice! You are 18 years old.
Return Values
A function can send a result back to the caller using the return statement. This allows the function to output a value that can be used elsewhere in the code.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
Lambda Functions
Lambda functions are small, anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression.
Creating a Lambda Function
A typical lambda function looks like this:
Here, lambda x: x ** 2 defines a function that takes one argument x and returns x squared.
Reduce: Apply a function cumulatively to the items of an iterable.
from functools import reduce
sum_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_numbers) # Output: 15
Practice Day – Applying What You’ve Learned
Good Coding Questions
Basic Function Practice:
Write a function is_even() that takes an integer and returns True if the number is even, and False otherwise.
Create a function factorial() that takes a number and returns its factorial using a loop.
Function Arguments:
Define a function greet_user() that takes a userโs first name and last name and prints a greeting message. Use keyword arguments to call the function.
Write a function calculate_area() that calculates the area of a circle given its radius. Use a default argument for the value of ฯ (pi).
Working with Return Values:
Write a function find_max() that takes a list of numbers and returns the maximum value.
Create a function reverse_string() that takes a string and returns the string in reverse order.
Lambda Functions:
Use a lambda function to create a list of squares of numbers from 1 to 10 using map().
Write a lambda function to filter out words from a list that are shorter than 5 characters using filter().
Advanced Lambda Usage:
Use reduce() with a lambda function to find the product of all elements in a list.
Combine map() and filter() to create a list of squares of even numbers from 1 to 20.
Leave a Reply to Chapter 9: Object-Oriented Programming OOP in Python Cancel reply