Unit-II
Q.1 Define function in python? Write it's syntax. Explain
the formal and actual arguments with a suitable example.
Ans: ✅ Q.1 Define function in Python
Definition:
A function in Python is a reusable block of code that performs a specific task. It helps to
divide the program into smaller, organized, and manageable sections. Functions help in
reducing code repetition and increasing reusability.
✅ Syntax of a Function in Python:
def function_name(parameters):
# function body
statements
return result # optional
def: Keyword used to define a function.
function_name: Name of the function.
parameters: (optional) Input values passed to the function.
return: (optional) Used to return a value from the function.
✅ Example:
def greet(name): # 'name' is a formal argument
print("Hello", name)
greet("Alice") # "Alice" is an actual argument
✅ Formal and Actual Arguments:
Type of
Explanation Example
Argument
Formal The variable name listed in the function name in def
Argument definition. greet(name):
Actual The real value passed to the function when it is "Alice" in
Argument called. greet("Alice")
➤ Formal Arguments are placeholders.
➤ Actual Arguments are the real data passed when calling the function.
✅ Output of the Example:
Hello Alice
Let me know if you'd like an example using multiple arguments or return values too!
Q.2 What is the lambda function? Write the
characteristics of a lambda function. Explain the same
with an example.
Ans: ✅ Q.2 What is a Lambda Function?
Definition:
A lambda function in Python is a small, anonymous function defined using the lambda
keyword. It can take any number of arguments but has only one expression.
✅ Syntax of Lambda Function:
lambda arguments: expression
✅ Characteristics of Lambda Function:
1. � Anonymous: Lambda functions don’t have a name unless assigned to a variable.
2. � Single Expression: Can only contain one expression (no statements, loops, etc.).
3. � Used for Short Functions: Often used where a full function is not necessary.
4. � Can be Used as an Argument: Commonly used with functions like map(),
filter(), and sorted().
✅ Example of Lambda Function:
# Lambda function to add two numbers
add = lambda x, y: x + y
# Call the lambda function
result = add(5, 3)
print("Sum:", result)
✅ Output:
Sum: 8
✅ Comparison with Normal Function:
# Normal function
def add(x, y):
return x + y
print(add(5, 3)) # Output: 8
Both the normal function and the lambda function above do the same task, but the lambda
version is more compact and useful for short, throwaway operations.
Let me know if you want examples using map(), filter(), or sorted() with lambda!
Q.3 What is recursive function? Write the recursive
function program to find factorial of a number.
Ans: ✅ Q.3 What is a Recursive Function?
Definition:
A recursive function is a function that calls itself during its execution to solve a smaller
instance of the same problem. It continues to call itself until a base condition is met, which
stops further recursion.
✅ Key Parts of Recursion:
1. Base Case – Condition where recursion stops.
2. Recursive Case – Function calls itself with a smaller/simpler input.
✅ Example: Recursive Function to Find Factorial
The factorial of a number n is:
n! = n × (n-1) × (n-2) × ... × 1
Also, 0! = 1 (by definition)
✅ Python Program Using Recursion:
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
# Example: Find factorial of 5
num = 5
print("Factorial of", num, "is", factorial(num))
✅ Output:
Factorial of 5 is 120
✅ How it works (Step-by-Step for n = 5):
factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120
Let me know if you want the same program using a loop instead of recursion!
Q.4 Differentiate global and local variables with a suitable
example.
Ans: ✅ Q.4 Difference Between Global and Local Variables
✅ Global Variable:
A global variable is declared outside any function and is accessible throughout the
program, including inside functions.
✅ Local Variable:
A local variable is declared inside a function, and it is accessible only within that
function.
✅ Difference Table:
Global Variable Local Variable
Declared outside functions Declared inside a function
Accessible anywhere in the code Accessible only within that function
Value remains throughout program Value exists only during function execution
Modified inside function using global keyword Directly used within the function
✅ Example:
x = 10 # Global variable
def example():
y = 5 # Local variable
print("Inside function - Global x:", x)
print("Inside function - Local y:", y)
example()
# Trying to access local variable y outside function will cause an error
print("Outside function - Global x:", x)
# print("Outside function - Local y:", y) # This would give an error
✅ Output:
Inside function - Global x: 10
Inside function - Local y: 5
Outside function - Global x: 10
� If you try to access y outside the function, you'll get a NameError, because it's a local
variable.
Let me know if you'd like an example where a function modifies a global variable using the
global keyword!
Q.5 Explain the Inductive function in python with a
suitable example.
Ans: ✅ Q.5 Explain the Inductive Function in Python
Definition:
An inductive function in Python is another way of referring to a recursive function, where
the solution to a problem depends on solutions to smaller instances of the same problem.
It follows the principle of mathematical induction:
Base Case: The simplest, smallest input for which the function returns a result
directly.
Inductive/Recursive Step: The function calls itself with a smaller/simpler input,
moving toward the base case.
✅ Example: Inductive (Recursive) Function to Calculate Sum of First N
Natural Numbers
Formula:
Sum(n)=n+Sum(n−1)\text{Sum}(n) = n + \text{Sum}(n-1)
with
Sum(1)=1(Base case)\text{Sum}(1) = 1 \quad \text{(Base case)}
✅ Python Program:
def sum_natural(n):
if n == 1: # Base case
return 1
else:
return n + sum_natural(n - 1) # Inductive step
# Example
num = 5
print("Sum of first", num, "natural numbers is:", sum_natural(num))
✅ Output:
Sum of first 5 natural numbers is: 15
✅ Explanation:
For n = 5, the function works as:
sum_natural(5)
= 5 + sum_natural(4)
= 5 + 4 + sum_natural(3)
= 5 + 4 + 3 + sum_natural(2)
= 5 + 4 + 3 + 2 + sum_natural(1)
= 5 + 4 + 3 + 2 + 1 = 15
So, an inductive function is just a recursive function that follows the logic of building the
solution step-by-step, based on a base case and an inductive step.
Let me know if you want this concept applied to another problem like Fibonacci!
Q.6 Explain the Call by value in python with a suitable
example.
Ans: ✅ Q.6 Explain Call by Value in Python
Definition:
In Call by Value, a copy of the actual value is passed to the function. Any changes made
inside the function do not affect the original variable outside the function.
� In Python, all arguments are passed by object reference, but:
Immutable types (like int, float, str, tuple) behave like Call by Value.
Mutable types (like list, dict) behave more like Call by Reference.
✅ Example of Call by Value with Immutable Type:
def modify(x):
x = x + 5
print("Inside function, x =", x)
a = 10
modify(a)
print("Outside function, a =", a)
✅ Output:
Inside function, x = 15
Outside function, a = 10
✅ Explanation:
a = 10 is an integer (immutable).
When passed to modify(x), a copy of a is sent.
Modifying x inside the function does not affect a outside.
So, even though Python doesn’t strictly use "Call by Value", with immutable types like int,
it behaves as if it does.
Let me know if you'd like an example where it behaves like Call by Reference using a list!
Q.7 What is module? How many ways to import module in
python? Explain the same with an example.
Ans: ✅ Q.7 What is a Module in Python?
Definition:
A module in Python is a file that contains Python code (functions, variables, classes, etc.)
which can be reused in other programs.
Modules help in organizing and separating code for better readability and reusability.
Python has:
Built-in modules (like math, random, datetime, etc.)
User-defined modules (your own .py files)
✅ Ways to Import a Module in Python:
Method Syntax Description
1. import module_name import math Imports the entire module
import math as
2. import module_name as alias m Imports with an alias name
3. from module_name import from math
import sqrt Imports a specific function
function_name
from math Imports all functions and variables
4. from module_name import * import * from the module
✅ Example Using Built-in math Module:
# Method 1
import math
print("Square root using math:", [Link](16))
# Method 2
import math as m
print("Ceiling using alias:", [Link](4.3))
# Method 3
from math import pow
print("Power using specific import:", pow(2, 3))
# Method 4
from math import *
print("Floor using wildcard import:", floor(4.9))
✅ Output:
Square root using math: 4.0
Ceiling using alias: 5
Power using specific import: 8.0
Floor using wildcard import: 4
Let me know if you want an example using a user-defined module too!
Q.8 What is Package? Give an example of package
creation in Python.
Ans: ✅ Q.8 What is a Package in Python?
Definition:
A package in Python is a way to organize related modules into a directory hierarchy.
It allows large programs to be broken into smaller, manageable parts.
A package is simply a folder that contains a special __init__.py file (can be empty), which
tells Python that the directory should be treated as a package.
✅ Why Use Packages?
Organizes code into logical structure
Improves code reusability and readability
Makes importing modules easier from nested folders
✅ Structure of a Package:
my_package/
│
├── __init__.py
├── [Link]
└── [Link]
✅ Example: Creating and Using a Package
✅ Step 1: Create Package Structure
my_package/
├── __init__.py
├── math_operations.py
✅ math_operations.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
✅ __init__.py
# Can be empty or used to initialize the package
✅ Step 2: Use the Package in Another Python File
✅ [Link]
from my_package import math_operations
print("Addition:", math_operations.add(10, 5))
print("Multiplication:", math_operations.multiply(4, 3))
✅ Output:
Addition: 15
Multiplication: 12
� Make sure the [Link] is in the same directory as the my_package folder or that the
package path is correctly added.
Let me know if you want help actually creating this on your computer or turning it into an
installable package (pip style)!