Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Module 3

Uploaded by

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

Module 3

Uploaded by

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

MODULE 3

Syllabus

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
RECURSION:- Recursion Defined, Reasons for using Recursion, The Call Stack,
Recursion and the Stack, Avoiding Circularity in Recursion, Sample problems -
Finding the nth Fibonacci number, greatest common divisor of two positive integers,
the factorial of a positive integer, adding two positive integers, the sum of digits of a
positive number **.

CONTROL STRUCTURES IN PYTHON

● The code execution occurs sequentially in the same order in which they occur in the
program.
● Sometimes there is a need to implement logic to control the flow of execution based on
certain conditions or loop
● There are three types of control structures used in Python.
● They are:

1. Sequential

● Sequential statements are a set of statements whose execution process happens in a


sequence.
● Problem - if the logic has broken in any one of the lines, then the complete source code
execution will break.

2. Selection

● Also referred to as branching statements or decision control statements


● Their fundamental role is to make decisions.

3. Repetition
● This structure is used for looping
● Repeatedly executing a certain piece of a code block.

Selection and Iteration Using Python

● A program can test many conditions using selection statements


● Depending on whether the given condition is true or not, it can execute different code
blocks.

Conditional/ Selection Statements in Python

1. If Conditional Statement in Python

● The if statement is the most simple decision-making statement.


● It is used to decide whether whether a certain statement or block of statements will be
executed or not.

Syntax:

if condition:
#Statements to execute if condition is true

Flowchart:

Example:

if 10 > 5:
print("10 greater than 5")

Output

10 greater than 5

2. If-else Conditional Statements in Python


● If we went along with block of code when the conditions false, we can use the 'else'
statement with the 'if" statement in python.

Syntax of Python If-else:

if condition:

#Statements to execute if condition is true

else:
#Executes this block if condition is false

● If the condition evaluates to true, the indented block of code under the if statement is
executed.
● Otherwise, the indented block of code under the else statement is executed.

Flowchart
Example

Program to check whether a number is even or odd

3. Nested if..else Statements in Python

● The nested if statements in Python are the nesting of an if statement inside another if
statement with or without an else statement.
● There is an outer if statement, and inside it another if-else statement is present. These
type of statement is known as nested if statement.

Example
4. Elif Conditional Statements in Python

● A user can decide among multiple options.


● The if statements are executed from top to down.
● One of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed.
● If none of the conditions is true, then the final "else" statement will be executed.
● The elif keyword is python is way of saying "if the previous conditions were not true, then
try this condition".

Syntax
Example

Flowchart
5. Ternary Statement (Short Hand If Else Statement)

● Whenever there is only a single statement to be executed inside the if block then
shorthand if can be used.
● The statement can be put on the same line as the if statemem

Syntax

[option1] if [condition] else [option2]

The first option will be executed when the condition provided in the expression is True. If
the condition returns False, then option2 will be executed

Example:

a = 10
b=20
min = "a is minimum" if a < b else "b is minimum"
print(min)

Loops in Python
● In programming, loops are designed to execute a specified code block repeatedly.

1. While Loop in Python

● The python while statement is the simplest and the most basic iteration mechanism.
repeatedly executes a block of statements (usually indented) as long as the condition
evaluates to true.
● When the test condition becomes false, the control moves to the statement that follows
the while block.
● In case the test condition evaluates to false, to begin with, the body of the loop never run
and the while statement will be entirely skipped.

While Loop Syntax:

while expression:
Statement(s)

Flowchart:
2. For Loop in Python

● The for loops in Python are a special type of loop statement that is used for sequential
traversal.
● Python for loop is used for iterating over string, tuple, list, set, dictionary
● Python's for loop is designed to repeatedly execute a code block while iterating throup
list, tuple, dictionary, or other iterable objects of Python.

Syntax of the for Loop

for value in sequence:


code block

● In this case, the variable 'value' is used to hold the value of every item present in
sequence before the iteration begins until this particular iteration is completed.
Example

for Loop with Python range() element

● In Python, the range() function returns a sequence of numbers.


● For example,

values = range(4)

● Here, range(4) returns a sequence of 0, 1, 2, and 3.

For example,
Definition and Usage

● The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.

Syntax

range(start, stop, step)

● start:- Optional. An integer number specifying at which position to start. Default is 0


● stop:- Required. An integer number specifying at which position to stop (not included).
● step:- Optional. An integer number specifying the incrementing. Default is 1.

Example

Create a sequence of numbers from 3 to 19 but incremented by 2 instead of 1

Sequence Data Types in Python

1. Lists in Python

● List is a collection of things, enclosed in [] and separated by commas.


Example

List Characteristics

Lists are:

● Ordered-They maintain the order of elements.


● Mutable Items can be changed after creation.
● Allow duplicates They can contain duplicate values.

Access List Elements

● Each element in a list is associated with a number, known as a index.


● The index always starts from 0.
● The first element of a list is at index 0, the second element is index 1, and so on

Access elements using index


Add elements to python list

● Use append() method to add an element to end of python list

Change list items

● Change the items of a list by assigning new values using the = operator
Remove an item from the list

● Can remove an item from the list using remove() method

