[go: up one dir, main page]

0% found this document useful (0 votes)
2 views13 pages

Module 3 ATP

The document covers key programming concepts in Python, including control structures like selection (if-else, elif) and iteration (for and while loops), as well as data types such as lists, tuples, sets, and dictionaries. It also discusses problem decomposition, modularization, and the use of functions, including recursion and its applications. Additionally, it introduces the NumPy library for array manipulation and highlights the importance of modular code for improved readability and maintenance.

Uploaded by

Reji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Module 3 ATP

The document covers key programming concepts in Python, including control structures like selection (if-else, elif) and iteration (for and while loops), as well as data types such as lists, tuples, sets, and dictionaries. It also discusses problem decomposition, modularization, and the use of functions, including recursion and its applications. Additionally, it introduces the NumPy library for array manipulation and highlights the importance of modular code for improved readability and maintenance.

Uploaded by

Reji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Module 3(11)

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: SELECTION AND ITERATION

Control Structures can be considered as the building blocks of computer programs. They are commands
that enable a program to “take decisions”, following one path or another.

The basic Control Structures in programming languages are:

1
• Selection (Conditionals): which are used to execute one or more statements if a condition is met.

• Iteration (Loops): which purpose is to repeat a statement a certain number of times or while a
condition is fulfilled.

Logical conditions

 Equals: a == b

 Not Equals: a != b

 Less than: a < b

 Less than or equal to: a <= b

 Greater than: a > b

 Greater than or equal to: a >= b

Conditional statements

1)if statement

If statements execute one or more statements when a condition is met. If the testing of that condition
is TRUE, the statement gets executed. But if it is FALSE (the condition is not met), then nothing happens.

The syntax of the If statements is:

If condition:

statements

2
Eg:

a = 33
b = 200
if b > a:
print("b is greater than a")

2)else statement

This Control Structure allows a program to follow alternative paths of execution, whether a condition is
met or not.

The syntax of “If-Else statements” is:

If condition:

Statements

else:

Statements

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than or equal to b")

3
3)elif statement

The elif keyword tells if the previous conditions were not true, then try this condition.

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

Iteration (Loop) statements

Iteration repeat a sequence of steps based on condition.

Two types of “Looping techniques”:

1. For Loops: Execute the prescribed steps a number of times, as controlled by a counter or an index.

2. While Loops: Based on the onset and verification of a logical condition. The condition is tested at the
start .

1) while Loop:

In While Loops a condition is first evaluated, and if the result of testing that condition is TRUE, one or
more statements are repeatedly executed until that condition becomes FALSE.

The syntax of “While Loops” is:

while condition:

statement

4
i=1
while i < 6:
print(i)
i=I+1

With the break statement we can stop the loop even if the while condition is true:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

The continue statement stop the current iteration, and continue with the next

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

2) for loop

5
In this Control Structure, statements are executed one after another in a consecutive order over a
sequence of values that gets evaluated only when the For Loop is initiated (never reevaluated). In this
case, the number of iterations is fixed and known in advance.

The syntax of For Loops is:

For variable-in-sequence :

statements

Eg:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

for loops cannot be empty, but if for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.

for x in [0, 1, 2]:


pass

3)range() function

6
The range() function returns a sequence of numbers, starting from the start index, and increments by
the step index, and stops before a specified number.

range(start, stop, step)

Parameter Description

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 .

step Optional. An integer number specifying the increment. Default is 1

Eg:

x = range(3, 20, 2)
for n in x:
print(n)

Sequence data types(Collection data types)

There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.

 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

 Set is a collection which is unordered, unchangeable, and unindexed. No duplicate members.

 Dictionary is a collection which is ordered and changeable. No duplicate members.

List

List is used to collect items that usually consist of elements of multiple data types.

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

list4 = ["abc", 34, True, 40, "male"]

7
type(): To obtain the data type

print(type(list1))

Tuple

Tuples are used to store multiple items in a single variable.

A tuple is a collection which is ordered and immutable.

Tuples are written with round brackets.

thistuple = ("apple", "banana", "cherry")


print(thistuple)

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Set

Sets are used to store multiple items in a single variable.

A set is a collection which is unordered, unchangeable, and unindexed.

Sets are written with curly brackets.

Sets cannot have two items with the same value.

Set items can be of any data type:

set1 = {"abc", 34, True, 40, "male"}

thisset = {"apple", "banana", "cherry"}


print(thisset)

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)

Dictionary

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered, changeable and do not allow duplicates.

8
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

The values in dictionary items can be of any data type:

Dictionaries are written with curly brackets, and have keys and values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

print(thisdict["brand"])

Creating and using Arrays in Python

Arrays are used to store multiple values in one single variable:

cars = ["Ford", "Volvo", "BMW"]

You refer to an array element by referring to the index number.

x = cars[0]

Modify the value of the first array item:

cars[0] = "Toyota"

Use the len() method to return the length of an array (the number of elements in an array).

x = len(cars)

