Module 3.3.1functions
Module 3.3.1functions
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 4
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 5
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 6
Modularization
Page 7
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 8
What is a Module?
Page 9
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 10
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 11
Python Functions
Page 12
Motivations for Modularization
Page 13
Function Declaration
Example
def greet():
print('Hello World!')
Page 14
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 15
Working of Python Function
Page 16
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 17
Function Parameters
► You can add as many arguments as you want, just separate them with a comma.
Page 18
Function Arguments
When a function is called, the values are transferred from calling function to called function. These values are
called arguments. There are four types of arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments:
Required arguments are the arguments passed to a function in correct positional order.
def printme( str ): "This prints a passed string"
print str;
return;
printme();
This would produce following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments:
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with
parameters.
Following example gives idea on default arguments, it would print default age if it is not passed:
When a function is called more number of arguments can be passed, For this operator “*”
is used. Multiple arguments are maintained by using tuples
def disp(x,*t):
print(len(t))
print(x,t)
n1=int(input(“Enter the number:”))
n2=int(input(“Enter the number:”))
disp(n1)
disp(n1,n2)
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 24
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 25
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 26
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 27
Exercises
► Write a function called celsius_to_fahrenheit that takes a temperature in
Celsius and converts it to Fahrenheit using the formula:
Page 28
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 29
Exercises
Page 30
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 31
Exercises
Page 32
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 33