Assignment -02
Programming In Python
(PGCA 1951)
Submitted To: Submitted By:
Prof. Navjot Singh Mohit Sharma
Assistant Professor MCA 1ST SEM
Department of Computer Applications
PUNJAB INSTITUTE OF MANAGEMENT AND
TECHNOLOGY
(AFFILIATED TO IKG PUNJAB TECHNICAL UNIVERSITY, JALANDHAR)
1. What is meant by function in python language? What is their need and
advantages?
A function in Python is a block of reusable code that performs a specific task. It allows
programmers to break a large program into smaller, manageable, and reusable pieces of code.
Functions make the program more organized, modular, and easy to understand.
A function is defined using the keyword def followed by the function name and parentheses
containing parameters (if any).
Syntax of a Function:
def function_name(parameters):
# body of the function
statement(s)
return value
Example:
def add_numbers(a, b):
sum = a + b
return sum
result = add_numbers(10, 20)
print("Sum is:", result)
In this example, add_numbers() is a user-defined function that takes two parameters, adds them,
and returns the result.
Advantages of Functions
1. Reusability: Functions can be used several times without rewriting the code.
2. Simplicity: Breaking complex problems into smaller parts makes programming simpler.
3. Maintainability: Functions make it easier to modify code in one place.
4. Better collaboration: In team projects, different members can work on different functions.
5. Abstraction: The user can use a function without understanding its internal details.
Example: Function with Parameters and Return Value:
def multiply(x, y):
result = x * y
return result
Conclusion
Functions are one of the most important features of Python programming. They make programs
more structured, maintainable, and efficient. By defining reusable blocks of code, we reduce
redundancy and improve clarity. Hence, functions are the foundation of modular programming in
Python.
2. What do you understand by recursion? What are its advantages and
disadvantages?
Recursion in Python is a programming technique where a function calls itself directly or
indirectly to solve a problem.
Each recursive call reduces the problem into smaller subproblems until it reaches a base
condition that stops further recursion.
Syntax:
def recursive_function(parameters):
if base_condition:
return result
else:
return recursive_function(modified_parameters)
Example 1: Factorial of a Number using Recursion
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print("Factorial of 5 is:", factorial(5))
Explanation:
• When factorial(5) is called, it calls factorial(4), factorial(3) and so on.
• Finally, when n==1, recursion stops and returns the result.
Example 2: Fibonacci Series using Recursion
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
for i in range(8):
print(fibonacci(i), end=" ")
Output:
0 1 1 2 3 5 8 13
Working of Recursion
When a function calls itself, the current function execution is paused and stored in a call stack.
When the base case is reached, the functions start returning in reverse order, solving the problem
step by step.
Advantages of Recursion
1. Simplifies complex problems: Problems like tree traversal, factorial, Fibonacci, and
searching can be written elegantly.
2. Reduces code size: Fewer lines of code compared to loops.
3. Natural representation: Recursive code is close to mathematical definitions.
4. Useful in data structures: Essential in algorithms involving trees, graphs, and linked lists.
Disadvantages of Recursion
1. High memory usage: Each function call adds a new frame to the call stack.
2. Slower execution: Recursive calls take time due to repeated function invocation.
3. Risk of stack overflow: If base condition is not defined properly, it leads to infinite
recursion.
4. Difficult debugging: Tracing recursive calls can be complex for beginners.
Conclusion:
Recursion is a powerful concept in Python that simplifies complex problems but must be used
wisely. Though it provides clarity and elegance, excessive recursion can lead to inefficiency and
memory issues. It is important to ensure a proper base condition to avoid infinite recursion.
3. How for loop is used to access list, tuple, set, string, and dictionary in
Python? Elaborate with a programming example.
A for loop in Python is used to iterate over a sequence of elements such as lists, tuples, sets,
strings, and dictionaries. It executes a block of code multiple times, once for each element in the
sequence.
Syntax:
for variable in sequence:
# block of code
1. For Loop with List
A list is an ordered collection of elements that can be accessed one by one using a for loop.
eg. fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
2. For Loop with Tuple
Tuples are similar to lists but are immutable.
numbers = (10, 20, 30, 40)
for num in numbers:
print(num)
3. For Loop with Set
A set is an unordered collection, so elements may appear in any order.
colors = {"red", "green", "blue"}
for color in colors:
print(color)
4. For Loop with String
Strings are sequences of characters, so we can iterate through each character.
word = "Python"
for letter in word:
print(letter)
5. For Loop with Dictionary
A dictionary stores data in key-value pairs. We can loop through keys, values, or both.
student = {"name": "Amit", "age": 21, "course": "BCA"}
print("Keys:")
for key in student:
print(key)
print("\nValues:")
for value in [Link]():
print(value)
print("\nKey-Value Pairs:")
for key, value in [Link]():
print(key, ":", value)
Using Range() in For Loop
for i in range(1, 6):
print(i)
Output:
12345
Using Enumerate() in For Loop
The enumerate() function provides both index and value.
fruits = ["apple", "banana", "mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Conclusion:
The for loop in Python is versatile and can iterate through any iterable object. It simplifies
accessing and processing data from different data structures like lists, tuples, sets, strings, and
dictionaries.
4. Describe decision-making control statements of Python with example of
each.
Decision-making statements allow a program to make decisions based on certain conditions.
Python uses if, if-else, if-elif-else, and nested if statements to control program flow.
1. if Statement
The if statement checks a condition and executes a block of code if the condition is true.
age = 20
if age >= 18:
print("You are eligible to vote.")
2. if-else Statement
Used when there are two possible outcomes — one when the condition is true, another when
false.
marks = 40
if marks >= 50:
print("You passed!")
else:
print("You failed!")
3. if-elif-else Ladder
Used when there are multiple conditions to check.
num = 0
if num > 0:
print("Positive number")
elif num < 0:
print("Negative number")
else:
print("Number is zero")
4. Nested if Statement
One if statement inside another is known as nested if.
age = 25
citizenship = "Indian"
if age >= 18:
if citizenship == "Indian":
print("Eligible for voting")
else:
print("Not an Indian citizen")
else:
print("Underage")
Example: Largest of Three Numbers
a = 10
b = 20
c = 15
if a > b and a > c:
print("A is largest")
elif b > c:
print("B is largest")
else:
print("C is largest")
Real-Life Example: Grading System
marks = 85
if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
Conclusion:
Decision-making statements are the backbone of logical programming. They allow Python
programs to react differently based on conditions. Using if, if-else, and if-elif constructs,
developers can implement dynamic and intelligent behavior in their programs.