Looping Array Elements

for x in cars:
print(x)

Use the append() method to add an element to an array.

cars.append("Honda")

use the remove() method to remove an element from the array.

cars.remove("Volvo")

reverse(): Reverses the order of the array

sort():sorts the array

9
NumPy

Python library used for working with arrays.

It also has functions for working in domain of linear algebra, fourier transform, and matrices.

NumPy was created in 2005 by Travis Oliphant.

NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.( 0, 1, 2, 3
dimensional array)

The array object in NumPy is called ndarray, it provides a lot of supporting functions that make working
with ndarray very easy.

pip install numpy

import numpy as np

arr = numpy.array([1, 2, 3, 4, 5])

print(arr)

print(arr[0])

DECOMPOSITION AND MODULARISATION - Problem decomposition as a strategy for solving complex


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

Decomposition

Decomposition is a useful problem-solving strategy. It is breaking a problem down into smaller parts to
make it easier to solve.

Eg: mobile phone.

One factory can be making the screens while another makes batteries and another makes the phone
case.

Modularization

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.

Motivations for Decomposition:

10
1) Ease of Debugging: If a program is designed with modularity, and if there is a problem
in a particular function, the programmer knows where to look and can manage a smaller
portion of code.
2) Reusable Code: Modular code allows programmers to easily reuse code
3) Readability: Modular code is code that is highly organized. Other programmers working
on the code can follow the code as well. This optimizes code for use among multiple
developers with less trouble.
4) Reliability: Code that is easier to read, easier to debug, easier to maintain and easier to
share will always run smoother with less errors. Modularization of code is necessary to
create complex software reliably.
5) Parallel Development: Different team members can work on different components
simultaneously.

Basic Concept of Modularization:

 Program Control Function: Modules that manage the flow of control in a program, such as main
routines or decision-making components.

 Specific Task Function: Modules that perform specific tasks or calculations, such as utility
functions or algorithms.

Advantages of Modularization in Programming:

1. Improved Readability: Code is easier to read and understand when organized into modules.

2. Easier Maintenance: Bugs are easier to find and fix in smaller, well-defined modules.

3. Enhanced Testing: Modules can be tested independently, improving the reliability of the
system.

4. Faster Development: Developers can work on different modules concurrently, speeding up the
development process.

Function in Python

A function is a block of code which only runs when it is called.

One can pass data, known as parameters, into a function.

A function can return data as a result.

In Python a function is defined using the def keyword:

Eg:

11
def my_function(x): #function definition, Parameter
return( 5 * x)
print(my_function(3)) #Argument

Arguments:

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses.

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.

A function must be called with the correct number of arguments.

Functions with Multiple Return Values:

Python functions can return multiple values using tuples.

def calculate(a, b):

sum_result = a + b

diff_result = a – b

return sum_result, diff_result

sum_result, diff_result = calculate(10, 5)

print("Sum:", sum_result) # Output: Sum: 15

print("Difference:", diff_result) # Output: Difference: 5

By organizing related functions into modules (Python files), one can improve code organization and
reusability.

3c) 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 **.

RECURSION

Recursion is a powerful implementation technique in which a function calls itself.

Every recursive function must have at least two cases: the recursive case and the base case.

12
Example, for the factorial function, !, the recursive case is n! = n*(n - 1)! and the base case is n = 1
when n = = 0 or n = = 1.( a linear recursion)

Reasons for using Recursion:

Reduce the length of the code

Make the program easier to read and write

Recursion is one of the best solutions for task that can be defined with its similar subtask

Example; The Factorial of a number.

The Call Stack

When a function is called, a certain amount of memory is set aside for that function to use for purposes
such as storing local variables. This memory, called a frame, is also used by the computer to store
information about the function such as the function's address in memory; this allows the program to
return to the proper place after a function call.

Every function has its own frame that is created when the function is called. These frames are stored on
the call stack, an area of memory devoted to holding information about currently running functions.

A stack is a Last In First Out (LIFO) data structure, meaning that the last item to enter the stack is the
first item to leave.

In the call stack, the frames are put on top of each other in the stack. Adhering to the LIFO principle, the
last function to be called (the most recent one) is at the top of the stack while the first function to be
called (which should be the main() function) resides at the bottom of the stack. When a new function is
called, that new function's frame is pushed onto the stack and becomes the active frame. When a
function finishes, its frame is destroyed and removed from the stack, returning control to the frame just
below it on the stack (the new top frame).

Recursion and the Call Stack

When using recursive techniques, functions "call themselves". Every function called gets its own frame,
with its own local variables, its own address, etc. As far as the computer is concerned, a recursive call is
just like any other call.

Avoiding Circularity in Recursion

A crucial problem to avoid when writing recursive functions is circularity. Circularity occurs when a point
is reached in recursion where the arguments to the function are the same as with a previous function
call in the stack. If this happens, the base case will never be reached and the recursion will continue
forever, or until the computer runs out of memory and crashes, whichever comes first.

13

You might also like