Exploring Functions in Python
Exploring Functions in Python
Why Functions?
Code Reusability: Write once, use multiple times, reducing redundancy.
Modularity: Break programs into smaller parts, making them easier to understand
and debug.
Scalability: Functions allow for scaling programs by adding functionality without
altering existing code.
Built-in and Customizable: Python provides many built-in functions, and
developers can create custom functions to suit their needs.
Join me in exploring Python functions and their role in building efficient, modular, and
scalable programs!
def is_even(num):
"""
This function returns if a given number is even or odd
input- any valid integer
output- odd/even
created on - 12 January 2025
"""
if type(num) == int:
if num % 2 == 0:
return 'even'
else:
return 'odd'
else:
return 'kuchh v karte ho bhai '
file:///C:/Users/goura/Downloads/06-Functions.html 1/18
1/13/25, 2:52 PM 06-Functions
In [2]: # Function
# Function_name(input)
for i in range(1,11):
x = is_even(i)
print(i,x)
1 odd
2 even
3 odd
4 even
5 odd
6 even
7 odd
8 even
9 odd
10 even
2 Point of views
In [3]: is_even('hello')
In [4]: is_even(9)
Out[4]: 'odd'
Parameters Vs Arguments
at the time of making function that is known as parameter and at the time when we
are using that function that is known as argument
Tpes of Arguments
Default Argument
Positional Argument
Keyword Argument
Default Argument
file:///C:/Users/goura/Downloads/06-Functions.html 2/18
1/13/25, 2:52 PM 06-Functions
Using Default Arguments, you can assign a default value to a function parameter.
This makes the function more flexible and helps in handling errors.
If the user does not pass any value, the default value is used, allowing the function to
work without interruption.
Example:
def greet(name="Guest"):
print(f"Hello, {name}! Welcome to Python programming.")
print(calculate_total(100))
print(calculate_total(100, 0.10))
105.0
110.0
Positional Argument
Positional Argument ka matlab hai ki function ke arguments ko unke position ke basis
par pass kiya jata hai.
Arguments ko unhi order mein pass karna hota hai, jisme function ke parameters define
kiye gaye hain.
Agar arguments galat order mein diye gaye, to unexpected behavior ya error aa sakti hai.
Positional arguments simple aur basic tarika hai function ke parameters ko value assign
karne ka.
Example:
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
file:///C:/Users/goura/Downloads/06-Functions.html 3/18
1/13/25, 2:52 PM 06-Functions
15
15
Keyword Argument
Keyword Arguments are arguments passed to a function by explicitly specifying the
parameter name along with its value.
This makes the function call more readable and allows arguments to be passed in any
order.
Example:
def introduce(name, age, city):
print(f"My name is {name}, I am {age} years old, and I live in
{city}.")
105.0
105.0
file:///C:/Users/goura/Downloads/06-Functions.html 4/18
1/13/25, 2:52 PM 06-Functions
*args and **kwargs are special Python keywords that allow functions to accept a
variable number of arguments.
They are used when the number of arguments that will be passed to the function is
unknown.
*args
*args allows a function to accept any number of positional arguments.
These arguments are passed as a tuple to the fuut: Sum of numbers: 0
def add_numbers(*args):
total = sum(args)
print(f"Sum of numbers: {total}")
Sum of numbers: 15
Sum of numbers: 0
**kwargs
**kwargs allows a function to accept any number of keyword arguments.
These arguments are passed as a dictionary to the function.
name: Gourab
age: 25
city: Kolkata
file:///C:/Users/goura/Downloads/06-Functions.html 5/18
1/13/25, 2:52 PM 06-Functions
In [17]: print(is_even.__doc__)
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
In [20]: display(Bihar='Patna',Punjab='chandigarh',Telangana='Hyderabad')
Local Variable
A local variable is a variable that is defined inside a function and is only accessible
within that function's scope.
file:///C:/Users/goura/Downloads/06-Functions.html 6/18
1/13/25, 2:52 PM 06-Functions
Key Difference:
1. Local variables cannot be accessed outside their function.
2. Global variables, however, can be accessed and modified (if required) inside a
function using the global keyword.
Example:
In [21]: # Global variable
x = 10
def my_function():
# Local variable
y = 5
print(f"Local variable y: {y}")
print(f"Global variable x accessed inside function: {x}")
my_function()
Local variable y: 5
Global variable x accessed inside function: 10
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[23], line 2
1 # Accessing local variable outside function will throw an error
----> 2 print(y)
In [24]: # If a variable is not defined inside the function, it can use the global variab
# However, changes to the global variable are not allowed.
def h(y):
x += 1
x = 5
h(x)
print(x)
file:///C:/Users/goura/Downloads/06-Functions.html 7/18
1/13/25, 2:52 PM 06-Functions
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Cell In[24], line 8
5 x += 1
7 x = 5
----> 8 h(x)
9 print(x)
def g(x):
# Local scope: x is a local variable within the function
print(x) # This will print the value of x passed to the function
print(x + 1) # This will print the value of x + 1
x = 5 # Global variable
a = g(x) # Calling the function with x as an argument
print(a) # This will print the value of a, which is None since g() does
5
6
None
def f(y):
# Local variable x is created inside the function with a value of 1
x = 1
x += 1 # Local x is incremented by 1, so x becomes 2
print(x) # This will print the local x, which is 2
2
5
x = 5 # Global variable x
h(x) # Calling the function h() with x as the argument
print(x) # This will not execute due to the error in the function
file:///C:/Users/goura/Downloads/06-Functions.html 8/18
1/13/25, 2:52 PM 06-Functions
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Cell In[27], line 5
2 x += 1 # This will throw an error because x is not declared as globa
l
4 x = 5 # Global variable x
----> 5 h(x) # Calling the function h() with x as the argument
6 print(x)
x = 3
z = f(x)
print("in main program scope: z = ",z)
print("in main program scope: x = ",x)
in f(x): x = 4
in main program scope: z = 4
in main program scope: x = 3
Nested Functions
In Python, a nested function is a function defined inside another function.
A nested function can access variables from its enclosing function's scope. These are
often used for cases where you want to use a function temporarily or to create closures.
Example:
In [29]: # Nested Functions in Python
def f():
def g():
print('inside function g')
# f() # Uncommenting this would lead to a RecursionError
inside function g
inside function f
file:///C:/Users/goura/Downloads/06-Functions.html 9/18
1/13/25, 2:52 PM 06-Functions
x = 5
print(outer_function(x)) # Output: 6
def g(x):
def h(x):
x = 'abc' # This assigns 'abc' to the local variable x within function
x += 1 # This modifies the local variable x in function g
print("in g(x): x =", x) # This prints the value of x after it is increment
h(x) # Calling the nested function h() with x
return x # Returning the value of x after incrementing
x = 3 # Global variable x
z = g(x) # Calling function g with x as argument
print(z) # This prints the returned value of x from function g
in g(x): x = 4
4
x = 3
z = g(x)
print('in main programme scope: x= ', x)
print('in main programme scope: z= ', z)
in g(x): x = 4
in h(x): x = 5
in main programme scope: x= 3
in main programme scope: z= 4
def square(num):
# A simple function that returns the square of the given number
return num**2
<class 'function'>
2166862109472
file:///C:/Users/goura/Downloads/06-Functions.html 10/18
1/13/25, 2:52 PM 06-Functions
def square(num):
return num**2
# Checking the unique identifier (memory address) of 'x' (which now refers to th
print(id(x))
# Calling the function using 'x' (it behaves the same as 'square')
print(x(3)) # This will print 9, as 3^2 = 9
2166862113472
9
In [36]: # storing
L = [1,2,3,4,5,square]
L
Sets and Immutability: A set in Python is an unordered collection that only allows
immutable data types as elements. This means that you cannot add mutable data
types like lists, dictionaries, or other sets into a set.
Example:
In [37]: # Adding a function to a set
def square(num):
return num**2
my_set = {square}
True
file:///C:/Users/goura/Downloads/06-Functions.html 11/18
1/13/25, 2:52 PM 06-Functions
my_set.add(cube)
True
def func_a():
# Function that prints a message
print('inside func_a')
def func_b(z):
# Function that takes another function as argument
print('inside func_b')
return z() # Calls the function passed as argument (z)
inside func_b
inside func_a
None
Code Readability
Since the code is divided into separate functions, it becomes easier to read and
understand. In a team environment, you can assign different functionalities to different
team members. For instance, one person can work on the login function, another on
registration, etc. This enhances collaboration and reduces complexity.
Code Reusability
Once a function is written, it can be reused multiple times across your program. This
reduces redundancy and makes your code more efficient. For example, if you need to use
the login function at several points in your application, you can call it each time without
having to rewrite the same code.
file:///C:/Users/goura/Downloads/06-Functions.html 12/18
1/13/25, 2:52 PM 06-Functions
Lambda Function: A, B: A + B
Lambda Keyword:
The lambda keyword is used to create an anonymous function (a function without
a name) in Python.
Parameters (A, B) :
A lambda function can take one or more parameters, which should be separated by
commas.
Unlike regular functions, lambda functions do not require parentheses around the
parameters if there are no default values.
Colon : :
The colon : separates the parameters from the expression. It signals the start of
the function body.
Expression (A + B) :
The expression is a single, valid Python expression that gets evaluated and returned.
In a lambda function, you cannot include statements or multiple expressions. In this
case, A + B is the expression that returns the sum of A and B .
Lambda Function
A lambda function is a small anonymous function defined using the lambda
keyword.
Key Points:
A lambda function can take any number of arguments, but it can only have one
expression.
The expression is evaluated and returned when the function is called.
Lambda functions are often used for short-term, quick operations where defining a
full function is unnecessary.
file:///C:/Users/goura/Downloads/06-Functions.html 13/18
1/13/25, 2:52 PM 06-Functions
Normal Function:
Has a Name: Normal functions are defined using the def keyword and can be
called by their name.
Return Value: Normal functions explicitly use the return keyword to return a
value.
Multiple Lines: Normal functions can span multiple lines, allowing more complex
logic.
Reusable: Normal functions are reusable and can be called multiple times
throughout your code.
Example:
In [41]: # Lambda Function Example
add = lambda x, y: x + y
print(add(3, 4)) # Output: 7
file:///C:/Users/goura/Downloads/06-Functions.html 14/18
1/13/25, 2:52 PM 06-Functions
Out[43]: False
Out[44]: 'odd'
Explanation:
Higher-order functions allow us to treat functions as first-class citizens by passing
them as arguments or returning them from other functions.
These functions are commonly used in functional programming and are essential for
creating more modular and reusable code.
Higher order function ek aisa function hota hai jiske return me aapko khud ek
fuction milta hai (ek aisa fuction jo ek fuction ko return karta hai) ya phir aisa fuction
jo input me dusre fuction ko recieve kare usko higher order function kahte hain.
In [45]: # Example
def square(x):
return x**2
# HOF
print(output)
L = [1,2,3,4,5]
# transform(square,L)
file:///C:/Users/goura/Downloads/06-Functions.html 15/18
1/13/25, 2:52 PM 06-Functions
# OR
transform(lambda x:x**2,L)
map()
map always expects two things: a lambda function and an iterable (like a list). Using
map , you can apply any logic or perform mapping on the elements of an iterable.
For example, if you're given a list and asked to find the square of each element, you can
easily do this using map() .
Example:
In [46]: # square the item of list
list(map(lambda x:x**2,[2,4,6,8,10,12]))
l = [1,2,3,4,5,6,7,8,9]
list(map(lambda x:'even' if x%2 ==0 else 'odd',l))
Out[48]: ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
In [49]: users = [{
'name':'gourab',
'age':26,
'gender':'male'},
{
'name':'saurabh',
'age':24,
'gender':'male'
},
{
'name':'suman',
'age':26,
'gender':'male'
},
{
'name':'saroj',
'age':26,
'gender':'male'
}
]
file:///C:/Users/goura/Downloads/06-Functions.html 16/18
1/13/25, 2:52 PM 06-Functions
list(map(lambda users:users['name'],users ))
list(map(lambda users:users['age'],users ))
list(map(lambda users:users['gender'],users ))
filter()
filter() is also a higher-order function that filters a given list based on a condition. It
requires two things:
[7, 9, 11]
file:///C:/Users/goura/Downloads/06-Functions.html 17/18
1/13/25, 2:52 PM 06-Functions
reduce()
Imagine you have a list, and you want to calculate the sum of all its items. You can do this
in a single line using reduce() . Like map() and filter() , reduce() also requires
two things:
15
working--> (1+2+3+4+5)(1+2,3,4,5)(3+3,4,5)(6+4,5)(10+5)
It picks only two items at a time, compares them, and discards the one that is false.
Then, it picks the next item, because one of them is already being carried over. It
works iteratively, but at any point, it only operates on two items. Finally, it will return
a single value.
Out[55]: 1
Out[56]: 45
In [ ]:
file:///C:/Users/goura/Downloads/06-Functions.html 18/18