Professional Documents
Culture Documents
School of Computing
Structured Programming
Presented
By
D.Deva Hema
Structured Programming Paradigm
Unit-I (15 Session)
Session 1-5 cover the following topics:-
• By the end of the 20th century, concepts of structured programming were widely
applied so programming languages that originally lacked structure now have it
(FORTRAN, COBOL and BASIC). Now, it is possible to do structured programming in
any programming language (Java, C++, Python ...).
2. Overview
Structured programming was defined as a method used to minimize complexity that uses:
Ex:-
• Structograms use the following diagrams:
1.process blocks - Process blocks represent the simplest actions and don’t require analysis.
Actions are performed block by block.
2.branching blocks
Branching blocks are of two types – True/False or Yes/No block and multiple branching
block.
3.Testing loops
Testing loops allow the program to repeat one or many processes until a condition is
fulfilled. There are two types of testing loops – test first and test last blocks – and the
order in which the steps are performed is what makes them different.
Advantages of structured programming are:
Recursion:
Recursion"; a statement is executed by repeatedly calling itself until termination conditions
are met. While similar in practice to iterative loops, recursive loops may be more
computationally efficient, and are implemented differently as a cascading stack.
Graphical representation of the three basic patterns — sequence, selection, and repetition
Control Structure - DECISION MAKING (PYTHON )
• Decision making statements in programming languages decides the direction of flow of program
execution. Decision making statements available in python are:
if statement :
It is used to decide whether a certain statement or block of statements will be executed or not i.e
if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Example :
i = 10
if (i > 15):
print ("10 is less than 15")
print ("I am Not in if"
• if..else statements:
We can use the else statement with if statement to execute a block of code when the condition is
false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Example :
i = 20;
if (i < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
• nested if statements
Python allows us to nest if statements within if statements. i.e, we can place an if statement
inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example : Nested if else
i = 10
if (i == 10):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
if-elif-else ladder
• Here, a user can decide among multiple options. The if statements are executed from
the top down. As soon as 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 Syntax:-
Syntax:-
if (condition):
statement
elif (condition):
statement
else:
• statement the final else statement will be executed.
example
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
CONDITION SYNTAX
SIMPLE IF if test expression:
statement(s)
• High level languages such as COBOL, FORTRAN and C, is commonly known as procedure oriented programming(POP). In the
procedure oriented programming, program is divided into sub programs or modules and then assembled to form a complete
program. These modules are called functions.
• The problem is viewed as a sequence of things to be done.
• The primary focus is on functions.
• Procedure-oriented programming basically consists of writing a list of instructions for the computer to follow and organizing
these instructions into groups known as functions.
• In a multi-function program, many important data items are placed as global so that they may be accessed by all functions.
Each function may have its own local data. If a function made any changes to global data, these changes will reflect in other
functions. Global data are more unsafe to an accidental change by a function. In a large program it is very difficult to identify
what data is used by which function.
• This approach does not model real world problems. This is because functions are action-oriented and do not really correspond
to the elements of the problem.
Typical structure of procedure-oriented program
• Procedural programming is a programming paradigm, derived from structured programming, based on the concept of
the procedure call. Procedures, also known as routines, subroutines, or functions, simply contain a series of computational
steps to be carried out. Any given procedure might be called at any point during a program's execution, including by other
procedures or itself.
• procedural languages generally use reserved words that act on blocks, such as if, while, and for, to implement control flow,
whereas non-structured imperative languages use goto statements and branch tables for the same purpose.
Note:
• Subroutine:-
• Subroutines; callable units such as procedures, functions, methods, or subprograms are used to allow a sequence to be
referred to by a single statement.
Functions in Python
• A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better
modularity for your application and a high degree of code reusing.
• There are 2 types of function
• Built-in function ex. Print()
• User defined function -User can create their own functions.
Defining a Function
• Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these
parentheses.
• The first statement of a function can be an optional statement - the documentation string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with
no arguments is the same as return None.
• You can call a function by using the following types of formal arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Function Arguments
We want to make some of its parameters as optional and use default values if the user does not want to provide values for such
parameters.
Example:
say('Hello')
say('World', 5)
Example:
def my_sum(*args):
return sum(args)
print(my_sum(1, 2, 3, 4)) # 10
print(my_sum(1, 2, 3, 4, 5, 6, 7, 8)) # 36
Keyword Arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first ='WELCOME', mid ='TO', last='SRM')
Anonymous function
Usually in any programming function declaration should have a valid identifier as name to be invoked, but python supports user
defined function to be defined without any name. Such function are called as anonymous function or lambda function.
Syntax:
lambda arguments: expression
Example:
double = lambda x: x * 2
print(double(5))
Lambda functions are used along with built-in functions like filter(), map() etc
Object Oriented
Programming Paradigm
Introduction
• OOP treat data as a critical element in the program development and does not allow it to flow freely around the system.
• It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside
functions.
• OOP allows decomposition of a problem into a number of entities called objects and then build data functions around these
objects.
• The data of an object can be accessed only by the functions associated with that object.
• Functions of one object can access the functions of another objects Objec Obje
tA ct B
Data Data
Functio Communic Functio
ns ation ns
Obje
ct C
Data
Functio
ns
Characteristics
• Objects
• Classes
• Data Abstraction and Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
Classes in Python
• Defining a class is simple, all you have to do is use the keyword class followed by the name that you want to give your class,
and then a colon symbol :. It is standard approach to start the name of class with a capital letter and then follow the camel
case style.
• The class definition is included, starting from the next line and it should be indented, as shown in the code below. Also, a class
can have variables and member functions in it.
• The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python.
Example
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
Classes in Python
Classes
Note:
• We add the self parameter when we define a member function, but do not specify it while calling the function.
• When we called get_destination function for objFirst it gave output as Destination is: mars, because we updated the value for
the variable destination for the object objFirst
• To access a member function or a member variable using an object, we use a dot . symbol.
• And to create an object of any class, we have to call the function with same name as of the class.
Constructor and Destructor
Note:
Like Destructor is counter-part of a Constructor, function __del__ is the counter-part of function __new__. Because __new__ is
the function which creates the object.
__del__ method is called for any object when the reference count for that object becomes zero.
As reference counting is performed, hence it is not necessary that for an object __del__ method will be called if it goes out of
scope. The destructor method will only be called when the reference count becomes zero.
The __init__() Function
• All classes have a function called __init__(), which is always executed when the class is
being initiated.
• Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Object Methods
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Function Overloading
• In OOP, it is possible to make a function act differently using function overloading. All we have to do is, create different
functions with same name having different parameters. For example, consider a function add(), which adds all its parameters
and returns the result. In python we will define it as,
• Python doesn't support method overloading on the basis of different number of parameters in functions.
Function Overloading
def add(a,b):
return a+b
def add(a,b,c):
return a+b+c
print add(4,5)
• If you try to run the above piece of code, you get an error stating, “TypeError: add() takes exactly 3 arguments (2 given)”. This
is because, Python understands the latest definition of method add() which takes only two arguments. Even though a method
add() that takes care of three arguments exists, it didn’t get called. Hence you would be safe to say, overloading methods in
Python is not supported.
Inheritance
Method overriding
Method overriding is a concept of object oriented programming that allows us to change the implementation of a function in the
child class that is defined in the parent class. It is the ability of a child class to change the implementation of any method which is
already provided by one of its parent class(ancestors).