Module 3.3.1
Module 3.3.1
Prof. Sarju S
21 November 2024
Module 3
Page 2
Module 3
► SELECTION AND ITERATION USING PYTHON:- if-else, elif, for loop, range, while loop.
► SEQUENCE DATA TYPES IN PYTHON - list, tuple, set, strings, dictionary, Creating and
using Arrays in Python (using Numpy library).
Page 3 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Problem decomposition
Page 4
What is Problem Decomposition?
Page 5 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Why Decompose Programming Problems?
► Improves Clarity: Understanding a smaller task is simpler than grasping the entire program
at once.
► Facilitates Reusability: Decomposed solutions often result in reusable code components
(e.g., functions or classes).
► Enhances Debugging: Smaller parts are easier to test and debug, allowing you to isolate
errors.
► Encourages Collaboration: Different team members can work on separate components
simultaneously.
► Promotes Maintainability: Modular code is easier to update or expand without affecting
other parts.
Page 6 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Best Practices for Decomposition in Programming
► Keep Functions Small: Each function should perform one specific task.
► Use Meaningful Names: Names should describe what the function or variable does, e.g.,
calculate_total.
► Test Incrementally: Write and test each component independently before combining
them.
► Document Your Code: Add comments explaining the purpose of each function or module.
► Think Recursively (if Applicable): For some problems, like tree traversal or factorial
calculation, decomposing using recursion is effective.
Page 7 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Modularization
Page 8
Modularization: An Overview
► Modularization is the process of breaking a large program or system into smaller, self-
contained, and reusable modules.
► Each module performs a specific function or handles a distinct aspect of the program.
► These modules work together to achieve the overall goal of the software while remaining
independent from one another.
Page 9 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
What is a Module?
Page 10 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Motivations for Modularization
► Improved Readability
► Modularization makes Python programs easier to read and navigate.
► Large projects are broken into smaller, logically separated files or functions.
► Example: Instead of one large file for a project, you have user.py, database.py, and utils.py.
► Easier Maintenance
► When updating or debugging, modularization allows you to focus on a specific part of the code
without affecting others.
► Example: A bug in the email_sender module doesn’t require digging into other unrelated parts of
the application.
► Code Reusability
► Code written in one module can be reused in multiple parts of the project or in entirely different
projects.
► Example: A function in math_utils.py for calculating the factorial can be reused wherever needed:
Page 11 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Motivations for Modularization
► Supports Collaboration
► Modularization enables team members to work on separate modules simultaneously.
► Example: One developer can work on the authentication.py module, while another works on
payment_processing.py.
► Encourages Testing
► Modularized code allows for unit testing of individual components in isolation.
► Example: Test the login() function in the auth.py module independently of the rest of the
program.
► Facilitates Scalability
► New features can be added by creating new modules without altering existing functionality.
► Example: Adding a report_generator.py module to a payroll system.
Page 12 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Python Functions
Page 13
Motivations for Modularization
Page 14 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Function Declaration
Example
def greet():
print('Hello World!')
Page 15 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Function Call
def greet():
print('Hello World!')
def greet():
print('Hello World!')
#output
# call the function Hello World!
greet() Outside function
print('Outside function')
Page 16 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Working of Python Function
Page 17 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Function Parameters
► Sometimes functions require input to provide data for their code. This input is defined
using parameters.
► Arguments are specified after the function name, inside the parentheses.
► You can add as many arguments as you want, just separate them with a comma.
greet("David")
Page 18 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Function Parameters
► You can add as many arguments as you want, just separate them with a comma.
Page 19 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Return Statement
► In Python, the return statement is used inside a function to send a result back to the
caller.
► It allows a function to produce a value that can be used later in the program.
► Without the return statement, a function doesn't return anything by default, and the
value returned is None.
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:', square)
Note: The return statement also denotes that the function has ended. Any code after return is not executed.
Page 20 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Returning Multiple Values
► Returning Multiple Values as a Tuple (Most Common Method)
► The simplest and most common way to return multiple values from a function is by using a
tuple.
► Python automatically creates a tuple when you return more than one value separated by
commas.
Explanation: When you return multiple values like
def get_dimensions(): width, height, Python packs them into a tuple (5, 10)
width = 5 behind the scenes.
height = 10
# Returning a tuple implicitly Accessing Values: You can unpack the tuple later when
return width, height you call the function
Page 21 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Returning Multiple Values
► Returning Multiple Values as a List
► A function can return a list to hold multiple values. Lists are mutable, meaning you can
modify them after they are returned.
def get_fruits():
fruits = ['apple', 'banana', 'cherry']
# Returning a list
return fruits
result = get_fruits()
print(result)
# Output: ['apple', 'banana', 'cherry']
Page 22 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Returning Multiple Values
► Returning Multiple Values as a Dictionary
► A dictionary can be used to return multiple values, especially when the data has a meaningful
key-value structure.
► This is particularly useful when you want to return named values (e.g., "name" and "age").
def get_person_info():
info = {
'name': 'Alice',
'age': 30,
'is_student': False
}
return info # Returning a dictionary
result = get_person_info()
print(result)
# Output: {'name': 'Alice', 'age': 30, 'is_student': False}
Page 23 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Exercises
► Write a function called celsius_to_fahrenheit that takes a temperature in
Celsius and converts it to Fahrenheit using the formula:
Page 24 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Exercises
► Write a function is_even_or_odd that takes an integer and returns whether
the number is even or odd.
► The function should return "Even" if the number is even and "Odd" if the
number is odd.
# Define the function
def is_even_or_odd(number):
# Check if the number is even or odd
if number % 2 == 0:
return "Even"
else:
return "Odd"
Page 25 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Exercises
Page 26 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Exercises
► Write a function even_numbers_in_list that takes a list of integers and returns a new list
containing only the even numbers.
Page 27 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Exercises
Page 28 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Exercises
► Write a function called calculate_area_and_perimeter that takes the length and width
of a rectangle as input, and returns both the area and the perimeter of the rectangle.
# Define the function
def calculate_area_and_perimeter(length, width):
# Calculate area
area = length * width
# Calculate perimeter
perimeter = 2 * (length + width)
# Return both area and perimeter as a tuple
return area, perimeter
Page 29 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Thank You
Prof. Sarju S
Department of Computer Science and Engineering
St. Joseph’s College of Engineering and Technology, Palai (Autonomous)
[email protected]
Page 30 Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the respective content creators.
Document is compiled exclusively for study purpose and shall not be used for commercial purpose.