APP - Unit 1
APP - Unit 1
APP - Unit 1
School of Computing
Structured Programming
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:
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.
2. Modularization for program structure and organization :
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)
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 “)
21
Iteration – Loops
• Python has two primitive loop commands:
• while loops
• for loops
The while Loop
• With the while loop we can execute a set of statements as long as a condition is true
Example
• Print i as long as i is less than 6:
•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":
• 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)
Reference : https://www.w3schools.com/python/python_for_loops.asp
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
• 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.
• 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.
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 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.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax
error as follows −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
call for that argument. The following example gives an idea on default arguments, it prints default age
if it is not passed −
• You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.
• Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"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;
• 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;
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.
Basic Concepts of OOP continue
…
•Data Abstraction and Encapsulation
o The wrapping up of data and functions into a single unit is
known as encapsulation.
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.
• 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.
Basic Concepts of OOP continue
…
•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.
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).