Functions
In
Python
A function in Python is a block of
organized, reusable code designed to
perform a specific task.
What are It encapsulates a sequence of statements
that can take inputs, process them, and
Functions? produce outputs.
A program can contain different
functions, Each function in a program may
have one or more tasks to be performed.
Why need Functions?
To improve
Reduces the Errors are
Reusabality of the
size of the easy to be
Code readability of
code traced
code.
Function Syntax
def function_name(parameters):
"""A Comment on what this function does"""
statement(s)
Example:
def greet():
"""This function prints a welcome message."""
print("Hello! Welcome to Python programming.")
Parameters and comments are optional
Contd.
•def → keyword to define a function
•function_name → name you give the function
•(parameters) → inputs to the function (can be empty)
•"""docstring""" → optional comment explaining purpose
•statement(s) → code block inside the function
•return → sends back a result (optional)
• Can only contain letters, digits, and underscores
✅ Example: my_function, calculate_sum
❌ Example: my-function, calculate sum
• Must start with a letter or underscore (_)
✅ Example: greet_user, _hidden_function
Rules for naming ❌ Example: 1function
a function • Cannot be a Python keyword
❌ Example: def, class, return (reserved words)
• Case-sensitive
myFunction, MyFunction, and MYFUNCTION are all different
names.
Return statement
It is used to exit the current function that is being executed and to transfer control
back to the point where the function was called.
Features of the return statement:
• Contain an expression, which is evaluated, and the resulting value is returned.
• Value can be directly returned.
• If a function's return statement lacks an expression, the function will return None.
• If a function lacks a return statement, it will return None.
• Python functions can return multiple values simultaneously.
Types of Functions:
[Link]-defined functions – Defined by the programmer
Eg: add_numbers().
2. Built-in functions – Provided by Python
Eg: print(), len(), sum().
3. Lambda functions – Small anonymous functions defined in a single line
(Will discuss later)
Declaration (definition) → tells
Python what the function will do.
Function
Declaration Call → actually runs the function.
and call
If you only declare a function
but don’t call it, nothing
happens.
Argument: Parameter
An argument is an expression passed to a When you define a function, you list
function by its caller, enabling the parameters inside the parentheses.
function to perform its task. Parameters act like local variables within
Arguments are elements within a the function, holding the values provided
comma-separated list enclosed by by arguments.
parentheses in a function call expression. They only exist while the function is
They are specified only in the function executing (temporary memory
call (not in the declaration). allocation).
They are defined in the calling function.
Example of Argument and parameters
def greet(name, age): # name and age are parameters
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 25) # "Alice" and 25 are arguments
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
Types of arguments
• Positional arguments: It depend on the order they are passed to a function.
Example: voter_id(name, age).
Here, the first argument should be a string representing the name, and the second argument should be an
integer representing the age.
• Keyword arguments: Keyword arguments are passed as key-value pairs using the = operator. This
allows the Python interpreter to ignore their position.
Example: def team(name, company):
print(name, "is working at", company)
team(company = "Google", name = 'John')
Order of keyword arguments doesn't matter
Practice Question
Solution
QUESTIONS
• Write a function to find the square of a number.
• Write a function that takes a name as input and prints
“Hello <name>”.
• Write a function to check whether a number is even or
odd.
• Write a function to calculate the factorial of a number.
Write a function to find the maximum of three numbers.
Write a function that takes a list of numbers and returns
their average.
Q1. Employee Details
Write a function employee(*, name, salary) that accepts only
keyword arguments.
Take input from the user for the employee’s name and salary.
Print the employee details.
Q2:Write a function car(*, brand, price) that prints the brand and
price of a car.
Q3. Student Marks Write a function marks(*, name, maths,
science) that accepts only keyword arguments
Q4. Person Introduction
• Write a function introduce(*, first, last, age) that only accepts
keyword arguments.
• def employee(*, name, salary):
• print("Employee Name:", name)
• print("Salary:", salary)
• n = input("Enter employee name: ")
• s = int(input("Enter salary: "))
• employee(name=n, salary=s)
def car(*, brand, price):
print("Brand:", brand)
print("Price:", price)
b = input("Enter car brand: ")
p = int(input("Enter car price: "))
car(brand=b, price=p)
def marks(*, name, maths, science):
print(f"Student: {name}, Maths: {maths}, Science: {science}")
n = input("Enter student name: ")
m = int(input("Enter Maths marks: "))
s = int(input("Enter Science marks: "))
marks(name=n, maths=m, science=s)
def introduce(*, first, last, age):
print(f"My name is {first} {last} and I am {age} years old.")
f = input("Enter first name: ")
l = input("Enter last name: ")
a = int(input("Enter age: "))
introduce(first=f, last=l, age=a)
What’s the error in the code?
• def my_fun(*, x, y):
• print(x + y)
• my_fun(10, 20)
Default Arguments
1. Provide default values:
• You can assign a default value to a function parameter.
• If a value is passed by the user, it overrides the default.
• If the user doesn’t pass a value, Python automatically uses the default.
Example:
Users only need to pass values if they want something different from the default.
Default Arguments Contd.
2. Must follow non-default arguments
• All default parameters must be placed after non-default parameters.
• Otherwise, Python will throw a syntax error.
Example:
Variable-length Arguments
• Used when you don’t know how many arguments will be passed into a function during execution.
• This kind of scenario can be addressed with a function defined to handle an arbitrary number of arguments,
which can then be called.
• Asterisk (*) is used in the function definition. Placing the asterisk before the parameter name indicates that
this type of parameter can accommodate numerous arguments.
Syntax:
def fun_name( * args)
There are two types of variable-length arguments:
*args → handles multiple positional arguments
**kwargs → handles multiple keyword arguments
*args (Arbitrary Positional Arguments)
• Collects extra positional arguments into a tuple.
• Use it when you don’t know how many values will be given.
Example:
**kwargs (Arbitrary Keyword Arguments)
• Collects extra keyword arguments into a dictionary.
• Use it when you want to pass values as key-value pairs.
Example:
Practice Question
Solution
# Function that accepts variable number of arguments
def mySum(*args):
total = 0
for n in args:
total += n
return total
# Taking 4 inputs from the user
a = int(input("Enter value of a: "))
b = int(input("Enter value of b: "))
c = int(input("Enter value of c: "))
d = int(input("Enter value of d: "))
# Calling the function with different combinations
print("Sum of a, b, c, d =", mySum(a, b, c, d))
print("Sum of a, b, c =", mySum(a, b, c))
print("Sum of a, b =", mySum(a, b))
Anonymous Function (lambda functions)
• An anonymous function is a function without a name.
• In Python, we create them using the lambda keyword.
• That’s why they are also called lambda functions.
Syntax:
lambda arguments: expression
arguments → the inputs
expression → what to return
Regular vs. Lambda Function
• def square(x): return x * x → defines a normal function with the name square.
• square_lambda = lambda x: x * x → defines the same functionality but without a name; instead, it’s
stored in the variable square_lambda.
• Both return the square of a number.
• filter()
• The filter() function is used to filter out elements from a list (or any sequence)
based on a condition.
• It takes two things:
A function (the condition to test each element).
A sequence (like a list).
• It returns only those elements that satisfy the condition.
filter(function, iterable)
• filter() takes two arguments: a function and an iterable.
• The function should return True/False for each element.
• If True → element is kept. If False → element is removed.
Using Example 1: Filter even numbers using lambda
Lambda with •The function is lambda n: n % 2 == 0.
•For each number n in the list, it checks if n % 2 == 0 (i.e., divisible
filter () by 2).
•If true, the number is kept.
•This way, filter() extracts only the even numbers.
Output: Even numbers: [2, 4, 6]
Practice Question
Create an anonymous (lambda) function and assign it to a variable named doublenum.
This function should double the value passed to it. Then, prompt the user to enter an
integer using "a: " as the prompt message. Pass this value to the function and print the
returned result.
Map Function
The map() function applies a function to each element of an iterable (like list, tuple).
Syntax
map(function, iterable)
Function: The function you provide as the first argument is applied to each element in the
sequence.
iterable: A collection of items (e.g., list, tuple) to which the function will be applied.
returns: An iterator that yields the transformed elements. You can convert it to a list or a
tuple if needed.
Filter vs Map
• If you want to select / keep only certain elements → use filter().
• If you want to change / transform every element → use map().
Function Purpose Example Output
filter() Select elements based on condition [50, 65, 85, 40] (passing marks only)
map() Transform each element ['Pass', 'Pass', 'Pass', 'Pass'] (marks → grade)
Filter() Map()
Marks = [35, 50, 65, 20, 85, 40] Marks = [35, 50, 65, 85, 40]
Condition = keep only marks >= 40 Transformation = convert each mark into "Pass" or "Fail"
Result = [50, 65, 85, 40] Result = ['Fail', 'Pass', 'Pass', 'Pass', 'Pass’]
Only passing marks are filtered out. Every mark is mapped into a grade.
Example: numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
print(squares)
Explanation: lambda x: x * x
map(lambda x: x * x, numbers) •This is an anonymous function
•Here we call the map() function. •For each element x in the list, it calculates x * x
•map() takes two things: (square).
• A function (in this case: lambda x: x * x) •Example: if x = 2 → returns 4.
• An iterable (in this case: numbers)
Result of map()
•map() does not directly give a list. How map() works internally:
•It gives a map object (an iterator). •It takes the first element of the list (1), applies the
function (1*1=1).
•Takes the second element (2), applies the function
list(map(...)) (2*2=4).
•We wrap map() inside list() to convert the result into a •Takes the third element (3), applies the function (3*3=9).
list. •And so on for all elements.
•So now we actually see [1, 4, 9, 16, 25].
Practice Questions
• Q1. Write a lambda function to find the square of a number and
use it to calculate square of 8.
• Use a lambda function with map() to add 5 to each element in
the list [1, 2, 3, 4].
• Use a lambda function with filter() to extract even numbers
from [10, 15, 20, 25, 30].
• Write a lambda function to check if a number is positive,
negative, or zero using conditional expression.
• Combine two lists element-wise using map() and a lambda
function to create sums.
• Filter words with length > 3 from the list ["cat", "lion",
"tiger", "dog"].
square = lambda x: x ** 2
print(square(8))
nums = [1, 2, 3, 4]
result = list(map(lambda x: x + 5, nums))
print(result)
• nums = [10, 15, 20, 25, 30]
• even_nums = list(filter(lambda x: x % 2 == 0, nums))
• print(even_nums)
check = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else
"Zero"
print(check(-5))
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sums = list(map(lambda x, y: x + y, list1, list2))
print(sums)
• words = ["cat", "lion", "tiger", "dog"]
• long_words = list(filter(lambda x: len(x) > 3, words))
• print(long_words)
Local
and
Global Variables
Local Variables
• A local variable is a variable that is defined inside a function.
• It is accessible only within that function.
• Local variables are created when the function is called and destroyed when the function ends.
• Two functions can have local variables with the same name, but they are stored separately in memory and do not
affect each other.
Global Variables
• A global variable is a variable that is defined outside all functions and is accessible from any function in the
program.
• Global variables retain their values throughout the program execution and across function calls.
• If a local variable with the same name is defined inside a function, the local variable takes precedence over the
global variable inside that function.
• To modify a global variable inside a function, you must declare it as global; otherwise, Python creates a new
local variable with the same name.
Example of local
variable
In this code :
We are creating a local variable “x” inside a function and then trying to access it outside
the function, which causes an error.
Example:
In this code :
• x= 10 is a global variable, visible to all functions.
• func1() accesses without modifying it, prints 10.
• func2() declares as global and modifies it,the change
affects the variable globally.
• The final print shows that the global variable retains
the modified value after the function call.
Function composition
Function composition means combining two or more functions together so
that the output of one function becomes the input of the next.
Example:
Consider two functions f_1 and f_2.
• Composition of two functions f_1 and f_2 is denoted f_1(f_2(x)).
• x is the argument of f_2.
• The return value of f_2 is passed as an argument to f_1.
• The result of the composition is the return value of f_1.
Example of function composition:
Nested Function
• A nested function is simply a function defined inside another function.
• The outer function can call the inner one.
• Inner function can access variables of the outer function (this is called closure).
Syntax of a Nested Function:
def outer_function():
# Code of the outer function
def inner_function():
# Code of the inner function
print("Hello from the inner function!")
# Calling the inner function from inside the outer function
inner_function()
Step-by-Step Flow:
1. Define outer
• Python sees the outer() function and stores it in memory.
Example of Nested Function: • Inside outer, there’s another function inner(x) defined.
2. Call outer()
new_func = outer()
• When outer() is called:
• It does not run inner immediately.
• Instead, it returns the function object inner.
So now, new_func is actually referring to the inner function.
new_func = inner
3. Call new_func(10)
print(new_func(10))
• Since new_func = inner, this is actually calling:
• inner(10)
• Inside inner:
x + 1 → 10 + 1 = 11
4. Final Output:
11
Lexical Scoping
• Scope = where a variable is visible/accessible in code.
• Lexical scope means → the inner function can “see” and remember
variables defined in the outer function, even after the outer function has
finished running.
Variables defined in the outer function are accessible to the inner function.
Inner functions remember the variables of the outer function even after the outer
function finishes (closure).
The scope is determined by where the function is written, not where it is called
Example
Workflow:
[Link] outer() runs, it creates a variable message = "Hello from outer!".
[Link] function inner() is defined inside, and it remembers that message exists.
[Link] though outer() is finished, Python keeps message alive because inner still needs it.
[Link] func() (which is inner) runs → it can still access "Hello from outer!".
This “remembering” is called a closure.
WHAT WILL BE THE OUTPUT?
• def outer():
• x=5
• def inner():
• y = 10
• print(x + y)
• inner()
• outer()
• def outer(a):
• def inner(b):
• return a + b
• return inner
• add_5 = outer(5)
• print(add_5(3))
• def outer():
• def inner():
• print("Inner function executed")
• return inner
• func = outer()
• func()