Python List length

● Can use the built in len() function to find the number of elements in a list
Iterating through a list

● Can use a for loop to iterate through the elements of a list

Python List methods


Sort List alphanumerically

● Sort() method will sort the list alphanumerically

DECOMPOSITION AND
MODULARISATION

Problem Decomposition as a Strategy for solving Complex Problems


● In a multiprocessing computer system, a single problem or program must be divided into
subproblems to assign them to different processors.
● This task is accomplished using a Ina technique called problem decomposition
● It is the process of decomposing a problem/program into multiple
subproblems/subprograms
● It is the basic building block of Parallel Computing.
● Decomposition is necessary because a problem needs to be broken down into different
tasks that can then be assigned to various processors.

Parallel Processing: In a multiprocessing system. subproblems that can be processed


simultaneously by multiple computational efficiency and significantly reduces execution time.

Modularity: Decomposition promotes modularity, where each subproblem can be developed,


tested, and debugged independently.

Task Assignment: By breaking a problem into smaller tasks, it becomes easier to assign specific
tasks to different processors or team members.

Scalability: Decomposition allows for the scalable design of systems

Simplification: Tackling smaller subproblems simplifies the development proces subproblem can
be solved more easily than addressing the entire problem at once

Modularisation

● Modularisation is the process of separating the functionality of a program into


independent, interchangeable modules, such that each contains everything necessary to
execute only one aspect of the desired functionality.
Motivation for modularisation

1. Ease of debugging
2. Reusable Code
3. Readability
4. Reliability

All these advantages add up to one big advantage: reliability. Code that is easier to read, easier
to debug, easier to maintain and easier to share will always run smoother with less errors. This
becomes necessary when working on extremely large projects, with hundreds of developers, all
of which have to either share code or work on code

Advantages of modularisation in Programming

1. Manageability
2. Team Programming
3. Quality Modularisation
4. Code is easier to text
5. Code is easier to test
6. Reusability
7. Easy collaboration

Disadvantages of modular programming

● It is a challenging task to combine all the modules. There is a need for extra time and
budget for a product in modular programming.
● Careful documentation is required so that other program modules are not affected.
● Some modules may partly repeat the task performed by other modules. Hence, Modular
programs need more memory space and extra time for execution
● Integrating various modules into a single program may not be a task because different
people working on the design of different modules may not have the same style.
● It reduces the program's efficiency because testing and debugging are time-consuming,
where each function contains a thousand lines of code.
Functions in Python

Defining and Using Functions in Python

● Functions in programming is a block of code that encapsulates a specific task or related


group of tasks.
● Functions are defined by a name, may have parameters and may return a value.
● The main idea behind functions is to take a large program, break it into smaller

Function Declaration and Definition

● A function declaration tells the compiler about a function's name, return type, and
parameters.
● It also tells the compiler that there is a function with the given name defined somewhere
else in the program.
● The function definition contains a function declaration and the body of a function.
● The body is a block of statements that perform the work of the function.

Calling Function in Programming

● Once a function is declared, it can be used or "called" by its name.


● When a function is called, the control of the program jumps to that function, which then
executes its code.
● Once the function finishes executing, the control returns to the part of the program that
called the function, and the program continues running from there

Types of Functions in Python

1. Built-in Functions These functions are pre-defined in Python and can be used directly
without any further declaration.

Example

#Using the built-in len() function

mylist[1, 2, 3, 4, 5]
print(len(mylist))

Output: 5

2. User-defined Functions - These are functions that users create to perform specific tasks.
● We can define a function in Python, using the def keyword
Example
def greet ():
print('Hello World!')

3. Recursive Functions - These are functions that call themselves within their definition.
They help solve problem that can be broken down into smaller, similar problems.

Recursion Defined

● Recursion can be defined as the process in which a function calls itself repeatedly.
● Using a recursive algorithm, certain problems can be solved quite easily.
● Examples of such Recursion
● Towers of Hanoi (TOH),
● Inorder/Preorder/Postorder Tree Traversals
● DFS of Graph

Advantages of using Recursion

● A complicated function can be split down into smaller sub-problems utilizing recursion.
● Sequence creation is simpler through recursion than utilizing any nested iteration.

Disadvantages of using Recursion

● A lot of memory and time is taken through recursive calls which makes it expensive for
use..Recursive functions are challenging to debug.
● The reasoning behind recursion can sometimes be tough to think through.

Syntax:

def func():
(recursive call)
func()

Example
Reasons for using Recursion

● Learning recursion makes you a better programmer


● Using recursion make the code clearer
● Readability
● Recursion is data structure best friend

The Call Stack

● A call stack is a data structure used by computer programs to keep track of function
calls.
● When a function is called, a new frame is added to the call stack.
● This frame contains information about the function call, such as the function arguments
and the current position in the code
● When the function completes its execution, the frame is removed from the call stack, and
the program returns to the previous frame.
● The call stack operates in a Last-In-First-Out (LIFO) manner, which means that the last
function called is the first to be completed.

Overhead of Recursion
● Memory overhead
● Function call overhead
● Performance
● Readability and Maintainability
● Difficulty to debugging and understanding.

You might also like