Module 3 ATP
Module 3 ATP
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).
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 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.
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
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.
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.
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")
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.
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.
For variable-in-sequence :
statements
Eg:
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.
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.
Parameter Description
Eg:
x = range(3, 20, 2)
for n in x:
print(n)
There are four collection data types in the Python programming language:
List
List is used to collect items that usually consist of elements of multiple data types.
7
type(): To obtain the data type
print(type(list1))
Tuple
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Set
print(thisset)
print(thisset)
Dictionary
8
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
print(thisdict["brand"])
x = cars[0]
cars[0] = "Toyota"
Use the len() method to return the length of an array (the number of elements in an array).
x = len(cars)
for x in cars:
print(x)
cars.append("Honda")
cars.remove("Volvo")
9
NumPy
It also has functions for working in domain of linear algebra, fourier transform, and matrices.
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.
import numpy as np
print(arr)
print(arr[0])
Decomposition
Decomposition is a useful problem-solving strategy. It is breaking a problem down into smaller parts to
make it easier to solve.
One factory can be making the screens while another makes batteries and another makes the phone
case.
Modularization
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.
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.
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
Eg:
11
def my_function(x): #function definition, Parameter
return( 5 * x)
print(my_function(3)) #Argument
Arguments:
Arguments are specified after the function name, inside the parentheses.
A parameter is the variable listed inside the parentheses in the function definition.
sum_result = a + b
diff_result = a – b
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
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)
Recursion is one of the best solutions for task that can be defined with its similar subtask
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).
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.
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