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

Module 3.3.1

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

Module 3.3.1

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

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ALGORITHMIC THINKING WITH PYTHON

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

► 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 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?

► 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 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

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

► Some Benefits of Using Functions


► Increase Code Readability
► Increase Code Reusability

Page 14 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Function Declaration

► The syntax to declare a function is:

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!')

► 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 16 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 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.

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

# 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 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

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


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

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:

# 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 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"

# Call the function with 7


result = is_even_or_odd(7)

# Print the result


print(result) # Output: Odd

Page 25 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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):
integers less than or equal to 𝑛. result *= i
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 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.

# 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 27 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
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 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

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

You might also like