app unit 1
app unit 1
School of Computing
Structured Programming
Programming Paradigm: An introduction
• A programming language is an artificial language designed to communicate instructions to a machine, e.g., computer
• The earliest programming languages preceded the invention of the computer e.g., used to direct the behavior of machines such
as Jacquard looms and player pianos.
• “Programming languages are the least usable, but most powerful human-computer interfaces ever invented”
• Low-level programming languages provide little or no abstraction, e.g., machine code and assembly language
• Difficult to use
• High-level programming languages isolate the execution semantics of a computer architecture from the specification of the
program
Programming Paradigm: An introduction
Programming Paradigm: An introduction
• Programming languages can be categorized into programming paradigms
• “Paradigms emerge as the result of social processes in which people develop ideas and create principles and practices that
embody those ideas”
• Programming paradigms are the result of people’s ideas about how computer programs should be constructed
• Once you have understood the general concepts of programming paradigms, it becomes easier to learn new programming
languages
Structured Programming Paradigm
Unit-I (15 Session)
Session 1-5 cover the following topics:-
by using subroutines, block structures and loops (for and while) and discouraging the use of goto
statement.
Structured programming offers ability to control a program and allow different set of codes runs for
different occasions
Structured Programming
Bohm-Jacopini
The Böhm-Jacopini theorem, also called structured program theorem, stated that working out a function is
possible by combining subprograms in only three manners:
• Executing one of two subprograms according to the value of a Boolean expression (selection) .
Some of the languages that initially used structured approach are ALGOL, Pascal, PL/I and Ada.
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:
Top-down analysis includes solving the problem and providing instructions for every step.
When developing a solution is complicated, the right approach is to divide a large problem
into several smaller problems and tasks.
Structured coding relates to division of modules into set of instructions organized within control
structures. A control structure defines the order in which a set of instructions are executed. The
statements within a specific control structure are executed:
• sequentially – denotes in which order the controls are executed. They are executed one after the
other in the exact order they are listed in the code.
• conditionally – allows choosing which set of controls is executed. Based on the needed
condition, one set of commands is chosen while others aren’t executed.
• repetitively – allows the same controls to be performed over and over again. Repetition stops
when it meets certain terms or performs a defined number of iterations.
3.Component
• 3.1 Structograms - graphical representation of structured programming(Flowchart).
• 3.3 Block- Block is a section of code grouped together and it consists of one or more
declarations and statements.(ex: { ….}
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):
if (condition2):
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)
Syntax:
expression if Boolean-expression else expression
Example:
Biggest of two numbers
num1 = 23
num2 = 15
big = num1 if num1 > num2 else num2
print ( “ the biggest number is “ , big )
Even or odd
print ( “ num is even “ if num % 2 == 0 else “ num is odd “)
24
Iteration – Loops
With the while loop we can execute a set of statements as long as a condition is true
Example
i=1
while i < 6:
print(i)
i += 1
With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Example
#Print a message once the condition is false:
•i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string). This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages. With the for loop we can
execute a set of statements, once for each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
The for loop does not require an indexing variable to set beforehand
Looping Through a String
With the break statement we can stop the loop before it has looped through all the items:
Example
Exit the loop when x is "banana":
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.
Example
• for x in range(6):
print(x)
Example
print(x)
The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
Example
#Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Nested Loops
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each
iteration of the "outer loop":
Example
#Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Note:
What is meant by structured language?
• C is called a structured programming language because to solve a large problem, C
programming language divides the problem into smaller modules called functions or procedures each
of which handles a particular responsibility. The program which solves the entire problem is a
collection of such functions
Examples of Structured Programming language are C, C+, C++, C#, Java, PERL, Ruby, PHP,
ALGOL, Pascal, PL/I and Ada
Examples of unstructured Programming language are JOSS, FOCAL, MUMPS, TELCOMP, COBOL
Procedural Programming Paradigm
• 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.
• 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
Relationship of data and functions in procedural programming
Characteristics of Procedure-Oriented Programming
• 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.
Function 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.
• 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.
Python function
Syntax:
def function_name(parameters):
"""docstring"""
statement(s)
Defining a function:
def greet(name):
print("Hello, " + name + ". Good morning!")
Calling a function
>>>greet ( “name”)
50
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Example:
#function definition
def my_function():
print("Hello from a function")
You can call a function by using the following types of formal arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the
function call should match exactly with the function definition.
print str
return;
printme()
Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1
argument (0 given)
Keyword Arguments
If you have some functions with many parameters and you want to specify only some of them, then you can
give values for such parameters by naming them - this is called keyword arguments. By specifying the name of
the parameter we can substitute the value.
Advantages
• one, using the function is easier since we do not need to worry about the or-der of the arguments.
• we can give values to only those parameters which we want, provided that the other parameters have default
argument values.
Example:
def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
54
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
call for that argument. The following example gives an idea on default arguments, it prints default age
if it is not passed −
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function call.
Following is a simple example −
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
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
Example:
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
59
The Anonymous Functions
• These functions are called anonymous because they are not declared in the standard manner by using the def
keyword. You can use the lambda keyword to create small anonymous functions.
• Lambda forms can take any number of arguments but return just one value in the form of an expression. They
cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an expression
• Lambda functions have their own local namespace and cannot access variables other than those in their parameter
list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements
in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.
Syntax
• The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
• Following is the example to show how lambda form of function works −
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
O/p
Value of total : 30
Value of total : 40
The return Statement
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.
All the above examples are not returning any value. You can return a value from a function
as follows −
Returning multiple values
62
• Scope of Variables
• All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.
• The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python −
• Global variables
• Local variables
• Global vs. Local variables
• Variables that are defined inside a function body have a local scope, and those defined outside
have a global scope.
• This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all functions.
When you call a function, the variables declared inside it are brought into scope. Following is a
simple example −
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0
3. Object-Oriented Programming
• 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
Organization of data and functions in OOP
Object A Object B
Data Data
Communication
Functions Functions
Object C
Data
Functions
Characteristics of Object-Oriented Programming
• Definition:
It is an approach that provides a way of modularizing programs by creating partitioned
memory area for both data and functions that can be used as templates for creating copies
of such modules on demand. Thus the object is considered to be a partitioned area of
computer memory that stores data and set of operations that can access that data.
Basic Concepts of Object-Oriented Programming
• Objects
• Classes
• Data Abstraction and Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
Basic Concepts of OOP
continue …
• Objects
Objects are the basic run-time entities in an object-oriented system. They may represent a
person, a place, a bank account, etc. Objects take up space in the memory and have an
associated address like a structure in C.
When a program is executed, the objects interact by sending messages to one another.
Basic Concepts of OOP continue …
• Objects
Object : CUSTOMER Object : ACCOUNT
DATA DATA
AC No. AC No.
Name of AC Holder AC Balance
Address Type of Account
FUNCTIONS FUNCTIONS
Deposit Account Balance
Withdrawal
AC Balance Display
Basic Concepts of OOP
continue …
• Classes
Classes are user-defined data types.
The entire set of data and code of an object can be made a user-defined data type with the
help of a class. Objects are variables of the type class. Once a class has been defined, we
can create any number of objects belonging to that class. Each object is associated with
the data of type class with which they are created.
•Classes
fruit mango;
The attributes wrapped in the classes are called data members and the functions
that operate on these data are called methods or member functions.
Since the classes use the concept of data abstraction, they are known as Abstracted
Data Types (ADT).
Basic Concepts of OOP continue …
•Inheritance
o Inheritance is the process by which objects of one class acquire the
properties of objects of another class.
o Each derived class shares common characteristics with the class from which it
is derived.
Property Inheritance
Bird
Attributes:
Feathers
Lay eggs
Attributes: Attributes:
------------ ------------
------------ ------------
•Inheritance
o Inheritance provides the idea of reusability.
•Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in
response to the call.
Dynamic binding ( late binding ) means that the code associated with a given
procedure call is not known until the time of the call at run-time.
•Message Passing
o An oop consists of a set of objects that communicate with each other.
o Oop involves the following steps:
o Creating classes that define objects and their behaviour.
o Creating objects from class definitions.
o Establishing communication among objects.
o Objects communicate with one another by sending and receiving
information.
Basic Concepts of OOP continue …
•Message Passing
o A message for an object is a request for execution of a procedure.
o The receiving object will invoke a function and generates results.
o Message passing involves specifying:
o The name of the Object.
o The name of the Function.
o The information to be send.
Benefits of OOP
• Inspiration: In the real world, objects have a “state” (data) and “behaviors” (functions)
• Think in terms of objects that contain data and offer methods (functions that operate on objects) −→ Data and functions form a
unit
• Organize your code in classes (blueprints for objects): Every object is instance of its class
Class and Objects
• Python, everything is an object.
• A class is a blueprint for the object. To create an object we require a model or plan or blueprint which is nothing but class.
• A class contains the properties (attribute) and action (behavior) of the object. Properties represent variables, and the methods
represent actions. Hence class includes both variables and methods.
• Object is an instance of a class. The physical existence of a class is nothing but an object. In other words, the object is an entity
that has a state and behavior. It may be any real-world object like the mouse, keyboard, laptop, etc.
Class and Objects
Class, attributes can be defined into two parts:
• Instance variables: The instance variables are attributes attached to an instance of a class. We define instance variables in the
constructor ( the __init__() method of a class).
• Class Variables: A class variable is a variable that is declared inside of class, but outside of any instance method or __init()__
method.
• Instance method: Used to access or modify the object attributes. If we use instance variables inside a method, such methods are
called instance methods.
• Class method: Used to access or modify the class state. In method implementation, if we use only class variables, then such type
of methods we should declare as a class method.
• Static method: It is a general utility method that performs a task in isolation. Inside this method, we don’t use instance or class
variable because this static method doesn’t have access to the class attributes.
Creating Class and Objects
Syntax:
Create Object:
Creating Class and Object in Python
Creating Class and Object in Python
Class
Constructor in Python
• Constructor is a special type of method used to initialize the object of a Class
• It can take at least one argument that is self. The __init()__ method is called the constructor in Python
Syntax:
• __init__() Method: It is a reserved method. This method gets called as soon as an object of a class is instantiated.
• self: The first argument self refers to the current object. It binds the instance to the __init__() method. It’s usually named self to follow the
naming convention.
• Python, every class has a constructor, but it’s not required to define it explicitly. Defining constructors in class is optional.
• In Python, we have three types of constructor default, Non-parametrized, and parameterized constructor.
• Using self, we can access the instance variable and instance method of the object. The first argument self refers to the current
object.
• If the parent class doesn’t have a default constructor, then the compiler would not insert a default constructor in the child class.
• A child class constructor can also invoke the parent class constructor using the super() method.
Destructor in Python
• Destructor is a special method that is called when an object gets destroyed.
• The special method __del__() is used to define a destructor. For example, when we execute del object_name destructor gets
called automatically and the object gets garbage collected.
Syntax:
• __del__() Method: It is a reserved method. This method gets called as soon as all references to the object have been deleted
• Encapsulation can be achieved by declaring the data members and methods of a class either as private or protected. But In
Python, we don’t have direct access modifiers like public, private, and protected. We can achieve this by using single underscore
and double underscores.
Encapsulation in Python
Access modifiers limit access to the variables and methods of a class. Python provides three types of access modifiers private,
public, and protected.
The process of calling the same method with different parameters is known as method overloading. Python does not support method
overloading. Python considers only the latest defined method even if you overload the method. Python will raise a TypeError if you
overload the method.
Polymorphism
Inheritance
Process of inheriting the properties of the parent class into a child class is called inheritance
Syntax:
Inheritance
Multiple
Single
Inheritance
Hierarchical
Multilevel
Super
In child class, we can refer to parent class by using the super() function. The super function returns a temporary object of the parent
class that allows us to call a parent class method inside a child class method.
Overriding
All members available in the parent class are by default available in the child class. If the child class does not satisfy with parent class
implementation, then the child class is allowed to redefine that method by extending additional functions in the child class.
Benefits of OOP continue …
•Multiple instances of an objects can
co-exists with out any interference.
•It is easy to partition the work in a project
based on objects.
• Object-oriented system can be easily upgraded from
small to large systems.
• Message passing techniques for communication
between objects makes the interface descriptions
with external systems much simpler.
• Software complexity can be easily managed.
5.Declarative paradigm
Unit- 2 (15 Session )
Session 6-10 covers the following Topics:-
• Definition Declarative Paradigm
• Sets of Declarative Statements
• Object Attribute and Binding behavior
• Creating Event without describing flow
• Other languages: Prolog, Z3, LINQ, SQL
• Demo: Declarative Programming in Python
• Lab 5: Declarative Programming