Python Functions – Exam Notes
1. Introduction to Functions
• A function is a block of reusable code that performs a specific task.
• Helps reduce code duplication, improve readability, and organize programs.
Syntax:
def function_name(parameters):
"""Optional documentation string"""
# function body
return result
2. Defining Your Own Functions
def greet():
print("Hello, World!")
greet() # Output: Hello, World!
• def keyword defines a function.
• Function name follows naming conventions.
• Parentheses are required even if no parameters.
3. Parameters in Functions
• Parameters allow passing values to a function.
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Alice") # Output: Hello, Alice!
Explanation:
• name is a parameter, "Alice" is the argument.
4. Function Documentation
• Use docstrings (""" """) to describe function behavior.
• Accessible via help().
def add(a, b):
"""Returns sum of two numbers"""
return a + b
print(add(5, 3)) # Output: 8
help(add) # Shows documentation
5. Keyword and Optional Parameters
• Keyword arguments: specify parameter names explicitly.
• Optional parameters: parameters with default values.
def greet(name, msg="Welcome"):
print(f"Hello {name}, {msg}!")
greet("Alice") # Hello Alice, Welcome!
greet("Bob", msg="Hi!") # Hello Bob, Hi!
6. Passing Collections to a Function
• Functions can take lists, tuples, sets, dictionaries as arguments.
def print_list(lst):
for item in lst:
print(item)
print_list([1, 2, 3])
Output:
1
• Dictionaries:
def print_dict(d):
for key, value in [Link]():
print(f"{key}: {value}")
print_dict({"a": 1, "b": 2})
7. Variable Number of Arguments
• *args for variable positional arguments.
• **kwargs for variable keyword arguments.
def add_numbers(*args):
return sum(args)
print(add_numbers(1, 2, 3, 4)) # Output: 10
def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Alice", age=25)
8. Scope of Variables
• Local Variables: defined inside function, accessible only there.
• Global Variables: defined outside functions, accessible everywhere.
x = 10 # global
def func():
y = 5 # local
print(x + y)
func() # Output: 15
# print(y) # Error: y is not defined
• Use global keyword to modify global variables:
x = 10
def modify():
global x
x += 5
modify()
print(x) # Output: 15
9. Functions as "First Class Citizens"
• Functions can be assigned to variables, passed as arguments, or returned from
other functions.
def square(x):
return x*x
f = square # assign function to variable
print(f(5)) # Output: 25
10. Passing Functions to a Function
• Functions can accept other functions as parameters.
def apply_func(func, value):
return func(value)
def cube(x):
return x**3
print(apply_func(cube, 3)) # Output: 27
11. Exam Tips / Important Points
1. Syntax: def func_name(params):
2. Docstring: Always document your function for clarity.
3. Default values: Avoid errors by providing optional parameters.
4. Variable arguments: Use *args and **kwargs for flexible inputs.
5. Scope: Know difference between local and global variables.
6. First-class functions: Functions can be treated like variables.
7. Passing functions: Useful in higher-order functions, callbacks, etc.
12. Advanced Example – Full Program
def apply_operation(func, *args):
"""Applies a function to multiple arguments"""
results = [func(x) for x in args]
return results
def square(x):
return x*x
def cube(x):
return x**3
print(apply_operation(square, 1, 2, 3, 4)) # [1, 4, 9, 16]
print(apply_operation(cube, 1, 2, 3, 4)) # [1, 8, 27, 64]
. Mapping Functions in a Dictionary
Theory (Beginner-Friendly)
• In Python, functions are first-class objects, meaning they can be assigned to
variables, passed as arguments, or stored in data structures like lists or dictionaries.
• Using a dictionary to map keys to functions allows dynamic execution, avoiding long
if-else statements.
Example 1 – Basic Mapping
def add(a, b):
return a + b
def subtract(a, b):
return a - b
# Dictionary mapping
operations = {"add": add, "subtract": subtract}
# Call functions via dictionary
print(operations["add"](10, 5)) # Output: 15
print(operations["subtract"](10, 5)) # Output: 5
Example 2 – Dynamic User Input
def greet():
print("Hello!")
def farewell():
print("Goodbye!")
menu = {"1": greet, "2": farewell}
choice = input("Enter 1 for Hello, 2 for Goodbye: ")
[Link](choice, lambda: print("Invalid choice"))() # Calls default if input invalid
Key Points:
1. [Link](key, default) avoids KeyError.
2. Functions can be called dynamically using () after dictionary lookup.
2. Lambda Functions
Theory
• Lambda functions are anonymous, single-line functions defined with lambda
keyword.
• Syntax:
• lambda arguments: expression
• Useful for short operations where defining a full function is unnecessary.
Example 1 – Simple Lambda
square = lambda x: x**2
print(square(5)) # Output: 25
Example 2 – Lambda in Dictionary Mapping
operations = {
"square": lambda x: x**2,
"cube": lambda x: x**3
print(operations ) # Output: 16
print(operations ) # Output: 8
Example 3 – Lambda with Multiple Arguments
multiply = lambda a, b: a * b
print(multiply(6, 7)) # Output: 42
Key Points:
1. Lambda functions cannot contain multiple statements.
2. They are often used with map(), filter(), reduce().
3. Can be stored in variables or dictionaries.
3. Modules in Python
Theory
• A module is a file containing Python code (functions, classes, variables).
• Modules allow code reuse, organization, and separation of concerns.
• Python has built-in modules (e.g., math, os, random) and you can create custom
modules.
3.1 Importing Modules
# Import entire module
import math
print([Link](16)) # Output: 4.0
# Import specific functions
from math import factorial
print(factorial(5)) # Output: 120
# Import with alias
import math as m
print([Link](2, 3)) # Output: 8.0
3.2 Creating a Custom Module
my_module.py
def greet(name):
print(f"Hello, {name}!")
def farewell(name):
print(f"Goodbye, {name}!")
[Link]
import my_module
my_module.greet("Alice") # Output: Hello, Alice!
my_module.farewell("Bob") # Output: Goodbye, Bob!
Key Points:
1. Modules help organize code and avoid repetition.
2. Custom modules are imported just like built-in modules.
3. Use __name__ == "__main__" to run code only when module is executed directly.
4. Combining All Concepts
Example – Calculator with Lambda & Dictionary
calculator = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b if b != 0 else "Division by zero!"
a, b = 10, 5
for op in calculator:
print(f"{a} {op} {b} = {calculator[op](a, b)}")
Output:
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.0
Explanation:
• Dictionary keys are operators.
• Lambda functions perform the operation dynamically.
• No if-else needed.
Exam Points to Remember:
1. Functions are first-class objects; can be stored in dictionaries.
2. Lambda functions are single-line anonymous functions.
3. Modules help organize code and can be built-in or custom.
4. Using dictionaries + lambda makes programs dynamic and concise.
5. Always test for invalid keys or exceptions when mapping functions.
ambda Functions are anonymous functions means that the function is without a name. As
we already know def keyword is used to define a normal function in Python. Similarly,
lambda keyword is used to define an anonymous function in Python.
In the example, we defined a lambda function to convert a string to its upper case
using upper().
s1 = 'GeeksforGeeks'
s2 = lambda func: [Link]()
print(s2(s1))
Output
GEEKSFORGEEKS
Explanation: s2 is a lambda function that takes a string and returns it in uppercase. Applying
it to 'GeeksforGeeks' gives the result.
Syntax
lambda arguments : expression
• lambda: The keyword to define the function.
• arguments: A comma-separated list of input parameters like in a regular function.
• expression: A single expression that is evaluated and returned.
Use Cases of Lambda Functions
Let's see some of the practical uses of the Python lambda function.
1. Using with Condition Checking
A lambda function can include conditions using if statements.
Here, the lambda function uses nested if-else logic to classify numbers as Positive, Negative
or Zero.
n = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero"
print(n(5))
print(n(-3))
print(n(0))
Output
Positive
Negative
Zero
Explanation:
• The lambda function takes x as input.
• It uses nested if-else statements to return "Positive," "Negative," or "Zero."
This lambda checks divisibility by 2 and returns "Even" or "Odd" accordingly.
check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(4))
print(check(7))
Output
Even
Odd
Explanation:
• The lambda checks if a number is divisible by 2 (x % 2 == 0).
• Returns "Even" for true and "Odd" otherwise.
• This approach is useful for labeling or categorizing values based on simple conditions.
2. Using with List Comprehension
Combining lambda with list comprehensions enables us to apply transformations to data in a
concise way.
This code creates a list of lambda functions, each multiplying its input by 10 and then
executes them one by one.
li = [lambda arg=x: arg * 10 for x in range(1, 5)]
for i in li:
print(i())
Output
10
20
30
40
Explanation:
• The lambda function multiplies each element by 10.
• The list comprehension iterates through li and applies the lambda to each element.
• This is ideal for applying transformations to datasets in data preprocessing or
manipulation tasks.
3. Using for Returning Multiple Results
Lambda functions do not allow multiple statements, however, we can create two lambda
functions and then call the other lambda function as a parameter to the first function.
The lambda calculates both sum and product of two numbers and returns them as a tuple.
calc = lambda x, y: (x + y, x * y)
res = calc(3, 4)
print(res)
Output
(7, 12)
Explanation:
• The lambda function performs both addition and multiplication and returns a tuple
with both results.
• This is useful for scenarios where multiple calculations need to be performed and
returned together.
4. Using with filter()
filter() function in Python takes in a function and a list as arguments. This offers an elegant
way to filter out all the elements of a sequence "sequence", for which the function returns
True.
Here, the lambda is used as a filtering condition to keep only even numbers from the list.
n = [1, 2, 3, 4, 5, 6]
even = filter(lambda x: x % 2 == 0, n)
print(list(even))
Output
[2, 4, 6]
Explanation:
• The lambda function checks if a number is even (x % 2 == 0).
• filter() applies this condition to each element in nums.
5. Using with map()
map() function in Python takes in a function and a list as an argument. The function is called
with a lambda function and a new list is returned which contains all the lambda-modified
items returned by that function for each item.
This code doubles each element of the list using a lambda function and returns a new list.
a = [1, 2, 3, 4]
b = map(lambda x: x * 2, a)
print(list(b))
Output
[2, 4, 6, 8]
Explanation:
• The lambda function doubles each number.
• map() iterates through a and applies the transformation.
6. Using with reduce()
reduce() function in Python takes in a function and a list as an argument. The function is
called with a lambda function and an iterable and a new reduced result is returned. This
performs a repetitive operation over the pairs of the iterable. The reduce() function belongs
to the functools module.
Here, the lambda multiplies two numbers at a time and reduce() applies this across the
whole list to calculate the product.
from functools import reduce
a = [1, 2, 3, 4]
b = reduce(lambda x, y: x * y, a)
print(b)
Output
24
Explanation:
• The lambda multiplies two numbers at a time.
• reduce() applies this operation across the list.
Difference Between lambda and def Keyword
In Python, both lambda and def can be used to define functions, but they serve slightly
different purposes. While def is used for creating standard reusable functions, lambda is
mainly used for short, anonymous functions that are needed only temporarily.
# Using lambda
sq = lambda x: x ** 2
print(sq(3))
# Using def
def sqdef(x):
return x ** 2
print(sqdef(3))
Output
Explanation:
• lambda function sq takes a number and returns its square.
• regular function sqdef does the same but is defined using the def keyword.
• Both approaches give the same result but lambda is more concise.
Now, let’s see a comparison between these two in tabular form:
Feature lambda Function Regular Function (def)
Definition Single expression with lambda. Multiple lines of code.
Anonymous or named if
Name Must have a name.
assigned.
Statements Single expression only. Can include multiple statements.
Documentation Cannot have a docstring. Can include docstrings.
Best for short, temporary Better for reusable and complex
Reusability
functions. logic.