0% found this document useful (0 votes)
22 views

Module 3.3.1functions

Uploaded by

anndriyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Module 3.3.1functions

Uploaded by

anndriyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

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).

► DECOMPOSITION AND MODULARIZATION* :- Problem decomposition as a strategy for


solving complex problems, Modularization, Motivation for modularization, Defining and
using functions in Python, Functions with multiple return values

Page 3 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Problem decomposition

Page 4
What is Problem Decomposition?

► When solving a programming problem, problem decomposition is a critical strategy to


design efficient and maintainable solutions.
► It involves breaking down a larger programming task into smaller, self-contained modules or
functions that are easier to understand, code, test, and debug.

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?

► A module is a self-contained unit of code that can be:


► A function
► A class
► A package (in languages like Python)
► A library or a separate component in the system

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

► A function is a block of code that performs a specific task.

► Some Benefits of Using Functions


► Increase Code Readability
► Increase Code Reusability

Page 13
Function Declaration

► The syntax to declare a function is:

Example
def greet():
print('Hello World!')

Page 14
Function Call

def greet():
print('Hello World!')

► If we run the above code, we won't get an output.


► It's because creating a function doesn't mean we are executing the code inside it. It
means the code is there for us to use if we want to.
► To use this function, we need to call the function.

def greet():
print('Hello World!')
#output
# call the function Hello World!
greet() Outside function

print('Outside function')

Page 15
Working of Python Function

1. When the function greet() is called, the program's control


transfers to the function definition.
2. All the code inside the function is executed.
3. The control of the program jumps to the next statement
after the function call.

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.

def greet(name): ► Here, we passed 'John' as an argument to the greet()


print("Hello", name) function.
# pass argument ► We can pass different arguments in each call, making the
greet("John") function re-usable and dynamic.
► Let's call the function with a different argument.

greet("David")

Page 17
Function Parameters

► You can add as many arguments as you want, just separate them with a comma.

# function with two arguments


def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ", sum)

# function call with two values


add_numbers(5, 4)

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.

example Note, here order of the parameter does not matter:


def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
This would produce following result:
Name: miki Age 50
Can call a function with some/all of its arguments out of order as long
as you specify their names
>>> def foo(x,y,z): return(2*x,4*y,8*z)
>>> foo(2,3,4)
(4, 12, 32)
>>> foo(z=4, y=2, x=3)
(6, 8, 32)
>>> foo(-2, z=-4, y=-3)
(-4, -12, -32)
Can be combined with defaults, too
>>> def foo(x=1,y=2,z=3): return(2*x,4*y,8*z)
>>> foo()
(2, 8, 24)
>>> foo(z=100)
(2, 8, 800)
Default arguments:
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.

Following example gives idea on default arguments, it would print default age if it is not passed:

def printinfo( name, age = 35 ): “Test function"


print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
This would produce following result:
Name: miki Age 50
Name: miki Age 35
In Python function definition, first the required arguments should be
listed and then the default arguments should be listed
Variable length arguments

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

result = get_dimensions() width, height = get_dimensions()


print(result) # Output: (5, 10) print(width) # Output: 5
print(height) # Output: 10

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:

# Define the function


def celsius_to_fahrenheit(celsius):
# Convert Celsius to Fahrenheit
fahrenheit = (celsius * 9/5) + 32
return fahrenheit

# Call the function with 25 degrees Celsius


result = celsius_to_fahrenheit(25)

# Print the result


print(result) # Output: 77.0

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"

# Call the function with 7


result = is_even_or_odd(7)

# Print the result


print(result) # Output: Odd

Page 29
Exercises

# Define the function


def factorial(n):
► Write a function factorial that takes a non- # Initialize result as 1
negative integer as an argument and result = 1
returns its factorial. The factorial of a # Multiply all integers from 1 to n
number 𝑛 is the product of all positive for i in range(1, n + 1):
result *= i
integers less than or equal to 𝑛.
return result
► For example, the factorial of 5 is 5 * 4 * 3 *
2 * 1 = 120. # Call the function with 4
result = factorial(4)

# Print the result


print(result) # Output: 24

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.

# Define the function


def even_numbers_in_list(numbers):
# Use a list comprehension to filter even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
return even_numbers

# Call the function with the list [1, 2, 3, 4, 5, 6, 7, 8]


result = even_numbers_in_list([1, 2, 3, 4, 5, 6, 7, 8])

# Print the result


print(result) # Output: [2, 4, 6, 8]

Page 31
Exercises

# Define the function


def is_palindrome(word):
# Convert the word to lowercase to make the check
case-insensitive
word = word.lower()
# Check if the word is the same when reversed
► Write a function is_palindrome return word == word[::-1]
that checks if a given string is a
palindrome. A palindrome is a # Test the function with a case-insensitive palindrome
word that reads the same result1 = is_palindrome("MadAm")
forward and backward (e.g., result2 = is_palindrome("RaceCar")
"madam", "level") result3 = is_palindrome("Hello")

# Print the results


print(result1) # Output: True
print(result2) # Output: True
print(result3) # Output: False

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

# Test the function with length 5 and width 3


area, perimeter = calculate_area_and_perimeter(5, 3)

# Print the results


print(f"Area: {area}") # Output: Area: 15
print(f"Perimeter: {perimeter}") # Output: Perimeter: 16

Page 33

You might also like