Python Hand Book

Download as pdf or txt
Download as pdf or txt
You are on page 1of 387

ALGORITHMIC PROBLEM SOLVING

Algorithms, building blocks of algorithms (statements, state, control flow, functions),


notation (pseudo code, flow chart, programming language), algorithmic problem
solving, simple strategies for developing algorithms (iteration, recursion). Illustrative
problems: find minimum in a list, insert a card in a list of sorted cards, Guess an
integer number in a range, Towers of Hanoi.

PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating
number of solutions.
The problem solving process starts with the problem specifications and ends with a
Correct program.

PROBLEM SOLVING TECHNIQUES


Problem solving technique is a set of techniques that helps in providing logic for solving
a problem.
Problem Solving Techniques:
Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. programs
ALGORITHM
It is defined as a sequence of instructions that describe a method for solving a
problem. In other words it is a step by step procedure for solving a problem.

 Should be written in simple English


 Each and every instruction should be precise and unambiguous.
 Instructions in an algorithm should not be repeated infinitely.
 Algorithm should conclude after a finite number of steps.
 Should have an end point
 Derived results should be obtained only after the algorithm terminates.
Qualities of a good algorithm
The following are the primary factors that are often used to judge the quality of the
algorithms.
Time – To execute a program, the computer system takes some amount of time. The
lesser is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory
space. The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given
problem, some of these may provide more accurate results than others, and such
algorithms may be suitable.
Example:
Example
Write an algorithm to print „Good Morning”
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop

BUILDING BLOCKS OF ALGORITHMS (statements, state, control flow, functions)


Algorithms can be constructed from basic building blocks namely, sequence,
selection and iteration.
Statements:
Statement is a single action in a computer.

In a computer statements might include some of the following actions


 input data-information given to the program
 process data-perform operation on a given input
 output data-processed result

State:
Transition from one process to another process under specified condition with in a
time is called state.

Control flow:
The process of executing the individual statements in a given order is called control
flow.
The control can be executed in three ways
1. sequence
2. selection
3. iteration

Sequence:
All the instructions are executed one after another is called sequence execution.

Example:
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop

Selection:
A selection statement causes the program control to be transferred to a specific
part of the program based upon the condition.
If the conditional test is true, one part of the program will be executed, otherwise
it will execute the other part of the program.
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop

Iteration:
In some programs, certain set of statements are executed again and again based
upon conditional test. i.e. executed more than one time. This type of execution is called
looping or iteration.

Example

Write an algorithm to print all natural numbers up to n

Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop

2.4.Functions:
 Function is a sub program which consists of block of code(set of instructions)
that performs a particular task.
 For complex problems, the problem is been divided into smaller and simpler
tasks during algorithm design.
Benefits of Using Functions
 Reduction in line of code
 code reuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability
Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop

sub function add()


Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return

NOTATIONS
FLOW CHART

Flow chart is defined as graphical representation of the logic for problem solving.
The purpose of flowchart is making the logic of the program clear in a visual
representation.
Rules for drawing a flowchart
1. The flowchart should be clear, neat and easy to follow.
2. The flowchart must have a logical start and finish.
3. Only one flow line should come out from a process symbol.

4. Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.

5. Only one flow line is used with a terminal symbol.

6. Within standard symbols, write briefly and precisely.


7. Intersection of flow lines should be avoided.

Advantages of flowchart:
1. Communication: - Flowcharts are better way of communicating the logic of a
system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in more
effective way.
3. Proper documentation: - Program flowcharts serve as a good program
documentation, which is needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during the systems
analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. Efficient Program Maintenance: - The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put efforts more
efficiently on that part.

1. Complex logic: - Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart may
require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
4. Cost: For large application the time and cost of flowchart drawing becomes costly.
PSEUDO CODE:
 Pseudo code consists of short, readable and formally styled English languages used
for explain an algorithm.
 It does not include details like variable declaration, subroutines.
 It is easier to understand for the programmer or non programmer to understand the
general working of the program, because it is not based on any programming
language.
 It gives us the sketch of the program before actual coding.
 It is not a machine readable
 Pseudo code can’t be compiled and executed.
 There is no standard syntax for pseudo code.

 Write one statement per line


 Capitalize initial keyword
 Indent to hierarchy
 End multiline structure
 Keep statements language independent
Common keywords used in pseudocode
The following gives common keywords used in pseudocodes. 1. //:
This keyword used to represent a comment.
2. BEGIN,END: Begin is the first statement and end is the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given expression. 5.
ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7. IF, ELSE, ENDIF: used to make decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.
Syntax for if else: Example: Greates of two numbers
IF (condition)THEN BEGIN
Statement READ a,b
... IF (a>b) THEN
ELSE DISPLAY a is greater
Statement ELSE
... DISPLAY b is greater
ENDIF END IF
END
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-value) DO BEGIN
Statement GET n
... INITIALIZE i=1
ENDFOR FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO BEGIN
Statement GET n
... INITIALIZE i=1
ENDWHILE WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Advantages:
 Pseudo is independent of any language; it can be used by most programmers.
 It is easy to translate pseudo code into a programming language.
 It can be easily modified as compared to flowchart.
 Converting a pseudo code to programming language is very easy as compared
with converting a flowchart to programming language.

 It does not provide visual representation of the program’s logic.


 There are no accepted standards for writing pseudo codes.
 It cannot be compiled nor executed.
 For a beginner, It is more difficult to follow the logic or write pseudo code as
compared to flowchart.
Example:
Addition of two numbers:
BEGIN
GET a,b
ADD c=a+b
PRINT c
END
Algorithm Flowchart Pseudo code
An algorithm is a sequence It is a graphical It is a language
of instructions used to representation of algorithm representation of
solve a problem algorithm.
User needs knowledge to not need knowledge of Not need knowledge of
write algorithm. program to draw or program language to
understand flowchart understand or write a
pseudo code.

PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing a computer
to perform specific tasks. The programmers have to follow all the specified rules
before writing program using programming language. The user has to communicate
with the computer using language which it can understand.
Types of programming language
1. Machine language
2. Assembly language
3. High level language
Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In
machine language the different instructions are formed by taking different
combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language which the computer understands. For
executing any program written in any programming language, the conversion to
machine language is necessary. The program written in machine language can be
executed directly on computer. In this case any conversion process is not required.
High speed
The machine language program is translation free. Since the conversion time is
saved, the execution of machine language program is extremely fast.
Disadvantage:
 It is hard to find errors in a program written in the machine language.
 Writhing program in machine language is a time consuming process.
Machine dependent: According to architecture used, the computer differs from each
other. So machine language differs from computer to computer. So a program
developed for a particular type of computer may not run on other type of computer.
Assembly language:
 To overcome the issues in programming language and make the programming
process easier, an assembly language is developed which is logically equivalent to
machine language but it is easier for people to read, write and understand.
 Assembly language is symbolic representation of machine language. Assembly
languages are symbolic programming language that uses symbolic notation to
represent machine language instructions. They are called low level language
because they are so closely related to the machines.

Assembler is the program which translates assembly language instruction in to a


machine language.

 Easy to understand and use.


 It is easy to locate and correct errors.
Disadvantage
Machine dependent
The assembly language program which can be executed on the machine
depends on the architecture of that computer.
Hard to learn
It is machine dependent, so the programmer should have the hardware
knowledge to create applications using assembly language.
Less efficient
 Execution time of assembly language program is more than machine
language program.
 Because assembler is needed to convert from assembly language to machine
language.
High level language
High level language contains English words and symbols. The specified rules are
to be followed while writing program in high level language. The interpreter or
compilers are used for converting these programs in to machine readable form.
Translating high level language to machine language
The programs that translate high level language in to machine language are called
interpreter or compiler.

Compiler:
A compiler is a program which translates the source code written in a high level
language in to object code which is in machine language program. Compiler reads the
whole program written in high level language and translates it to machine language. If
any error is found it display error message on the screen.

Interpreter
Interpreter translates the high level language program in line by line manner. The
interpreter translates a high level language statement in a source program to a machine
code and executes it immediately before translating the next statement. When an
error is found the execution of the program is halted and error message is displayed
on the screen.
Advantages
Readability
High level language is closer to natural language so they are easier to learn and
understand
Machine independent
High level language program have the advantage of being portable between
machines.
Easy debugging
Easy to find and correct error in high level language
Disadvantages
Less efficient
The translation process increases the execution time of the program. Programs
in high level language require more memory and take more execution time to execute.

They are divided into following categories:


1. Interpreted programming languages
2. Functional programming languages
3. Compiled programming languages
4. Procedural programming languages
5. Scripting programming language
6. Markup programming language
7. Concurrent programming language
8. Object oriented programming language

Interpreted programming languages:


An interpreted language is a programming language for which most of its
implementation executes instructions directly, without previously compiling a program
into machine language instructions. The interpreter executes the program directly
translating each statement into a sequence of one or more subroutines already
compiled into machine code.
Examples:
Pascal
Python

Functional programming language:


Functional programming language defines every computation as a mathematical
evaluation. They focus on the programming languages are bound to mathematical
calculations
Examples:
Clean
Haskell

Unit 1: Algorithmic problem solving 10


Compiled Programming language:
A compiled programming is a programming language whose implementation are
typically compilers and not interpreters.
It will produce a machine code from source code.
Examples:
C
C++
C#
JAVA

Procedural programming language:


Procedural (imperative) programming implies specifying the steps that the
programs should take to reach to an intended state.
A procedure is a group of statements that can be referred through a procedure call.
Procedures help in the reuse of code. Procedural programming makes the programs
structured and easily traceable for program flow.
Examples:
Hyper talk
MATLAB

Scripting language:
Scripting language are programming languages that control an application.
Scripts can execute independent of any other application. They are mostly embedded in
the application that they control and are used to automate frequently executed tasks
like communicating with external program.

Examples:
Apple script
VB script

Markup languages:
A markup language is an artificial language that uses annotations to text that
define hoe the text is to be displayed.
Examples:
HTML
XML
Concurrent programming language:
Concurrent programming is a computer programming technique that provides
for the execution of operation concurrently, either with in a single computer or across a
number of systems.
Examples:
Joule
Limbo
Object oriented programming language:
Object oriented programming is a programming paradigm based on the concept
of objects which may contain data in the form of procedures often known as methods.
Examples:
Lava
Moto

ALGORITHMIC PROBLEM SOLVING:

Algorithmic problem solving is solving problem that require the formulation of an


algorithm for the solution.

Understanding the Problem


 It is the process of finding the input of the problem that the algorithm solves.
 It is very important to specify exactly the set of inputs the algorithm needs to
handle.
 A correct algorithm is not one that works most of the time, but one that works
correctly for all legitimate inputs.
Ascertaining the Capabilities of the Computational Device

 If the instructions are executed one after another, it is called sequential


algorithm.
 If the instructions are executed concurrently, it is called parallel algorithm.

Choosing between Exact and Approximate Problem Solving


 The next principal decision is to choose between solving the problem exactly or
solving it approximately.
 Based on this, the algorithms are classified as exact algorithm and approximation
algorithm.

 Data structure plays a vital role in designing and analysis the algorithms.
 Some of the algorithm design techniques also depend on the structuring data
specifying a problem’s instance
 Algorithm+ Data structure=programs.

Algorithm Design Techniques


 An algorithm design technique (or “strategy” or “paradigm”) is a general
approach to solving problems algorithmically that is applicable to a variety of
problems from different areas of computing.
 Learning these techniques is of utmost importance for the following reasons.
 First, they provide guidance for designing algorithms for new problems,
 Second, algorithms are the cornerstone of computer science

Methods of Specifying an Algorithm


 Pseudocode is a mixture of a natural language and programming language-like
constructs. Pseudocode is usually more precise than natural language, and its
usage often yields more succinct algorithm descriptions.

 In the earlier days of computing, the dominant vehicle for specifying algorithms
was a flowchart, a method of expressing an algorithm by a collection of
connected geometric shapes containing descriptions of the algorithm’s steps.

 Programming language can be fed into an electronic computer directly. Instead,


it needs to be converted into a computer program written in a particular
computer language. We can look at such a program as yet another way of
specifying the algorithm, although it is preferable to consider it as the algorithm’s
implementation.

 Once an algorithm has been specified, you have to prove its correctness. That is,
you have to prove that the algorithm yields a required result for every legitimate
input in a finite amount of time.
 A common technique for proving correctness is to use mathematical induction
because an algorithm’s iterations provide a natural sequence of steps needed for
such proofs.
 It might be worth mentioning that although tracing the algorithm’s performance
for a few specific inputs can be a very worthwhile activity, it cannot prove the
algorithm’s correctness conclusively. But in order to show that an algorithm is
incorrect, you need just one instance of its input for which the algorithm fails.
Analysing an Algorithm
1. Efficiency.
Time efficiency, indicating how fast the algorithm runs,
Space efficiency, indicating how much extra memory it
uses.

2. simplicity.
 An algorithm should be precisely defined and investigated with mathematical
expressions.
 Simpler algorithms are easier to understand and easier to program.
 Simple algorithms usually contain fewer bugs.

Coding an Algorithm
 Most algorithms are destined to be ultimately implemented as computer
programs. Programming an algorithm presents both a peril and an opportunity.
 A working program provides an additional opportunity in allowing an
empirical analysis of the underlying algorithm. Such an analysis is based on
timing the program on several inputs and then analysing the results obtained.

5.SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:


1. iterations
2. Recursions
5.1.Iterations:
A sequence of statements is executed until a specified condition is true is called
iterations.
1. for loop
2. While loop
Syntax for For: Example: Print n natural numbers
BEGIN
FOR( start-value to end-value) DO GET n
Statement INITIALIZE i=1
... FOR (i<=n) DO
ENDFOR PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
BEGIN
WHILE (condition) DO GET n
Statement INITIALIZE i=1
... WHILE(i<=n) DO
ENDWHILE PRINT i
i=i+1
ENDWHILE
END
Recursions:
 A function that calls itself is known as recursion.
 Recursion is a process by which a function calls itself repeatedly until some
specified condition has been satisfied.

Algorithm for factorial of n numbers using recursion:

Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop

Sub function factorial(n):


Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact
Pseudo code for factorial using recursion:

Main function:

BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN

Sub function factorial(n):

IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
More examples:
Write an algorithm to find area of a rectangle

Step 1: Start BEGIN


Step 2: get l,b values READ l,b
Step 3: Calculate A=l*b CALCULATE A=l*b
Step 4: Display A DISPLAY A
Step 5: Stop END

Write an algorithm for Calculating area and circumference of circle

Step 1: Start BEGIN


Step 2: get r value READ r
Step 3: Calculate A=3.14*r*r CALCULATE A and C
Step 4: Calculate C=2.3.14*r A=3.14*r*r
Step 5: Display A,C C=2*3.14*r
Step 6: Stop DISPLAY A
END
Write an algorithm for Calculating simple interest
Step 1: Start
Step 2: get P, n, r value BEGIN
Step3:Calculate READ P, n, r
SI=(p*n*r)/100 CALCULATE S
Step 4: Display S SI=(p*n*r)/100
Step 5: Stop DISPLAY SI
END

Write an algorithm for Calculating engineering cutoff


Step 1: Start
Step2: get P,C,M value BEGIN
Step3:calculate READ P,C,M
Cutoff= (P/4+C/4+M/2) CALCULATE
Step 4: Display Cutoff Cutoff= (P/4+C/4+M/2)
Step 5: Stop DISPLAY Cutoff
END

To check greatest of two numbers


Step 1: Start
Step 2: get a,b value
Step 3: check if(a>b) print a is greater
Step 4: else b is greater
Step 5: Stop
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END

To check leap year or not


Step 1: Start
Step 2: get y
Step 3: if(y%4==0) print leap year
Step 4: else print not leap year
Step 5: Stop
BEGIN
READ y
IF (y%4==0) THEN
DISPLAY leap year
ELSE
DISPLAY not leap year
END IF
END
To check positive or negative number
Step 1: Start
Step 2: get num
Step 3: check if(num>0) print a is positive
Step 4: else num is negative
Step 5: Stop

BEGIN
READ num
IF (num>0) THEN
DISPLAY num is positive
ELSE
DISPLAY num is negative
END IF
END
To check odd or even number
Step 1: Start
Step 2: get num
Step 3: check if(num%2==0) print num is even
Step 4: else num is odd
Step 5: Stop
BEGIN
READ num
IF (num%2==0) THEN
DISPLAY num is even
ELSE
DISPLAY num is odd
END IF
END

To check greatest of three numbers


Step1: Start
Step2: Get A, B, C
Step3: if(A>B) goto Step4 else goto step5
Step4: If(A>C) print A else print C
Step5: If(B>C) print B else print C
Step6: Stop
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
DISPLAY c is greater
END IF
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END

Write an algorithm to check whether given number is +ve, -ve or zero.


Step 1: Start
Step 2: Get n value.
Step 3: if (n ==0) print “Given number is Zero” Else goto step4
Step 4: if (n > 0) then Print “Given number is +ve”
Step 5: else Print “Given number is -ve”
Step 6: Stop
BEGIN
GET n
IF(n==0) THEN
DISPLAY “ n is zero”
ELSE
IF(n>0) THEN
DISPLAY “n is positive”
ELSE
DISPLAY “n is positive”
END IF
END IF
END
Write an algorithm to print all natural numbers up to n

Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 8
Step 5: Print i value
step 6 : increment i value by 1
Step 7: go to step 4
Step 8: Stop

BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Write an algorithm to print n odd numbers

Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check if(i<=n) goto step 5 else goto step 8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop

BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
Write an algorithm to print n even numbers

Step 1: start
step 2: get n value
step 3: set initial value i=2
step 4: check if(i<=n) goto step 5 else goto step8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop

BEGIN
GET n
INITIALIZE i=2
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
Write an algorithm to print squares of a number
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop

BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i
i=i+2
ENDWHILE
END
Write an algorithm to print to print cubes of a number
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: print i*i *i value
step 6: increment i value by 1
step 7: goto step 4
step 8: stop
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i*i
i=i+2
ENDWHILE
END
Write an algorithm to find sum of a given number

Step 1: start
step 2: get n value
step 3: set initial value i=1, sum=0
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate sum=sum+i
step 6: increment i value by 1
step 7: goto step 4
step 8: print sum value
step 9: stop

BEGIN
GET n
INITIALIZE i=1,sum=0
WHILE(i<=n) DO
sum=sum+i
i=i+1
ENDWHILE
PRINT sum
END
Write an algorithm to find factorial of a given number

Step 1: start
step 2: get n value
step 3: set initial value i=1, fact=1
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate fact=fact*i
step 6: increment i value by 1
step 7: goto step 4
step 8: print fact value
step 9: stop

BEGIN
GET n
INITIALIZE i=1,fact=1
WHILE(i<=n) DO
fact=fact*i
i=i+1
ENDWHILE
PRINT fact
END
Basic python programs:
Addition of two numbers Output
a=eval(input(“enter first no”)) enter first no
b=eval(input(“enter second no”)) 5
c=a+b enter second no
print(“the sum is “,c) 6
the sum is 11
Area of rectangle Output
l=eval(input(“enter the length of rectangle”)) enter the length of rectangle 5
b=eval(input(“enter the breath of rectangle”)) enter the breath of rectangle 6
a=l*b 30
print(a)
Area & circumference of circle output
r=eval(input(“enter the radius of circle”)) enter the radius of circle4
a=3.14*r*r the area of circle 50.24
c=2*3.14*r the circumference of circle
print(“the area of circle”,a) 25.12
print(“the circumference of circle”,c)
Calculate simple interest Output
p=eval(input(“enter principle amount”)) enter principle amount 5000
n=eval(input(“enter no of years”)) enter no of years 4
r=eval(input(“enter rate of interest”)) enter rate of interest6
si=p*n*r/100 simple interest is 1200.0
print(“simple interest is”,si)

Calculate engineering cutoff Output


p=eval(input(“enter physics marks”)) enter physics marks 100
c=eval(input(“enter chemistry marks”)) enter chemistry marks 99
m=eval(input(“enter maths marks”)) enter maths marks 96
cutoff=(p/4+c/4+m/2) cutoff = 97.75
print(“cutoff =”,cutoff)

Check voting eligibility output


age=eval(input(“enter ur age”)) Enter ur age
If(age>=18): 19
print(“eligible for voting”) Eligible for voting
else:
print(“not eligible for voting”)
Find greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Programs on for loop
Print n natural numbers Output

for i in range(1,5,1): 1234

print(i)
Print n odd numbers Output
for i in range(1,10,2):
13579
print(i)

Print n even numbers Output


for i in range(2,10,2):
2468
print(i)
Print squares of numbers Output

for i in range(1,5,1): 14916

print(i*i)

Print squares of numbers Output

for i in range(1,5,1): 182764

print(i*i*i)

Programs on while loop


Print n natural numbers Output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
5
Print n odd numbers Output
i=2 2
while(i<=10): 4
print(i) 6
i=i+2 8
10
Print n even numbers Output
i=1 1
while(i<=10): 3
print(i) 5
i=i+2 7
9
Print n squares of numbers Output
i=1 1
while(i<=5): 4
print(i*i) 9
i=i+1 16
25

Print n cubes numbers Output


i=1 1
while(i<=3): 8
print(i*i*i) 27
i=i+1

find sum of n numbers Output


i=1 55
sum=0
while(i<=10):
sum=sum+i
i=i+1
print(sum)
factorial of n numbers/product of n numbers Output
i=1 3628800
product=1
while(i<=10):
product=product*i
i=i+1
print(product)

sum of n numbers Output


def add(): enter a value
a=eval(input(“enter a value”)) 6
b=eval(input(“enter b value”)) enter b value
c=a+b 4
print(“the sum is”,c) the sum is 10
add()

area of rectangle using function Output


def area(): enter the length of
l=eval(input(“enter the length of rectangle”)) rectangle 20
b=eval(input(“enter the breath of rectangle”)) enter the breath of
a=l*b rectangle 5
print(“the area of rectangle is”,a) the area of rectangle is
area() 100

swap two values of variables Output


def swap(): enter a value3
a=eval(input("enter a value")) enter b value5
b=eval(input("enter b value")) a= 5 b= 3
c=a
a=b
b=c
print("a=",a,"b=",b)
swap()

Unit 1: Algorithmic problem solving 34


check the no divisible by 5 or not Output
def div(): enter n value10
n=eval(input("enter n value")) the number is divisible by
if(n%5==0): 5
print("the number is divisible by 5")
else:
print("the number not divisible by 5")
div()

find reminder and quotient of given no Output


def reminder(): enter a 6
a=eval(input("enter a")) enter b 3
b=eval(input("enter b")) the reminder is 0
R=a%b enter a 8
print("the reminder is",R) enter b 4
def quotient(): the reminder is 2.0
a=eval(input("enter a"))
b=eval(input("enter b"))
Q=a/b
print("the reminder is",Q)
reminder()
quotient()

convert the temperature Output


enter temperature in
def ctof(): centigrade 37
c=eval(input("enter temperature in centigrade")) the temperature in
f=(1.8*c)+32 Fahrenheit is 98.6
print("the temperature in Fahrenheit is",f) enter temp in Fahrenheit
def ftoc(): 100
f=eval(input("enter temp in Fahrenheit")) the temperature in
c=(f-32)/1.8 centigrade is 37.77
print("the temperature in centigrade is",c)
ctof()
ftoc()
program for basic calculator Output
def add(): enter a value 10
a=eval(input("enter a value")) enter b value 10
b=eval(input("enter b value")) the sum is 20
c=a+b enter a value 10
print("the sum is",c) enter b value 10
def sub(): the diff is 0
a=eval(input("enter a value")) enter a value 10
b=eval(input("enter b value")) enter b value 10
c=a-b the mul is 100
print("the diff is",c) enter a value 10
def mul(): enter b value 10
a=eval(input("enter a value")) the div is 1
b=eval(input("enter b value"))
c=a*b
print("the mul is",c)
def div():
a=eval(input("enter a value"))
b=eval(input("enter b value"))
c=a/b
print("the div is",c)
add()
sub()
mul()
div()

Unit 1: Algorithmic problem solving 36


Part A:
1. What is mean by problem solving?
2. List down the problem solving techniques?
3. Define algorithm?
4. What are the properties of algorithm?
5. List down the equalities of good algorithm?
6. Define statements?
7. Define state?
8. What is called control flow?
9. What is called sequence execution?
10. Define iteration?
11. What is mean by flow chart?
12. List down the basic symbols for drawing flowchart?
13. List down the rules for drawing the flowchart?
14. What are the advantages of flowchart?
15. What are the disadvantages of flowchart?
16. Define pseudo code?
17. List down the keywords used in writing pseudo code?
18. Mention the advantages of using pseudo code?
19. Mention the disadvantages of using pseudo code?
20. What are the ways available to represent algorithm?
21. Differentiate flowchart and pseudo code?
22. Differentiate algorithm and pseudo code?
23. What is programming language?
24. Mention the types of programming language?
25. What is mean by machine level language?
26. What are the advantages and disadvantages of machine level language?
27. What is high level programming language and mention its advantages?
28. What are the steps in algorithmic problem solving?
29. Write the algorithm for any example?
30. Draw the flow chart for any example?
31. Write pseudo code for any example?

1. Explain in detail about problem solving techniques?


2. Explain in detail about building blocks of algorithm?
3. Discuss the symbols and rules for drawing flowchart with the example?
4. Explain in detail about programming language?
5. Discuss briefly about algorithmic problem solving?
6. Write algorithm, pseudo code and flow chart for any example?
7. Explain in detail about simple strategies for developing algorithms?
DATA, EXPRESSIONS, STATEMENTS
Python interpreter and interactive mode; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; Modules and functions, function definition and use, flow of execution,
parameters and arguments; Illustrative programs: exchange the values of two variables,
circulate the values of n variables, distance between two points.

1. INTRODUCTION TO PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the year
2000.
 Python is interpreted: Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it.
 Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of applications.

Easy-to-learn:Python is clearly defined and easily readable. The structure of


the program is very simple. It uses few keywords.

 Easy-to-maintain: Python's source code is fairly easy-to-maintain.


 Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
 Interpreted: Python is processed at runtime by the interpreter. So, there is no
need to compile a program before executing it. You can simply run the program.
 Extensible: Programmers can embed python within their C,C++,Java script
,ActiveX, etc.
 Free and Open Source: Anyone can freely distribute it, read the source code, and
edit it.
 High Level Language: When writing programs, programmers concentrate on
solutions of the current problem, no need to worry about the low level details.
 Scalable: Python provides a better structure and support for large programs than
shell scripting.

Bit Torrent file sharing


Google search engine, Youtube
Intel, Cisco, HP, IBM
i–Robot
NASA
Facebook, Drop box
1.3. Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line at
a time.
Compiler: To translate a program written in a high-level language into a low-level
language all at once, in preparation for later execution.

Compile
r Interpreter
Interpreter Takes Single instruction as
Compiler Takes Entire program as input
input
No Intermediate Object Code
Intermediate Object Code is Generated
is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More(Since Object Memory Requirement is Less
Code is Generated)
Every time higher level program is
Program need not be compiled every time
converted into lower level program
Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
Example : C Compiler Example : PYTHON

1.4 MODES OF PYTHON INTERPRETER:


Python Interpreter is a program that reads and executes Python code. It uses 2 modes
of Execution.
1. Interactive mode
2. Script mode
Interactive mode:
 Interactive Mode, as the name suggests, allows us to interact with OS.
 When we type Python statement, interpreter displays the result(s)
immediately.
Advantages:
 Python, in interactive mode, is good enough to learn, experiment or explore.
 Working in interactive mode is convenient for beginners and for testing small
pieces of code.
Drawback:
 We cannot save the statements and have to retype all the statements once again to
re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you
to enter code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!

2 Unit 2: Data ,expressions, Statements


This is an example of a print statement. It displays a result on the screen. In this case,
the result is the words.

Script mode:
 In script mode, we type python program in a file and then use interpreter to
execute the content of the file.
 Scripts can be saved to disk for future use. Python scripts have the extension
.py, meaning that the filename ends with .py
 Save the code with filename.py and run the interpreter in script mode to execute
the script.

Interactive Script
mode mode
A way of using the Python interpreter by A way of using the Python interpreter to
typing commands and expressions at the read and execute statements in a script.
prompt.
Cant save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
we can use interactive mode. use script mode.
we cannot save the statements for further we can save the statements for further use
use and we have to retype and we no need to retype
all the statements to re-run them. all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.

Integrated Development Learning Environment (IDLE):


 Is a graphical user interface which is completely written in Python.
 It is bundled with the default implementation of the python language and also
comes with optional part of the Python packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.
 Auto completion with smart indentation.
 Python shell to display output with syntax highlighting.
Chapter 3: Input and Output
3.1 Input statement
Python has an input function which gives you a chance to approach a client for some text input.
You call this function to advise the program to stop and wait for the client to key in the data. In
Python 3, you have input().
Syntax
Input([prompt])
Prompt: Where prompt is the string we wish to show on the screen. It is optional
Ex:

By default it will takes as a string


If you want give another type then need to typecast it means changing data type
Syntax
X=int(input())
Y=float(input()
Ex2:

In the above example we are given input is string but we initially declared it as int
That’s the reason it is giving error
Note: in python 2.x we are using raw_input() as a input function

3.2 output statements


The basic way to get the output is using the print()
In python 2.x print is the statement whereas in python 3.x it’s the built in function
Syntax:
print(*objects, sep=’ ’,end=’ \n’, file=sys.stdout, flush=False)
objects: here objects is the value(s) to be printed
Ex:

sep: the sep is used between the values, by default it will take as space
Ex:
end: after all values are printed end is printed. it defaults into a new line
Ex:

File:the file is the object where the values are printed and its default value is sys.stdout(screen)
Output formatting
Some of the time we might want to organize our output to make it look appealing. This should
be possible by utilizing the str.format() method. This method is visible to any string object.
Ex:

Here the curly braces {} are utilized as placeholders. We can determine the order in which it is
printed by utilizing numbers (tuple index).
Ex:

We can even utilize keyword arguments to organize the string.


Ex:

Number formatting

Type Meaning
d Decimal integer
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lower case)
X Hexadecimal format (upper case)
n Same as 'd'. But it utilizes current
locale setting for number separator
e Exponential notation. (lowercase e)
E Exponential notation (uppercase E)
f Displays fixed point number (Default:
6)
F Same as 'f'. But shows 'inf' as 'INF' and
'nan' as 'NAN'
g General format. Rounds number to p
significant digits. (Default precision: 6)
G Same as 'g'. But changes to 'E' if the
number is vast.
% Percentage. Products by 100 and puts
% toward the end.

The below example gives the simple view of number formatting


Example:

Output:

Example:

Output:
Explanation:
in the principal statement, {:5d} takes a integer argument and assigns a base width of 5. Since,
no arrangement is determined, it is adjusted to one side.
In the second statement, you can see the width (2) is less than the number (1234), so it doesn't
take any space to the left but also doesn't truncate the number.
In contrast to integers, floats has both whole number and decimal parts. Also, the mininum width
characterized to the number is for the two parts overall including ".".
In the third statement, {:8.3f} truncates the decimal part into 3 places rounding off the last 2
digits. Also, the number, now 12.235, accepts a width of 8 in general leaving 2 spots to one side.
On the off chance that you need to fill the rest of the spots with zero, setting a zero preceding the
configuration specifier does this. It works both for numbers and buoys: {:05d} and {:08.3f}.
The below example gives the use of sign operator

Output:

Alignment

Type Meaning

< Left aligned to the remaining space

^ Center aligned to the remaining space

> Right aligned to the remaining space


= Forces the marked (+) (- ) to the furthest left position

Example:

Output:

the below example will gives the strings with alignment


example:
Output:

3.3 Command Line Arguments


Command functioning script need to use command line arguments. Python sys module
gives permission to any command line arguments through sys.argv. It is mainly an array holding
the command line arguments of the programs. The arguments start from “0” and not from “1”.
Python provides a module that helps you command-line options and arguments. This is module
is called as sys.argv Module, It is mainly used for following purpose
 sys.argv is the list of command-line arguments.
 len(sys.argv) is the number of command-line arguments.

sys.argv is the list of command-line arguments:


The list of command line arguments conceded to python script. argv[0] is the script name
which is osdependant. For the process of using we have to first import the import sys , the first
program name sys.argv[0]. And sys.argv[1] is the first argument first we pass to the program.
sys.argv is the list of the command line augments. And len(sys.argv) is the number of command
line arguments.
sys.argv:-
Syntax:-
Import sys
print(arg1,arg2,arg3…..)

Example:
Explanation Program:
In above example by using import keyword we are importing sys module to see the following
Details they are as follows
In first out we are getting the file location where it exists on our local machine or local drive
Whereas second output display the number students and third output is giving location in list
format by using sys arguments
sys.copyright:-
Example 2:

In above example by using import keyword we are importing sys module to see the following
Details they are as follows.
In first example it explains about the program name and second line it describes about defaults
arguments in existing file Where as second output display is giving location in list format by
using sys arguments
Example 2:
In above example by using import keyword we are importing sys module to see the following
Details they are as follows.
It gives addition of 3 and 5 is 8 by using sys arguments through command prompt
Sys.version:
This methods will gives you version of python i.e. currently which version and date
Time well be displayed and also version compatibility also it describes

Example:

Sys.api_version and sys.copyright:

This method will give the api version and copyright of python for by using python
software foundation help and version release year from staring to ending
For example a version is released from 2001 to 2017 year
Example:

Sys.winver and sys.platform:


This method gives us version of stable release of python in existing version and platform
Where we are using our python application
Example:
4. Variables and Data Type
4.1 Variable:
Python is a complete Object Oriented. Every variable in python is an object. A variable is the
name used to access a value. A variable is a named location which is used to store data in the
memory which can be replaceable. Every variable have a unique name called identifier.
Identifier helps to variables as container to hold data which can be changed later at any time of
the programming.
We can suppose variable as a bag to store stuff in it and that stuff can be replaced at any
time. We can use variables to store all kinds of stuff, but for now, we are just going to look at
storing numbers in variables.
Ex:-

This code creates a variable called python, and assigns to it, integer number as 13. When we ask
Python to tell us what is stored in the variable python, it returns that number again.
Declaring Variables in Python:-
Variables in Python do not need any declaration to reserve memory space. The variable
declaration happens automatically when we assign a value to a variable.
There are some rules with variable names in Python:
 It can only be an only one word.
 It can only use letters, numbers and underscores (_).
 Hyphens are not allowed (-).
 Spaces are not allowed.
 It can’t begin with a number.
 Special characters are not allowed such as $ or ‘.
Please remember:
 variable names are case sensitive, SPAM and spam are different variables
 it is convention in Python to use all lower case letters for variable name, using
underscore (_) separators.
 a good variable name describes the data it contains
Declaring and assigning a value to a variable.
Syntax:
Variable = “Assigning value”
Ex:
website = “Nareshit.com”
print(website)
Output: - Nareshit.com

Changing value of a variable:


Syntax:-
Variable=”new assigning value”
Ex:- website = “Python.org”
#assigning a new variable to website
Website = “nareshit.com”
print(website)
Output: - nareshit.com

Assigning multiple values to a multiple variables

Syntax:-
Variable1=”Assigned value 1”
Variable2=”Assigned value 2”
Variable3=”Assigned value 3”
Ex:-

Number: in python supports two types of numbers integer and floating point numbers. It also
supports complex numbers.

Note: in python, it defines also some special function declare integer and float
Syntax: int ( ) and float ( )

String variable: strings are defines a single quote or double quote.


Example:
Note: we are creates string with apostrophes, single code and double code.

4.2 Literals:
Objects are called data structures. In python some built-in objects. It has a quick way to make
these object called literals. The literals are includes the string, Unicode string, integer, float,
long, list, tuple and dictionary types.
4.2.1 String Literals:
Python has different types of string literals. The following example show you

4.2.2 Numeric literal:


 Numeric values refer to using integers, floating numbers, scientific notation, hexadecimal
notation and complex numbers
 Python integers larger than 2147483647 are called long integer because they can’t be
stored in 32 bits.
Note: long is removed in python 3.x
The following example shows numeric values:

4.2.3 Boolean literal: A Boolean literal can have any of the two values.
4.2.4 Unicode:
Normal character string is set of 256 characters. There are more than 256 characters in the world.
For example: with a notations like α=5ϻ it means it can’t be a written byte string. In world has
agreed on Unicode strings. It extends character space up to 65536 characters and even more.
Note: it complicated to Unicode explain.

4.2.5 Special literals: python contains one special literal i.e None

4.2.6 List literals:


 A list is created with symbol [ ]’s and separating with values with commas (,).
 A list empty is simply [ ].
 It can create, expanded and reduced.
 It reads index based elements.
The following example shows creating and modifying data

Example 2: List create with a generated operator expression


4.2.7 Tuple Literals:
 Tuples are defines by enclosing the elements in parentheses (( )).
 An empty tuple is ( ).
 Tuples are immutable.
 It can be a combined of any data types including other tuples also.
 The element of a tuple does not have to be the same type.
 It can’t assign value already existing element.
The following examples shows

4.2.8 Dictionary literal:


 A dict literal is created by a key-value list with { }’s. A keys is separated with colon (: )
and the key : value pairs are separated with commas ( , ).
 An empty literal is { }

The following example shows:


4.3 constants in python
There are no constants in python. Instead use a variable and don’t change it.

4.4 Identifiers and Reserved words


Python Identifiers:

A Python identifier is a name used to identify a variable, function, class, module, or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores, and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language. Thus Manpower and manpower are two different
identifiers in Python.

Here are following identifier naming convention for Python:


Class names start with an uppercase letter and all other identifiers with a lowercase letter.
Starting an identifier with a single leading underscore indicates by convention that the identifier
is meant to be private.

Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.
4.5 Data types

Data types in Python


Every value in Python has a datatypes. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are listed below.

Python datatypes are classified into two categories.


1. Simple Datatypes
- int
-float
-complex
-bool
-str
2. Compound Datatypes
-list,
-tuple
-set,
-frozenset
-dictionary

There are 3 numeric types in python.


1. int
2. float
3. complex

Python Numbers

Integers, floating point numbers and complex numbers fall under Python numbers category.
They are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and the is
instance() function to check if an object belongs to a particular class.

Ex:
Python List

List is an ordered sequence of items. It is one of the most used datatypes in Python and is very
flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within
brackets [ ].
a = [1, 2.2, 'python']
We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts
form 0 in Python.

Ex:

Python Tuple

Tuple is an ordered sequences of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically.
It is defined within parentheses () where items are separated by commas.

Ex:

Python Strings

String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
s = "This is a string"
s = '''a multiline
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.

Ex:
Python Set
Set is an unordered collection of unique items. Set is defined by values separated by
comma inside braces { }. Items in a set are not ordered.

We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates.
Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [] does
not work.
Ex:

Python Dictionary
Dictionary is an unordered collection of key-value pairs. It is generally used when we
have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the
key to retrieve the value.

In Python, dictionaries are defined within braces {} with each item being a pair in the form key:
value. Key and value can be of any type. We use key to retrieve the respective value. But not the
other way around.

What is type conversion or casting?


- Data can be converted from one type to another type is called type
conversion or casting.
- Python is an object oriented programming language so this
conversion is done using constructor functions of class.
1. int() : constructs an integer using integer,float and string value.
2. float() :constructs a float using float,string
3. str() :constructs a string using string,integer and float value
Examples:
Float convertion:

4.6 Operators
In python operator is a symbol which is used to perform particular operation a specified
operator. The following types of operators
1. Arithmetic operators
2. comparisons operator
3. logical operator
4. Assignment operators
5. Membership operators
6. Bitwise operator
7. Identity operators

4.6.1 Arithmetic operators:


An arithmetic operator performs mathematical operations like addition, subtraction, division and
multiplication.

Operato Meaning Example


r
+ Add two operands >>>5+4
9
- Subtract two operands >>>6 - 4
2
* Multiply two operands >>>2*10
20
/ divide the left oferend by right operand >>>5/2
2.5
% which will give us remindar part >>>5%3
2
// which will give integer part >>>5//3
1
** raised to the power >>>5**3
125
4.6.2 Comparisons operator

Operator Description Example


== If two operands values are equal, then the condition >>> 5==3
becomes true. False
!= values of two operands are not equal, then condition >>>5!=3
becomes true. True
> If the value of left operand is greater than the value >>>4>3
of right operand, then condition becomes true. True
< If the value of left operand is less than the value of >>>6<4
right operand, then condition becomes true. False
>= greater than equal: If the value of left operand is >>>5>=6
greater than or equal to the value of right operand, False
then condition becomes true.
<= less than equal: If the value of left operand is less >>>4<=6
than or equal to the value of right operand, then True
condition becomes true.

4.6.3 Logical operators


 Logical operators is Boolean expressions such as and, or, not.
 It is just a conditional test that a result is either True or False.

operato Description Example


r
and it two operands are true it become true >>> True and True
True
>>>False and True
False
or it two operands are non-zero then >>>True or False
condition becomes true. True
>>>False or False
False
not It is used to reverse the logical state of >>>not True
its operand. False
>>>not not not True
False

And Truth table:


operand1 operand2 Operand1 and operand2
True True True
False True False
True False False
False False False

Or Truth table
operand1 operand2 Operand1 or operand2
True True True
False True True
True False True
False False False

Not Truth table


operand not operand
True False
False True

4.6.4 Assignment operator:

Operator Description Example


= Assigns values from right side >>>x=20
operands to left side operand
+= It adds right operand to the left >>>x+=20
operand and assign the result to left
operand
-= It subtracts right operand from the >>>x-=20
left operand and assign the result to
left operand
*= It multiplies right operand with the >>>x*=50
left operand and assign the result to
left operand
/= It divides left operand with the right >>>x/=50
operand and assign the result to left
operand
%= It takes modulus using two operands >>>x%=50
and assign the result to left operand
**= Performs exponential (power) >>>x**=50
calculation on operators and assign
value to the left operand
//= It performs floor division on >>>x//=50
operators and assign value to the left
operand

Ex:

4.6.5 Membership operator


operator Description Example
in Evaluates to true if it finds a variable in >>>x=”python”
the specified sequence and false >>>’p’ in x
otherwise. True
not in Evaluates to true if it does not finds a >>>x=”python”
variable in the specified sequence and >>>’z’ in x
false otherwise. False

Ex:

4.6.6 Bitwise operators

Operator Description Example


& Operator copies a bit to the result if it >>>10&20
exists in both operands 0
| It copies a bit if it exists in either >>>10|20
operand. 30
^ It copies the bit if it is set in one >>>10^20
operand but not both. 30
~ It is unary and has the effect of 'flipping' >>>~20
bits. -21
<< The left operands value is moved left by
the number of bits specified by the right >>>10<<2
operand. 40
>> The left operands value is moved right
>>>10>>2
by the number of bits specified by the
2
right operand.

Ex:

4.6.7 Identity operators

Operator Description Example


is Evaluates to true if the variables on >>>x=”hello”
either side of the operator point to the >>>y=”hello”
same object and false otherwise. >>>x is y
True
is not Evaluates to false if the variables on >>>x=”hello”
either side of the operator point to the >>>y=”hello”
same object and true otherwise. >>>x is not y
False
Ex:

4.7 Strings in Python


String:
A string is a sequence of characters. A character is simply a symbol. For example, the English
language has 26 characters. Computers do not deal with characters; they deal with numbers
(binary). Even though you may see characters on your screen, internally it is stored and
manipulated as a combination of 0's and 1's.This conversion of character to a number is called
encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular
encoding used.
In Python, string is a sequence of Unicode character. Unicode was introduced to include every
character in all languages and bring uniformity in encoding. You can learn more about
Unicode from here.
Example:
P=”Python is easy to learn”
Print (P)
Creation of string:
Strings can be created by enclosing characters inside a single quote or double quotes.
Even triple quotes can be used in Python but generally used to represent multiline strings and
docstring
Ex:

P Y T H O n
0 1
2 3 4 5

Indexing in Strings
The index () method returns the index of a substring inside the string (if found). If the
substring is not found, it raises an exception.
The syntax of index() method for string is:
str.index(sub[, start[, end]] )
index () Parameters
 The index() method takes three parameters:
 sub - substring to be searched in the string str.
 start and end(optional) - substring is searched within str[start: end]

Return Value from index ()


 If substring exists inside the string, it returns the lowest index in the string where
substring is found.
 If substring doesn't exist inside the string, it raises a Value Error exception.
The index() method is similar to find() method for strings
The only difference is that find() method returns -1 if the substring is not found,
whereas index() throws an exception.

Example:

Slicing the Strings


We can also call out a range of characters from the string. Say we would like to just print the
word Shark. We can do so by creating a slice, which is a sequence of characters within an
original string. With slices, we can call multiple character values by creating a range of index
numbers separated by a colon :
Ex:

When constructing a slice, as in [0:8:10], the first index number is where the slice starts
(inclusive), and the second index number is where the slice ends (exclusive), which is why in our
example above the range has to be the index number that would occur just after the string ends.
Checking Membership
We can test if a sub string exists within a string or not, using the keyword in. Some of the
commonly used ones are function returns an enumerate object. It contains the index and value of
all the items in the string as pairs. This can be useful for iteration.
Ex:

In above example hyd in a hence it return true, It contains the index and value of all the items in
the string as pairs. This can be useful for iteration.
Comparing Strings
You can use ( > , < , <= , <= , == , != ) to compare two strings. Python compares string
lexicographically i.e. using ASCII value of the characters.
Suppose you have str1 as "Mary" and str2 as "Mac" . The first two characters from str1
and str2 ( M and M ) are compared. As they are equal, the second two characters are compared.
Because they are also equal, the third two characters ( r and c ) are compared. And because 'r'
has greater ASCII value than 'c'
Ex:

In above example x is python and y is also python when we compare these two it return True
Using the == (equal to) operator for comparing two strings

Example2:

Strings are Immutable


One final thing that makes strings different from some other Python collection types is that you
are not allowed to modify the individual characters in the collection. It is tempting to use
the [] operator on the left side of an assignment, with the intention of changing a character in a
string. For example, in the following code, we would like to change the first letter of greeting.
Splitting and Joining Strings:
Python program to Split a string based on a delimiter and join the string using another delimiter.
Split a string can be quite useful sometimes, especially when you need only certain parts of
strings. A simple yet effective example is splitting the First-name and Last-name of a person.
Another application is CSV(Comma Separated Files). We use split to get data from CSV and
join to write data to CSV.
In Python, we can use the function split() to split a string and join() to join a string. For detailed
article on split() and join() functions, refer these : split() in Python and join() in Python
Ex:

Ex:

In above example when we are splitting the string ”Python+Java is Jython” is splitting by using
built in function called split and it returns output in the format of list because these are always
represent in list only, when we pass an argument it won’t effect on our output it returns in list
format

String Testing Methods:

Python has a set of built-in methods that you can use on strings. All string methods return
new values. They do not change the original string. There are number of methods defined
in Python to work with strings.

capitalize () - Returns the string with first letter capitalized and the rest lowercased.
Ex:

center () - Center the string within the specified width with optional fill character.
Ex:

count() - Count the non-overlapping occurrence of supplied substring in the string.


Ex:

find() - Return the index of the first occurrence of supplied substring in the string. Return
-1 if not found.
Ex:

index() - Return the index of the first occurrence of supplied substring in the string. Raise
ValueError if not found.
Ex:

isdigit() - Return true if the string is non-empty and all characters are digits
Ex:
isalpha() - Return true if the string is non-empty and all characters are alphabetic.
Ex:

isdecimal() - Return true if the string is non-empty and all characters are decimal
characters.
Ex:

islower() - Return true if the string has all lowercased characters and at least one is cased
character.
Ex:

isupper() - Return true if the string has all uppercased characters and at least one is cased
character.
Ex:
lower() - Return a copy of all lowercased string.
Ex:

replace() - Replace all old substrings with new substrings.


Ex:

title () - Return a title (first character of each word capitalized, others lowercased) cased string.
Ex:

upper() - Return a copy of all uppercased string.


Ex:

Formatting the Strings


Python uses C-style string formatting to create new, formatted strings. The "%" operator is used
to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string,
which contains normal text together with "argument specifiers", special symbols like "%s" and
"%d".
Let's say you have a variable called "name" with your user name in it, and you would then like to
print (out a greeting to that user.)

Here are some basic argument specifiers you should know:

%s - String (or any object with a string representation, like numbers)


%d - Integers
%f - Floating point numbers
%.< Number of digits>f - Floating point numbers with a fixed amount of digits to the right of the
dot.
%x/%X - Integers in hex representation (lowercase/uppercase)

Ex:

Output formatting
Some of the time we might want to organize our output to make it look appealing. This should
be possible by utilizing the str.format() method. This method is visible to any string object.
Ex:
Here the curly braces {} are utilized as placeholders. We can determine the order in which it is
printed by utilizing numbers (tuple index).
Ex:

We can even utilize keyword arguments to organize the string.


Ex:

Number formatting

Type Meaning
d Decimal integer
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lower case)
X Hexadecimal format (upper case)
n Same as 'd'. But it utilizes current locale setting for number separator
e Exponential notation. (lowercase e)
E Exponential notation (uppercase E)
f Displays fixed point number (Default: 6)
F Same as 'f'. But shows 'inf' as 'INF' and 'nan' as 'NAN'
g General format. Rounds number to p significant digits. (Default precision: 6)
G Same as 'g'. But changes to 'E' if the number is vast.
% Percentage. Products by 100 and puts % toward the end.

The below example gives the simple view of number formatting


Example:
Output:

Example:

Output:

Explanation:
in the principal statement, {:5d} takes a integer argument and assigns a base width of 5. Since,
no arrangement is determined, it is adjusted to one side.
In the second statement, you can see the width (2) is less than the number (1234), so it doesn't
take any space to the left but also doesn't truncate the number.
In contrast to integers, floats has both whole number and decimal parts. Also, the mininum width
characterized to the number is for the two parts overall including ".".
In the third statement, {:8.3f} truncates the decimal part into 3 places rounding off the last 2
digits. Also, the number, now 12.235, accepts a width of 8 in general leaving 2 spots to one side.
On the off chance that you need to fill the rest of the spots with zero, setting a zero preceding the
configuration specifier does this. It works both for numbers and buoys: {:05d} and {:08.3f}.
The below example gives the use of sign operator

Output:

Alignment

Type Meaning

< Left aligned to the remaining space

^ Center aligned to the remaining space

> Right aligned to the remaining space

= Forces the marked (+) (- ) to the furthest left position

Example:
Output:

the below example will gives the strings with alignment


example:

Output:
sort () in Python
Like C++ sort(), Java sort()and other languages, python also provides built in function to sort.
The sort function can be used to sort the list in both ascending and descending order. To sort the
list in ascending order.
Syntax
List_name. Sort()
This will sort the given list in ascending order. This function can be used to sort list of integers,
floating point number, string and others.

Python Naming Conventions


1. General
 Avoid using names that are too general or too wordy. Strike a good balance between the
two.

Bad:data_structure,my_list,info_map,dictionary_for_the_purpose_of_storing_data_repres
enting_word_definitions
 Good: user profile, menu options, word definitions
 Don’t be a jackass and name things “O”, “l”, or “I”
 When using Camel Case names, capitalize all letters of an abbreviation (e.g. HTTP
Server)
2. Packages
 Package names should be all lower case
 When multiple words are needed, an underscore should separate them
 It is usually preferable to stick to 1 word names
3. Modules
 Module names should be all lower case
 When multiple words are needed, an underscore should separate them
 It is usually preferable to stick to 1 word names
4. Classes
 Class names should follow the UpperCase CamelCase convention
 Python’s built-in classes, however are typically lowercase words
 Exception classes should end in “Error”
5. Global (module-level) Variables
 Global variables should be all lowercase
 Words in a global variable name should be separated by an underscore
6. Instance Variables
 Instance variable names should be all lower case
 Words in an instance variable name should be separated by an underscore
 Non-public instance variables should begin with a single underscore
 If an instance name needs to be mangled, two underscores may begin its name
7. Methods
 Method names should be all lower case
 Words in an method name should be separated by an underscore
 Non-public method should begin with a single underscore
 If a method name needs to be mangled, two underscores may begin its name
8. Method Arguments
 Instance methods should have their first argument named ‘self’.
 Class methods should have their first argument named ‘cls’
9. Functions
 Function names should be all lower case
 Words in a function name should be separated by an underscore
10. Constants
 Constant names must be fully capitalized
 Words in a constant name should be separated by an underscore
5. Programming Structures
The Control flow of the programs is the order. In python the control flow is divided into
Conditional statements, looping statements and function calls.
The if, if … else … and if ..elif … else …. is a conditional and for and while are loops.
5.1 Flow Control (loops and conditional)
The following diagram are a control flows

Flow Controls

Conditional statements
1. if Loops statements Controlling statements
1. While 1. Break
2. if .. else
2. for 2. Continue
3. if ..elif .. else
3. pass
5.1.1 Conditional statements
If statements:
In Python, if condition is used to verify whether the condition is true or not.
Syntax:-
if condition:
body;
Condition is a Boolean expression, condition is true it execute the body part, condition is false it
doesn’t execute the body part.
Ex: the following example read a value from keyboard and store into x whether the if condition
is check true or not.

In above example when we are going to check whether the given condition true it returns the if
Block Statement
Example 2: the following example check bit wise condition
The above example, 1 means true so condition is true body part execute.
Example 3: the following example check a character condition is true or not.

The above example 4 ways conditions check, 1. If “true” is a characters is true body part
executed. 2. If ‘nit’ is single quote character also condition true so body part execute. 3. If true: it
is not a character checking, is a variable so it is NameError. 4. If True: True is predefined
keyword so condition is true.
if else statement:-
It construct if then else statement’s.
Syntax:-
if condition:
Body1
else:
body2

if condition is true, execute the body1. If condition false, execute the body2.
Example 1: the following example checking condition is true or not.

In above example when the type of input is str then it will gives condition is true and, if input
type is int it gives false statement
Example 2: the following example shows a False keyword checking condition is true or not.

Explanation:the above program if condition is False so it execute else body part.

If..elif..else:-
In python construct if –than – else general format.
Syntax:-
if condition1:
body1;
elif condition2:
body2;
elif condition3:
body3;
-
-
-
Elif condition(n-1):
Body(n-1)

else:
body(n)

if condition1 is True, execute body1 otherwise elif condition2 is true, execute body2 otherwise
… and so on until it either find a condition is true that part execute or false it execute else clause
body(n).
Example 1: the following example calculate student average marks and assign a grade
values.
Explanation: calculate the average value and store avg value. Checking the avg value until
condition is true and store a grade value. It avg value is above 50 and below 60 so grade is C+.

Example 2: the following example how to execute else body part.


Explanation: the avg value is 33 so all elif condition false so directly execute else body part.
Note: there is no switch case statement in python. Instead multiway branching as series of if
..elif test to done. Dictionaries and lists can be built at runtime are more flexible but it hardcoded
logic.
Example 3: the following example price of fruits checking

It more complicated actions you can code in if statement but it dictionaries are good at
associating values with key.

5.1.2 Looping Statements:

While statement:-
While is explain same several languages. While look like a
Syntax:-
while condition:
body part;

Condition is a Boolean expression, condition is true, it execute a body part repeatedly until
condition is false otherwise condition is false, it doesn’t execute the body part.
Example 1: the following example sum of first 10 natural numbers.

Explanation: while condition true when i=1, it execute a while body part, when i=11 condition
is false it come out the while part.
While loop with else statement:-
There is a structural similarity between while and else statement. Both have a block of
statement(s) which is only executed when the condition is true.
Syntax:-
While condition:
Body
else:
elsebody
Condition is a Boolean expression, condition is true, it execute a body part repeatedly until
condition is false otherwise condition is false, it doesn’t execute the elsebody part.
Note: else part is optional of the while loop and not often used. Because as long as there is no
break in the body.
Syntax:
While condition:
Body
elsebody
There is no mention the else clause in above syntax. You may confusing don’t worry about this
syntax. It is useful in some situations.
Two special statements break and continue can be used in the body of a while loop. If break is
executed, it immediately terminates the while loop and not even the elsebody (if there is) is
executed. If continue is executed, it causes the remainder of the body to be skipped over;
the condition is evaluated again, and the loop proceeds as normal.

Example 1:
Here in above example
it is clear the when the input
value is less than 3 and the
output incremented by
using 1 and the resultant
value should be inside and 1
and 2 else block is used
For printing the statement
Example 2: the following
example calculate the
avg marks and displayed
by using break with else
statement

Explanation: the above program calculate the average and condition check, is true so break
statement execute doesn’t display the else clause body part.
for loop Statement:-
In python, for loop is different from other languages. In general initialize, condition check and
increment and test a variable on each iteration. Python, for loop iterates over the values returned
by any iterable object that is any object that can yield a sequence of values.
For example, for loop can iterate over every element in a list, tuple or a string but an iterable
object can also be a special function called range or special type of function called a generator or
generator expression.
Syntax:-
for value in sequence:
body

Example 1: the following example, read list items and calculate length of the word.
In above example for loop is used to access the each and every element of list by using that we
Find the length of every element of a list
Example 2: the following example display the first 10 natural numbers squares by using
generator expression

for loop with else:-


for loop with else is like a while loop with else. In for loop, else clause is optional.
Syntax:
for item in sequence:
Body
else:
else_part
body is execute when for loop read each elements of sequence. Item is read to be the first
element of sequence and body is executed. Item is read to be second element of sequence and
body is executed and so on up to last element of the sequence. The else part is optional. Like the
else part of the while loop. It is rarely used. Break and continue do the same thing in a for loop as
in while loop.

Example: 1
In above example by using for loop we can access the every element and by using that we can
print the number by using for loop
The range function:
The range() function has takes two sets of arguments.
range(stop) :
stop:Number of integers to generate, starting from zero.
Example: range(5) is [ 0,1,2,3,4]
Syntax:
range([start],stop[,step])
start: starting number of sequence
stop: generates a sequence numbers up to, but not include this.
step : difference between each numbers in the sequence.

Note: the following points to follow the rules of range function


 All arguments must be integers.
 All arguments can be a positive or negative.
 Range() starting index is 0 means list indexes start at 0 not 1.

The range function doesn’t build a python list of integers instead of it creates a range object that
produces integers on demand. It is useful when you are using explicit loops to iterate over really
large list. For example range(10000000) , which takes up only small amount of memory and
generates a sequence of integers from 0 up to 10000000 as needed by the for loop.
Example 1: the following example simple read elements 1 to 4 and prints
In above example by using for loop we can access the every element and by using that we can
print the number by using for loop here range function is used to print the numbers in range
function starting point is included and ending point is excluded
Example: the following example list items find the negative numbers and displayed

Explanation:declare list items in x and use a range command together with the len command on
the list to generate a sequence of indices for use by the for loop. The above program print out the
all the position in the list where it find the position of negative numbers.
More details about range function:
If you use range with two numeric arguments, the first argument is the starting number for the
resulting sequence, and the second number is the number the resulting sequence goes up to (but
doesn’t include)
Examples:
Why list value range (8, 1) is empty? To count backward, or to count by any amount other than
1, you need to use the optional third argument to range, which gives a step value by which
counting proceeds. Understand the following examples

The sequence returned by range always include the starting value given as an parameter to range
and never include the ending value given as an argument.
5.1.3 Break and Continue Statement:-
Break statements:
The break and continue statements can alter the flow of a normal loop. The break
statement is used to break out of a loop statement i.e. stop the execution of a looping statement.
It breaks the function even if the loop condition has not become false or the series of objects not
been fully iterated over. Loops iterate over a block of code until test expression is false, but
sometimes we wish to finish the current iteration or even the whole loop without checking test
expression.

Syntax:-
Break
Example: the following example read the string and particular time exit the loop.
In above example if letters match with the given string it breaks the condition and prints the
output inside for loop
Example 2:the following example calculate the total marks and pass or fail

Explanation: for loop read list of items, the body code execute and if condition checking any
value below 35 condition true and assign k value is 1 and break statement exit the for loop.
Continue Statement:-
The continue statement principle an immediate jump to the top of the loop. Sometimes it also lets
you avoid statement nesting.

Example 1:the following example uses continue to skip odd numbers

Explanation:
It prints all even numbers less than 10 and greater than or equal to 0. Remember, 0 means false
and % isthe remainder of division (modulus) operator, so this loop counts down to 0, skipping
numbers that aren’t multiples of 2—it prints 8 6 4 2 0:

5.1.4 Pass and Assert Statement


Pass statement:
The pass statements is often used. If you want to code an infinite loop that does nothing each
time through, do it with a pass. When the body is just an empty statement, python gets stuck in
this loop. The pass statement as none is to object (an explicitly nothing).

Explanation: the above program infinite loop running

Assert statement:
Assert is a Debugging checks. An assert statement introduced in python 1.5. It is mostly
syntactic shorthand for a raise.
Syntax:
assert<test><data>
<data> part is an optional

Example: the following example to raise a assert error


Data Structures (List,tuples,set,dictionaries)

Agenda

1. What is list?
2. Why use list in python?
3. Creating list?
4. Different types of creation list.
5. Accessing list
6. Changing values of list item
7. Deleting list
8. operations on list
9. methods on list
10. function on list
11. nested list
12. advantage of list
13. list comprehension

6.1.1What is List?

List is a sequence of mutable object in python.

What is mutable object?

A mutable object is an object whose values can change.

6.1.2 Why use list in python?

In Python list is the most basic data structure each element of a list is assigned a number -
its position or index. The first index is zero, the second index is one, and so on. In addition,
Python has built-in functions for finding the length of a sequence and for finding its largest and
smallest elements.

Advantages of list are as follows


 List are allowed duplicate elements
 We can modify the elements of list
 We can convert list into tuple
 List have some related features with strings and Regular Expressions in python
 We can use list to perform Stack and pop operations.

6.1.3 Creating a list:


A list is a collection of different values, usually used for storing same values. Its functionality is
similar to arrays in other programming like C language, the list contains items separated by
commas and enclosed within square brackets [ ].

Example: A list is created with a comma separated list of values.

Example: Creation of list with dynamic input

6.1.4 Different ways of creation list.


To create a list by using built-in function list( )
Syntax: list (iterable):
a. Without argument passed to list function, it created empty list

Example:

b. With argument pass to List function, the argument is a sequence (string, list or tuple).

Example:
c. Create a list with mixed data items. To find which type of object ,we use the built-in
function type function
Example:

6.2.5 Accessing a list


Accessing elements of List:
To access elements or data items of list we use the following ways they are as follows
1. Indexing List
2. Accessing elements using loops
3. Slicing of List
1. Indexing lists:
 List follows zero based index. i.e. index of first element is zero.
 List supports both +ve and -ve indexes.
 +ve index meant for Left to Right
 -ve index meant for Right to Left
Example:

>>>list1=[10,20,30,40,50,60]
Example 1:

2. Accessing list elements using loops


Using for loop:
Example 1: using for loop

Output:

Example 2: using while loop


Slicing In List:
Slicing is define as when we want extract part of list we use a method called slicing
“:”( colon) is used perform the slicing operations, the first character has index 0 and last
character has index -1

Syntax: list2= List1 [start: stop: step]

List1[start] It indicates the index where slice has t o start default value is 0
List1[end] It indicates the index where slice has to end
List1[start: end: step] It indicate the index where to start and end including increment
List1[start:] items start through the rest of the list
List1[:end] items from the beginning through end
List1[:] a copy of the whole list
Examples:

6.1.5 Changing values of list elements:


We can change one of the elements with new value in list.

Example: the following example to modify the list

Example 2: we can change maximum element in the list.

Output:

We can’t extend a list using index.


Example 3: changing value using slice operator

6.1.7 Deleting list

Deleting a list, it is possible to delete individual elements of a list by using python built-
in statement del.
del target_list;
Deletion of a target list recursively deletes each target, from left to right.
Example 2:
Delete element using slice operator.

Example 3: delete minimum element in the list

Output:
6.1.8 operations on list

List can perform following operations


Arithmetic operations:
Example: list perform concatenate operation by using + operator

Explanation: lst1 has declared 4 elements and an lst2 element has declared 4 elements we can
add two lists it returns 8 elements.
We don’t want return 8 elements we need add two elements it returns 4 elements.

Example:

We can’t perform on other arithmetic operations on list.

Multiplication operations on list:


Explanation: create an lst1 with 5 elements. Create an lst2 multiply with 5 of lst1 it returns 25
elements with same list repeated lst1 5 times.
So we don’t want to create 25 elements, we need create 5 elements with multiply each element.

Example:

Output:

Comparison operations on list:

1. The comparison operator starts with a first element of each tuple. Don’t compare to < or
> or = of first element then it proceed to the second element and so on.

Example:
Explanation: lst1==lst2 is check first element (1==4) condition false it returns false then it is
not going to next element.
lst1>lst2 is compare first element condition (1>4) is false it return false then it is not going to
next element.
lst1<=lst2 is compare first element condition (1<=4) is true then it is not going to next element.

Example 2:

Explanation:

Logical operator on list:


Membership operators on list:

Example: the following example to compare the elements

Example 2: to find list of elements to equal and store in another list.


Output:

Bitwise operator on list:


We can perform only integer values. We can’t perform entire list and string other objects.
Example 1:

Example: perform programmatically


Output:

6.1.9 methods on list


Using list methods gives to manipulate the data and stored in the list effectively. The following
table is list methods
Method Description
append() It used to Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
Returns the number of elements with the specified
count() value
Add the elements of a list ,to the end of the current
extend() list
Returns the index of the first element with the
index() specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

1)Append ():
The append method is used for adding a single value at the end of the list.
Syntax:
list. append(x)
x must be a pass a single item,
Example:
Explanation:
In above example we are assign the values to a variable called List by using append we
are adding a value 7, it will added at the end of list

Example 2: the following example common elements to add another list.

Output:

Example: To add all elements to list up to 50 which are divisible by 10

2) extend():
The extend method is used for adding a multiple values at the end of the list.
Syntax:
list.extend(iterable)
Any iterable can passed an argument like string or list.
Example 1:
Example 2:

Explanation:
In above example we are assign the values to two variables called List and List 1by using
extend method we are extending two lists into one

Example:

Difference between extend and append methods:

Append:
 It appends any python object to the end of the list i.e last element in the list.
 The result of the list may be nested list and contain heterogeneous elements i.e list, string,
tuple, dictionary, set etc.
Extend:
 It accepts any iterable as its argument and makes the list larger.
 The resulting of the list is always single dimensional list i.e no nested list and it contains
heterogeneous elements in it.

Similarity of append and extend


 Both take single argument.
 Both modify the list in-place.
 The result both is None.

Example 1:

Example 2: Using + operator are equivalent to append and extend method.

3) Insert ():
The insert method is used to insert an item into the list at a required position. It takes two
values arguments, index position and the value to be inserted.
Syntax:
list.insert (index, item)
It takes two required arguments
Index is a position of the list.
Item is a value should be added in the list

Example 1:
Explanation:
To change the values in the list we use the respective index position of the item. For
changing a value the 0th element in we use the insert method

Example 2:

Example:

Note: If the specified index is greater than max index then element will be inserted at last
position. If the specified index is smaller than min index then element will be inserted at first
position.

4) remove ():
The remove ( ) method takes single argument, the item which is to be removed. It
removes the first occurrence of the given item in the list and returns an error if the item is not
present.
Syntax:
List.remove (item)
Example:
Explanation:
In above example if you want remove 6 from the list we use remove method

Example:

Example 3:

5) pop ():
The pop () method removes and returns the item from the list.
Syntax:
list.pop([index])

If no index is specified, list.pop() removes and returns the last item in the list.
If takes a single argument (index) and removes the item at the respective index position from the
list.

Example:

Explanation:
In above example by using pop method we can pop the last element of a list

Example 2:

Example: Python code for stack using list

Explanation:

In above example we append a element called 'machine learning', 'artificial intelligence'


by using append method it will added at the end of list similarly when we perform the pop
operation it will remove last element of list this entire process is called as Stack using List.
Difference between remove, pop and del list.

pop
- pop takes Index and returns Value.
-it delete only one item.
-it is a postfix method.

delete
- it takes index, removes value at that index, and returns nothing
-it is a prefix method.
- it delete multiple values.

remove
- remove takes value and removes first occurrence, and returns nothing.
-it delete only one item

Example:

6) Clear ():
The clear () method removes all the items from the list. It equivalent del list1[:]

Syntax:
list.clear()

Example:

Explanation:
In above example if you want clear all the elements of list we use the clearmethod
Example 2:

7) Index ():
The index method searches for the given item in the list and returns its index position. If
the given item is present more than once then index position of the first occurrence is returned.
Syntax:
list.index(x,[start[,end]])
Return zero-based index in the list of the first item whose value is equal to x.
The optional arguments start and end are interpreted as in the slice notation and are used to limit
the search to a particular subsequence of the list.

Example 1: positive index based


Example 2: negative index based

Example:

Explanation:
In above example we can find the position of python in a given list by using index
method
Note:
If the specified element not present in the list then we will get ValueError. Hence before
index ( ) method we have to check whether item present in the list or not by using in operator
Example 3:
8) count():
The count method is used for finding the number of occurrence of a particular item in a
given list.
Syntax:
list.count (item)
Return the number of times item appears in the list.
Example:

Example:

Explanation:
In above example we can find the number of occurrence of 1 is 1time, 2 is 4times, 4 is
0,and 3 is 2 times this counting is possible by count method

Example 3:
9) sort ():
The sort () method is used for sorting the items of a given list in specific order i.e.
ascending or descending. By default sort doesn’t require any arguments but it has two optional
keyword arguments:
Syntax:
list.sort(key=None, reverse=False)
key specifies a function of one argument that is used to extract a comparison key from each
element in iterable.
reverse take Boolean value. If set to True, then the list elements are sorted as if each
comparison were reversed.

Example:

Explanation:
In above example by using sort method elements of list are arranging in ascending order

Example:
Explanation:
Key=int means it converted all elements integer type after sorted elements.
Key= lambda x : x[1] it compare each sub list elements index 1 position and sorted.

Example 3:
Example 4:

Explanation: lst1 has string, sorting is each character wise sorting. When key=len it sorted
string length wise and reverse=True after sorting elements list it reversed.

Example 5:

Explanation:
String numeric values sort in list, it sort first digit value wise sorted. When key=int to pass a
keyword argument to function the entire list values converted into integer values after sorted
numeric value wise after list is reversed.

Example 6: the following example sorts a list from 2nd letter in the word by using lambda
function as key.
10) Reverse():
The reveres() method is used to reverse the order of the items in the list, it doesn’t return
any value.
Syntax:
list.reverse()

Example:

Explanation:
In above example we can find the reverse of list by using reverse method
Example:

Example:
Example:

11) Copy ():


The copy () method is used for making a copy of a list.
Syntax:
list.copy ()
Example:

Explanation:
In above example we can find the copy of list by using copy method
In python there are two ways of copying the items they are
 Shallow copy
 Deep copy
Shallow copy:
A shallow copy creates a new object which stores the reference of the original items of
list. Shallow copy doesn't create a copy of nested objects; instead it just copies the reference of
nested objects.
Example:

Deep copy:
In deep copy a copy of object is copied in other object. It means that any changes made to
a copy of object do not reflect in the original object.
Example:

6.1.10 function on list


Python interpreter has the following built-in functions that are always available.

Function Description
len(s) return the number of elements.
max(iterable, *[, key, default]) return the largest element in the iterable.
min(iterable, *[, key, default]) return the smallest element in the iterable.
It returns Boolean value, if there is exists an
any(iterable)
item in the sequence return True
It returns Boolean value; if all items exist in
all(iterable)
the sequence is true
Sums start and the items of an iterable from
sum(iterable[, start])
left to right and returns the total.
id(object) Return the “identity” of an object
reversed(seq) Return a reverse iterator.
Return the hash value of the object (if it has
hash(object)
one). Hash values are integers.
help([object]) Invoke the built-in help system.

len(s):
return the number of elements in the list.
Example:

max:
return the largest element in the iterable or the largest of two or more arguments..
Syntax:
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

If one positional argument is provided, it should be an iterable. The largest item in the iterable is
returned. If two or more positional arguments are provided, the largest of the positional
arguments is returned.

key specifies a function of one argument that is used to extract a comparison key from each
element in iterable.

Example:

Example2: the following example mixed type argument comparison elements.


min():
return the smallest element in the iterable or the smallest of two or more arguments.
Syntax:
min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

If one positional argument is provided, it should be an iterable. The smallest item in the iterable
is returned. If two or more positional arguments are provided, the smallest of the positional
arguments is returned.

key specifies a function of one argument that is used to extract a comparison key from each
element in iterable.
Example 1:

Any:
Syntax:
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False.
Example:

All:
Syntax: all(iterable)

Return True if all elements of the iterable are true


Example:
Sorted(iterable,*,key=None, reverse=False):
Return a new sorted list from the items in iterable. Here function takes two keyword arguments.
Key specifies a function of one argument that is used to extract a comparison key from each
element in iterable. Default value is None.
reverse take a Boolean value. If set True the list of element sorted and reversed elements

Example:

Difference between list.sort and sorted()

List.sort()
- List.sort() is nothing return but it modified original list.

Sorted()
- Sorted() is return a list with sorted elements but not modified original list

reversed(seq)
return a reverse iterator object. Seq must be an object.

Example 1:
Example 2:

sum(iterable[, start])
 Sums start and the items of an iterable from left to right and returns the total.
 The iterable’s items are normally numbers, and the start value is not allowed to be a
string.
 start defaults to 0.

Example 1:

Example 2: the following example string numerical values sum by using generator expression.

id(object):
Return the “identity” of an object. This is an integer which is guaranteed to be unique and
constant for this object during its lifetime.

Help([object])
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is
given, the interactive help system starts on the interpreter console.

6.1.11 nested list


A nested list is a list that appears as an element in another list. It is like a two dimensional
array.

Syntax:
List1= [ […..], [……], […..] etc.]

Example: the following example creation a nested list

Example 2: The following example to access a nested list.


Example 3: we can change to the nested list values.

Example 1: the following example customer order table, there is online and offline users stored
into another lists.
Output:

Example 2: the following example customer wise total price amount.

6.1.12 Comprehension on List

What is comprehension in python?

A comprehension is constructs that allow sequences to be built from other sequences. There are
three types of comprehension.
 List comprehension
 Dictionary comprehension
 Generator comprehension.

List comprehension:

List comprehension consists of square brackets containing an expression followed by for clause
and then zero or more for or if clauses.
Note: in list comprehension, we can’t assign value to variable. Assign operator not work in list
comprehension.
Syntax:

The expression can be anything, it means we can put all kinds of objects in lists and generated
new list after evaluation of the expression.
Example: the following example first 5 natural numbers cube values generated
We will generate single statement cube as follows.

Explanation:
First range function executed and then

The list comprehension constructs as the follows

1. list comprehension with conditionals


2. list comprehension with nested loops
3. list comprehension with nested list
4. List Comprehensions and Generator Expressions
List comprehension with conditionals:

List comprehensions can utilize conditional statement to modify existing list. We will create list
that uses mathematical operators, integers and range ( ).
There are two types
1. single if condition
2. multiple if condition
Single if condition:
Syntax:

If condition true execute the expression otherwise not executed


Example 1: the following example first 10 natural even numbers.

In above example it follows the following procedure


 First range function or domain get executed
 Second it checks the condition,
 Third Expression is evaluated
 Fourth it will return the whole list assign list1 variable.
Example 2: the following example to find the palindrome number or not

In above example
 First range function get executed
 p variable convert to string type after use str(p)[::-1] (slice operator) reversed after
convert integer and check condition true evaluated expression.
 It will return the whole list and assign list1 variable.
if...else With List Comprehension:
In List comprehensions we can use if and else condition also below examples give
us more details use of if..else Condition in list comprehension
Syntax:

if condition1 is true evaluated expression1, if condition1 is false expression2 evaluated.

Example 1: the following example to separated lists above 45 elements and below 45 elements.

Output:
Example 2: the following example to operate mixed operator multiply with 2 add with 2 and odd
numbers converted to negative.

Output:

Multiple if condition:

There are two types


1. Nested if condition
2. Nested if else condition.

Nested if condition:
Syntax:

All if conditions true the expression is evaluated otherwise not evaluated.

Example 1: the following example to display the between 50 to 100 numbers

Output:
Nested if else statement:
Syntax 1:

1. All conditions true and if condition1 true execute expression1, if condition2 true execute
expression2 execute and so on. All if condition1, condition2 … false it execute
expression and return None.
2. All if conditions false there are not checking condition1 and condition2.
Note: whenever we are write an expression append value to list and assign a value it is return
None and assign to list1.

Example 1: the following example to understand the expression

OUTPUT:
Syntax 2:

Here if condition1 true its evaluated expression1, if condition2 true its evaluated expression2
and so on. All if conditions false its evaluated expression.

Example:

Output:
list comprehension with nested loops
There are two ways
1. List comprehension with nested loops
2. List comprehension with nested loop and conditional
syntax:

Example: the following example first 5 non negative numbers multiply with 5 and added

Explanation:
Step1 first take i value 1(one) next goes another for loop str(i) convert string and read n value
and next expression executed.

Example 2: the following example multiply two list values


Output:

First for loop element multiply with each element with another for loop element its generated
3*3 elements generated.
List comprehension with nested loop and conditional

Example: the following example display a patterns

The following example to write a single line using list comprehension

Output:

List comprehension with nested list

Example: the following example to sum the sub list elements


Output:

Python List Comprehensions and Generator Expressions

 Generator expression is same as the list comprehension.


 A list comprehension executes immediately and returns a list.
 A generator expression returns an object generator that can be iterated over.
 A list comprehension enclosed with square brackets [ ].
 A generator expression enclosed with a parenthesis ( ).
 A list comprehension can access with index and slice operator.
 A generator expression can’t access with index and slice operator.
 Generator object take less size to compare list comprehension.
Example 1:
The following example difference way of creation comprehension:

List comprehension: Lst= [ x*2 for x in range(1,6) ]

Generator expression: Gen_exp= ( x*2 for x in range(1,6) )

Tuple comprehension: Tup_exp= tuple( x*2 for x in range(1,6) )

Example2:

The following example to find a type of object


Example 3: the following example to find the size of memory.

Example 4: the following example access by index


We can access elements list by index but we can’t access elements generator objects.

Example 5: by loops
We can access elements by loops.
Agenda

 What is tuple?
 Creating tuple?
 Different types of creation tuple.
 Why use tuple in python?
 Accessing tuple
 Tuple assignment
 Deleting tuple
 operations on tuple
 methods on tuple
 function on tuple
 nested tuple
 advantage of tuple compare to list
 tuple comprehension

6.2 Tuple
A tuple is a sequence of immutable in python object.

What is immutable object?


An immutable object is an object whose values can’t change.

6.2.1 Creating a tuple:


The tuple contains data items separated by commas and enclosed within parentheses ( ) it is
optional. Once a tuple is created we cannot add or remove items from the tuple. Tuple can store a
heterogeneous data items.

Example 1: a tuple is created with a comma separated list of values.

Or, tuple is created with a comma separated list of values using parentheses for quickly
understand in python code as tuple

Output:

Example 2: creating dynamic input


Output:

6.2.3 Different types of creation tuple.


The following points understand of creation a tuple
1. To create a single element, we have to place end of comma because it act like a string. To
find which type of object we use the built-in type function
Examples:

2. To create a tuple by using built-in function tuple().


a. Without argument passed to tuple function, it created empty tuple.
Example:

b. With argument pass to tuple function, the argument is a sequence (string, list or
tuple).
Example:

Note: tuple is the name of a constructor; we should avoid using it as a variable


name.
c. Create a tuple with mixed data items; tuple can hold both homogeneous and
heterogeneous values.

d. Create a tuple with data items as list, tuple, string and int

6.2.3 Why use tuple in python?

6.2.2 Accessing a tuple


We want to access elements of a tuple we use a square brackets along with the index.
Tuple has follows positive and negative index,
 positive index start with 0,1,2,… and start from left to right,
 negative index start with -1,-2,-3 … and right to left.
To access data items of a tuple we use the following ways
 indexing a tuple
 iteration using loops
 slicing of tuple
Indexing a tuple:
Example 1:
Example 2: we have to create tuple with data items a list, tuple and number

Iteration using loops:


Example 1: accessing tuple using looping statements

Example2: using while loop

Output:
6.2.3 Accessing elements using slicing operator:

What is slice in python?


In any iterable object (ex: string, list, tuple, etc) allows to slice and return a substring or sublist
of its data
Formatting for slicing:
Iterable_name [start:stop:step]
Start is the first index of the slice. Default index is 0.
Stop is the last index of the slice. Default index is len(iterable_name)
Step is the index increment at end point.

“:”( colon) is used perform the slicing operations, The first character has index 0 and last
character has index -1

Example:
Example: tuple assign elements through slice operators.

6.2.4 Tuple assignment

Assignment of tuple can be done in two ways


1. tuple packing
2. tuple unpacking
tuple packing:
The values on the left side of assignment operator (=) are called tuple packing.

Example:
tuple unpacking:
the values on the right side of assignment operator (=) are called tuple unpacking

Example 1:

Example 2: the following example assign element into tuple

Explanation: we can assign tuple element within list.

Example 3: the following example to swap a variables single statement

Note: tuple can’t directly assign an item because tuple an immutable data type. i.e you can’t
modify the elements.

Example: the following example to assign the value within list


Example : the programmatically

Output:

Example:

In above example, we can concatenate tuple with addition (+) operator as follows example
Example 2: the following example we can list data into a tuple.

6.2.5 Deleting a tuple


Deleting a tuple, it is not possible to delete individual elements of a tuple. We can delete the
whole tuple itself by using del statement.

Example:

In above program, we can delete items

6.2.6 Operations on Tuple:


Arithmetic operations
Tuple only can operate addition and multiplication.
Example 1: The following example addition operator

The above example tup1 and tup2 has 5 element, we can add a two tuples it returns 10 elements.
But here we need a 5 elements new tup3 with addition of tup1 and tup2 as the following example

Output:

Example 1: the following example multiplication operators

Above example tup1 has five elements. Whenever you can multiply tup1 with 5 it returns 25
elements in a tuple.
The above example don’t want to 25 elements, we need 5 elements multiply with each element
by 5 the follows the program
Output:

We can also perform all operations

Comparison operations on tuple:


2. The comparison operator starts with a first element of each tuple. Don’t compare to < or
> or = of first element then it proceed to the second element and so on.

Example 1:

Explanation: tup1==tup2 is check first element condition false it returns false then it is not
going to next element.
Tup1>tup2 is compare first element condition is false it return false then it is not going to next
element.
Tup1<tup2 is compare first element condition is true then it is not going to next element.

Example 2:
Explanation:

Example 3: the following example programmatically.

Output:

Logical operators on tuple:


Example 1:
Example 2:

In above problem, we can perform through programmatically by converting into list.

Output:

Membership operators on tuple:


Example 1: the following example to compare the elements
Example 2:

Output:
6.2.7 Methods on tuple
In tuple there are two methods
1. Count
2. Index

Index(x)  it returns the index of first item that is equal to x.

Count(x)  return the number of elements is equal to x.

Example:
6.2.8 Built-in function on tuple:

Python interpreter has the following built-in functions that are always available.

Function Description
len(s) return the number of elements.
max(iterable, *[, key, default]) return the largest element in the iterable.
min(iterable, *[, key, default]) return the smallest element in the iterable.
It returns Boolean value, if there is exists an
any(iterable)
item in the sequence return True
It returns Boolean value; if all items exist in
all(iterable)
the sequence is true
Sums start and the items of an iterable from
sum(iterable[, start])
left to right and returns the total.
id(object) Return the “identity” of an object
reversed(seq) Return a reverse iterator.
Return the hash value of the object (if it has
hash(object)
one). Hash values are integers.
help([object]) Invoke the built-in help system.

len( tuple )  integer


It returns the number of elements in sequence.

Examples: the following example to find number of elements in a tuple


Example 2:

Max return the largest element in the iterable or the largest of two or more arguments..
Syntax:
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

If one positional argument is provided, it should be an iterable. The largest item in the iterable is
returned. If two or more positional arguments are provided, the largest of the positional
arguments is returned.

key specifies a function of one argument that is used to extract a comparison key from each
element in iterable.

Example1:

Example 2:

Example 3:
min  It returns smallest item in the sequence. It compare element through ascii value
syntax:
min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

If one positional argument is provided, it should be an iterable. The smallest item in the iterable
is returned. If two or more positional arguments are provided, the smallest of the positional
arguments is returned.
key specifies a function of one argument that is used to extract a comparison key from each
element in iterable.

Example 2:

Example 3:
any( tuple )  boolean
It returns Boolean value, if there is exists an item in the sequence return True.

all( tuple )It returns Boolean value; if all items exist in the sequence is true.

Sorted(iterable,*,key=None, reverse=False):
Return a new sorted list from the items in iterable. Here function takes two keyword arguments.
Key specifies a function of one argument that is used to extract a comparison key from each
element in iterable. Default value is None.
reverse take a Boolean value. If set True the list of element sorted and reversed elements.

Example:

reversed(seq)
return a reverse iterator object. Seq must be an object.

Example:

Example 2:
sum(iterable[, start])
 Sums start and the items of an iterable from left to right and returns the total.
 The iterable’s items are normally numbers, and the start value is not allowed to be a
string.
 start defaults to 0.
Example:

id(object):

Return the “identity” of an object. This is an integer which is guaranteed to be unique and
constant for this object during its lifetime.

hash(object):
Return the hash value of the object (if it has one). Hash values are integers.
Help([object])
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is
given, the interactive help system starts on the interpreter console.
>>>tup1=(1,2,3)
>>>help(tup1)
6.2.8 Nested tuple

Tuple within tuple creation is called a nested tuple.

Example: the following is creation of nested tuple

Example: the following example to access an elements nested tuple


6.2.9 Conversion tuple to other data types.

Example 1: the following example we convert tuple to other data type.

Example 2:
Note: nested tuple elements can’t convert to set.

Advantage of tuple compare to list

 Tuple is an immutable data type and list is mutable. Iterating through tuple is faster than
list.
 Tuples are more explicit with memory, while lists required overhead.
 Tuples in the background doing work the following example
>>> a, b=1,2
It is a tuple assignment. Python first constructs the tuple (1, 2) and then assigns pair wise
elements its corresponding variables.
 Tuple items can’t be added to or removed and item can’t be replaced but list can possible.
 Bitwise operator (&) can’t perform on tuple but works on list.
Comprehension on Tuples
1. Tuple comprehensions is using ( ) instead of list comprehensions which use [ ].

Example:
We write the following tuple comprehension by the help use of ( ) not a [ ].

A tuple comprehension is a special kind of function called a generator. If we want, we can use
conversion function as tuple().

Note: the following example understand the difference between list and tuple for accessing on
generator
Example: the following example once we have iterated over a tuple comprehension in any way,
we can’t iterate over its value again.

Example:

The above example both are equivalent for creation. First call the conversion function tuple( )
with the tuple comprehension without an extra ().

Key points comprehension on tuple:

1. Tuple comprehensions are a bit strange.


2. Writing a tuple comprehension inside tuple( ) function produces a tuple of correct values.
Agenda
1. What is Set
2. Why use set in python
3. Types of sets.
4. Creating Set
5. Different types of creations
6. Accessing Set
7. Deleting Set
8. Operations and methods on Set
9. Functions on Set
10. Nested set.
11. Comprehension on set.

6.3.1 What is set in python?

A set is an unordered collection of unique elements. It is enclosed with { }, Set objects


are mutable i.e. once we creates set object we can perform any changes in that object based on
our requirement.

6.3.2 Why use set in python?

If we want to represent a group of unique values as a single entity then we should go for set.
Set has following Advantages, They are as follows
 Duplicates are not allowed.
 Insertion order is not preserved.
 But we can sort the elements.
 Indexing and slicing not allowed for the set.
 Heterogeneous elements are allowed.
 Set objects are mutable i.e. once we creates set object we can perform any changes in that
object based on our requirement.
 We can represent set elements within curly braces and with comma separation
 We can apply mathematical operations like union, intersection, difference etc on set
objects.

6.3.3 Types of sets:

There are two types in python


1. Set
2. frozenset
1. set – it is a mutable and new elements can be added once sets are defined.

Example:

2. frozenset – it is an immutable and new element can be added after its defined.
We can’t use any of the mutation methods or operators. The constructor is named
frozenset: frozenset ( ), it can create an empty frozenset.
Frozenset can take a single argument. That is an iterator.

Example:

Example 2: we can’ take nested list of argument in frozenset

6.2.4 Creating set


The elements which is separated by commas and these elements are placed in curly braces {} in
a function set.

Note: if we write the set { [ ] }, python raises a


Type Error: unhashable type: ‘list’
6.2.5 Different types of creations

To create a set by using built-in function set( )

Syntax: set(iterable)
a. Without argument passed to set function, it created empty set

Example:

b. With argument pass to set function, the argument is a sequence (string or tuple).

c. Create with mixed arguments.

d. Create a set with mixed data items. To find which type of object ,we use the built-in
function type function
Note: we can’t store a nested list in a set but we can store a tuple.

List is mutable object that’s list can’t store a list of values.


e. Nested tuple creation in a set

The above example it created whole data in single tuple but we need different data type’s
creation with single arguments
6.3.5. Accessing Set
We can access set elements by using looping statement. There is no indexing and slice operator
on set.
Example 1: the following example read elements using for loop

Example 2: the following example read elements by using while loop. The set values converts
the set_iterator by using iter() method, to read values by using next() method.

Output:

6.3.6 Deleting Set:


We can delete the entire set by the help of del keyword as given below examples.
6.3.7. Operations and methods on Set
Checking operators:
Membership Operations:
As we know that membership operator is used to find whether the element is exist in that
set or not, If element is present it return True else return False
Example:

Identity Operation:
As we know that Identity operator is used to find whether two sets equal or not, If they
are identical it return True else return False
Example:

Comparison operator on set


We can compare operator and through set methods in python.
Equality and inequality operator:
Note: the equal comparison operator to must be equal two objects and values must be same.

Example 2: the following example we have unequal sets but compare values return results
correct form

When you compare element in python have a inbuilt methods is there as follows the methods.
Set.isdisjoint(other):
It return true, if the set has no common value with other.
Example:

Example: the following example to compare with other object like list, tuple.

Set.issubset(other)
It returns true every element is also in other. It is equivalent to set <= other, other, other other.
It returns false any one value miss in other.

Example1:

Set.issuperset(other)
It returns true, every other element value is also in set. Set >= other, set > other set >= other and
set != other.
Set.union(other, ...)
 It returns new set with elements from other.
 It added elements, it is like a=a+b+c but it is not work on + operand on set.
 It is equivalent to set1 | set2 | ... | setn

Note: when we are using | operator all must be set object.

Example: the following example we compare | operator

set1.intersection (set2, ..., setn)


 It returns new set with common to the set and all others.
 It is equivalent set1 & set2 & ... & setn
 We must pass all argument set object.

Example:
Example 2: the following example we compare & operator

set1.difference(set2, ..., setn):


 It returns new set with elements in the set that are not in the set2,… setn.
 It is equivalent set1 - set2 - ... – setn
 We can pass any object like (list, tuple) arguments.
Note: when we are using – (negative) operator all must be set object.
Example:

Example 2: the following example we compare – (negative) operator


set.symmetric_difference(other):
 It returns new set with elements in either the set or other but not both.
 It is equivalent set ^ other.
 We can pass any iterable object and it can take single argument.
Example:

Example: the following example by using ^ operator.

Note: there is a difference between methods and operators.


Method allows any iterable object for their arguments.
Operators must be requiring sets for both operands.
Example:
Both set and frozenset support set to set comparisons. Two sets are equal if and only if every
element of each set is contained in the other (each is a subset of the other).

The following table understands the method and operator

Method Operator
set1.intersection(set2) set1 & set2
set1.union(set2) set1 | set2
set1.difference(set2) set1 - set2
set1.symmetric_difference(set2
set1 ^ set2
)
set1.issubset(set2) set1 <= set2
set1.issuperset(set2) set1 >= set2

set mutation operation:

set.add(value) : appending a elements to set.

Note: the frozenset() we can’t work on mutation method it is an immutable.


Set.remove(value) :
It removes the element in a set. the element is not contained it will raise error KeyError.

Example:

Set.discard(value):
It removes the element from the set in its present. The element is not in the set there is no error
message.

Set.pop() :
Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.
Set.clear():
It removes all values from a set and it creates an empty set.

update operations for sets:


The following lists operations available for set that do not apply to immutable instances of
frozenset.
set1.update(set2,...set):
1. Adding a elements from set2,… setn.
2. It is equivalent to a set1 |= set2 | ... | setn.

Example 1:
Example 2:

set1.intersection_update(set2,...setn):
 update the common elements from all set.
 it is equivalent set1 &= set2 & ... & setn
Example:
Example 2: the following example to operand

set1.difference_update(set2,...setn):
 It updates the set when removing elements found in other.
 It is equivalent to set1 - = set2 - ... - setn
Example 1:

Example 2: the following example to operand


set1.symmetric_difference_update(set2):
 Update the set, keeping only elements found in either set, but not in both.
 It is equivalent to set ^= other operator.

Example 1:

Example 2: the following example through operand


Note: frozensets is similar to sets, but we can’t use any mutation methods or operators.

The following table we can understand the details information update methods and methods.

method operation update method


union Set1 |= other set2 update
intersection Set1 &= other set2 intersection_update
difference Set1 -= other set2 difference_update
symmetric_difference Set1 ^= other set2 symmetric_difference_update

6.1.9 Functions on set


len() :
syntax: len(x)
It returns the number of elements in x.

 There is no indexing and slicing in set.


 We can’t addition and multiplication on set.
sum(iterable[, start])
 Sums start and the items of an iterable from left to right and returns the total.
 The iterable’s items are normally numbers, and the start value is not allowed to be a
string.
 start defaults to 0.

Example:
Sorted(iterable,*,key=None, reverse=False):
Return a new sorted list from the items in iterable. Here function takes two keyword arguments.
Key specifies a function of one argument that is used to extract a comparison key from each
element in iterable. Default value is None.
reverse take a Boolean value. If set True the list of element sorted and reversed elements

Example: the following example string numerical values to sort.

Example 2: the following example integer values to sort.

max:
return the largest element in the iterable or the largest of two or more arguments..
Syntax:
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

If one positional argument is provided, it should be an iterable. The largest item in the iterable is
returned. If two or more positional arguments are provided, the largest of the positional
arguments is returned.
key specifies a function of one argument that is used to extract a comparison key from each
element in iterable.

Example 1:

min():
return the smallest element in the iterable or the smallest of two or more arguments.
Syntax:
min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

If one positional argument is provided, it should be an iterable. The smallest item in the iterable
is returned. If two or more positional arguments are provided, the smallest of the positional
arguments is returned.

key specifies a function of one argument that is used to extract a comparison key from each
element in iterable.

Any:
Syntax:
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False.
All:
Syntax: all(iterable)

Return True if all elements of the iterable are true

6.3.10 nested set:

 there is no nested in python we can frozenset inside set.

6.3.11 comprehension on set


We can construct a set/frozenset via comprehension as like list comprehension.

Syntax:

Set1 = {comprehension}
Fset1 = frozenset({comprehension})

Example 1:

Example 2: the following example comprehension frozenset

Agenda
12. What is Set
13. Why use set in python
14. Types of sets.
15. Creating Set
16. Different types of creations
17. Accessing Set
18. Deleting Set
19. Operations and methods on Set
20. Functions on Set
21. Nested set.
22. Comprehension on set.

6.3.4 What is set in python?

A set is an unordered collection of unique elements. It is enclosed with { }, Set objects


are mutable i.e. once we creates set object we can perform any changes in that object based on
our requirement.

6.3.5 Why use set in python?

If we want to represent a group of unique values as a single entity then we should go for set.
Set has following Advantages, They are as follows
 Duplicates are not allowed.
 Insertion order is not preserved.
 But we can sort the elements.
 Indexing and slicing not allowed for the set.
 Heterogeneous elements are allowed.
 Set objects are mutable i.e. once we creates set object we can perform any changes in that
object based on our requirement.
 We can represent set elements within curly braces and with comma separation
 We can apply mathematical operations like union, intersection, difference etc on set
objects.

6.3.6 Types of sets:

There are two types in python


3. Set
4. frozenset

3. set – it is a mutable and new elements can be added once sets are defined.
Example:

4. frozenset – it is an immutable and new element can be added after its defined.
We can’t use any of the mutation methods or operators. The constructor is named
frozenset: frozenset ( ), it can create an empty frozenset.
Frozenset can take a single argument. That is an iterator.

Example:

Example 2: we can’ take nested list of argument in frozenset

6.2.4 Creating set


The elements which is separated by commas and these elements are placed in curly braces {} in
a function set.

Note: if we write the set { [ ] }, python raises a


Type Error: unhashable type: ‘list’

6.2.6 Different types of creations


To create a set by using built-in function set( )

Syntax: set(iterable)
f. Without argument passed to set function, it created empty set

Example:

g. With argument pass to set function, the argument is a sequence (string or tuple).

h. Create with mixed arguments.

i. Create a set with mixed data items. To find which type of object ,we use the built-in
function type function
Note: we can’t store a nested list in a set but we can store a tuple.

List is mutable object that’s list can’t store a list of values.


j. Nested tuple creation in a set

The above example it created whole data in single tuple but we need different data type’s
creation with single arguments
6.3.5. Accessing Set
We can access set elements by using looping statement. There is no indexing and slice operator
on set.
Example 1: the following example read elements using for loop

Example 2: the following example read elements by using while loop. The set values converts
the set_iterator by using iter() method, to read values by using next() method.

Output:

6.3.6 Deleting Set:


We can delete the entire set by the help of del keyword as given below examples.
6.3.7. Operations and methods on Set
Checking operators:
Membership Operations:
As we know that membership operator is used to find whether the element is exist in that
set or not, If element is present it return True else return False
Example:

Identity Operation:
As we know that Identity operator is used to find whether two sets equal or not, If they
are identical it return True else return False
Example:

Comparison operator on set


We can compare operator and through set methods in python.
Equality and inequality operator:
Note: the equal comparison operator to must be equal two objects and values must be same.

Example 2: the following example we have unequal sets but compare values return results
correct form

When you compare element in python have a inbuilt methods is there as follows the methods.
Set.isdisjoint(other):
It return true, if the set has no common value with other.
Example:

Example: the following example to compare with other object like list, tuple.

Set.issubset(other)
It returns true every element is also in other. It is equivalent to set <= other, other, other other.
It returns false any one value miss in other.

Example1:

Set.issuperset(other)
It returns true, every other element value is also in set. Set >= other, set > other set >= other and
set != other.
Set.union(other, ...)
 It returns new set with elements from other.
 It added elements, it is like a=a+b+c but it is not work on + operand on set.
 It is equivalent to set1 | set2 | ... | setn

Note: when we are using | operator all must be set object.

Example: the following example we compare | operator

set1.intersection (set2, ..., setn)


 It returns new set with common to the set and all others.
 It is equivalent set1 & set2 & ... & setn
 We must pass all argument set object.

Example:
Example 2: the following example we compare & operator

set1.difference(set2, ..., setn):


 It returns new set with elements in the set that are not in the set2,… setn.
 It is equivalent set1 - set2 - ... – setn
 We can pass any object like (list, tuple) arguments.
Note: when we are using – (negative) operator all must be set object.
Example:

Example 2: the following example we compare – (negative) operator


set.symmetric_difference(other):
 It returns new set with elements in either the set or other but not both.
 It is equivalent set ^ other.
 We can pass any iterable object and it can take single argument.
Example:

Example: the following example by using ^ operator.

Note: there is a difference between methods and operators.


Method allows any iterable object for their arguments.
Operators must be requiring sets for both operands.
Example:
Both set and frozenset support set to set comparisons. Two sets are equal if and only if every
element of each set is contained in the other (each is a subset of the other).

The following table understands the method and operator

Method Operator
set1.intersection(set2) set1 & set2
set1.union(set2) set1 | set2
set1.difference(set2) set1 - set2
set1.symmetric_difference(set2
set1 ^ set2
)
set1.issubset(set2) set1 <= set2
set1.issuperset(set2) set1 >= set2

set mutation operation:

set.add(value) : appending a elements to set.

Note: the frozenset() we can’t work on mutation method it is an immutable.


Set.remove(value) :
It removes the element in a set. the element is not contained it will raise error KeyError.

Example:

Set.discard(value):
It removes the element from the set in its present. The element is not in the set there is no error
message.

Set.pop() :
Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.
Set.clear():
It removes all values from a set and it creates an empty set.

update operations for sets:


The following lists operations available for set that do not apply to immutable instances of
frozenset.
set1.update(set2,...set):
3. Adding a elements from set2,… setn.
4. It is equivalent to a set1 |= set2 | ... | setn.

Example 1:
Example 2:

set1.intersection_update(set2,...setn):
 update the common elements from all set.
 it is equivalent set1 &= set2 & ... & setn
Example:
Example 2: the following example to operand

set1.difference_update(set2,...setn):
 It updates the set when removing elements found in other.
 It is equivalent to set1 - = set2 - ... - setn
Example 1:

Example 2: the following example to operand


set1.symmetric_difference_update(set2):
 Update the set, keeping only elements found in either set, but not in both.
 It is equivalent to set ^= other operator.

Example 1:

Example 2: the following example through operand


Note: frozensets is similar to sets, but we can’t use any mutation methods or operators.

The following table we can understand the details information update methods and methods.

method operation update method


union Set1 |= other set2 update
intersection Set1 &= other set2 intersection_update
difference Set1 -= other set2 difference_update
symmetric_difference Set1 ^= other set2 symmetric_difference_update

6.1.9 Functions on set


len() :
syntax: len(x)
It returns the number of elements in x.

 There is no indexing and slicing in set.


 We can’t addition and multiplication on set.
sum(iterable[, start])
 Sums start and the items of an iterable from left to right and returns the total.
 The iterable’s items are normally numbers, and the start value is not allowed to be a
string.
 start defaults to 0.

Example:
Sorted(iterable,*,key=None, reverse=False):
Return a new sorted list from the items in iterable. Here function takes two keyword arguments.
Key specifies a function of one argument that is used to extract a comparison key from each
element in iterable. Default value is None.
reverse take a Boolean value. If set True the list of element sorted and reversed elements

Example: the following example string numerical values to sort.

Example 2: the following example integer values to sort.

max:
return the largest element in the iterable or the largest of two or more arguments..
Syntax:
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

If one positional argument is provided, it should be an iterable. The largest item in the iterable is
returned. If two or more positional arguments are provided, the largest of the positional
arguments is returned.
key specifies a function of one argument that is used to extract a comparison key from each
element in iterable.

Example 1:

min():
return the smallest element in the iterable or the smallest of two or more arguments.
Syntax:
min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

If one positional argument is provided, it should be an iterable. The smallest item in the iterable
is returned. If two or more positional arguments are provided, the smallest of the positional
arguments is returned.

key specifies a function of one argument that is used to extract a comparison key from each
element in iterable.

Any:
Syntax:
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False.
All:
Syntax: all(iterable)

Return True if all elements of the iterable are true

6.3.10 nested set:

 there is no nested in python we can frozenset inside set.

6.3.11 comprehension on set


We can construct a set/frozenset via comprehension as like list comprehension.

Syntax:

Set1 = {comprehension}
Fset1 = frozenset({comprehension})

Example 1:

Example 2: the following example comprehension frozenset


6.4 Dictionaries in Python
Agenda of Dictionaries

1. What is dictionary?
2. Why use dict in python
3. Creating dict
4. Different types of creations
5. Accessing dict
6. Change values in dict
7. Deleting dict
8. Operations of dict
9. Methods in dict
10. Functions on dict
6.4.1 What is Dictionaries?
Python Dictionaries are most advanced and powerful data collections. It has unordered
data collection of items having key, Value pair. In dictionaries key is immutable and value is
mutable
6.4.2 Why use Dictionaries in Python?
In python we are using dictionaries because of following advantage
 Duplicate keys are not allowed but values can be duplicated
 Dictionary is accessed using key.
 Slicing Nested Dictionary is not possible.
 Heterogeneous objects are allowed for both key and values.
 insertion order is not preserved
 Dictionaries are mutable
 Dictionaries are dynamic
 indexing and slicing concepts are not applicable
Note: In C++ and Java Dictionaries are known as "Map" where as in Perl and Ruby it is known
as "Hash"
6.4.3 Create Dictionaries:
It consists of some items and they separated by comma and placing inside curly braces {}
is mandatory. Every item consists of keys and the related value defined as a pair, key: value.
Syntax:
Var= {key: value, key1:value1}
Key is index of value
: is separator
Value is Data item
Example: How to create the empty Dictionaries
6.4.4. Different types of creations
Example: Create the empty Dictionaries with key and value pair

Example: Create the empty Dictionaries with tuples

Example: Create dictionary using mapping

Example: Create dictionary with two lists

Example: Create dictionary with two sets

6.4.5Accessing the key and values of dictionary:


How access elements in dictionary:
To access dictionary elements, you can use the familiar for loop along with the key to
obtain its value. Following is a simple example
Example: Accessing elements using keys
Example: Accessing elements using for loop

Example: Accessing elements using keys, values, items

Example: Accessing elements using keys, values using for loops

6.4.6. Changing the values of Dictionaries


In dictionaries we can’t change the keys because keys are immutable and values are
mutable, we can change the values as follows by given example

Example:
6.4.7. Deleting the Dictionaries
To delete dictionaries we use the del keyword and after deleting the dictionaries it raises
the error

Example: Deleting the dictionary using del keyword

6.4.8. Operations on Dictionaries


We can perform membership and Identity operations in dictionaries they are as follows

Membership Operations Dictionary:

Example: Following Example gives us membership operations in dictionaries


Member ship operations is done according to key and not as per values here we are checking
whether the key is membership of given dictionaries or not

Identity operations in Dictionary:

Example: Following Example gives us membership operations in dictionaries

6.4.9. Buitin Methods on Dictionaries

clear( ) Clear the contents of the dictionaries

get(key[,d]) Return the value of key. If key does not exit, return d
(defaults to None).
copy( ) Return a shallow copy of the dictionary.
pop(key[,d]) Remove the item with key and return its value or d if
key is not found. If d is not provided and key is not
found, raises KeyError.
popitem() Remove and return an arbitrary item (key, value).
Raises KeyError if the dictionary is empty
items() Return a new view of the dictionary's items (key,
value).
keys() Return a new view of the dictionary's keys.
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value
equal to v (defaults to None).
values() Return a new view of the dictionary's values
set default(key[,d]) If key is in the dictionary, return its value. If not, insert
key with a value of d and return d
update([other]) Creates new dictionary with the key/value pairs from
other
Example on Dictionary:
Clear ( ): It is used to empty the dictionaries
Syntax: dict.clear ()
Example:-

In above example if we want to clear the elements of dictionary we use clear method it return
empty dictionary

get (key [,d]):


get method is used to get the values of values according to keys and it return the values
Syntax:-dict.get ()

Example:
In above example it is clear that by the help of get method we are accessing the values as follows
with their key values
Copy ( )
The copy() method generates a shallow copy of the dictionary A copy only copies
contents, and the new construct points to the same memory location.
Syntax:-dict.copy ()
Example:

It generates the another copy of same file with same


memory address

pop (key[,d])
Remove the item with key and return its value or d if key is not found. If d is not
provided and key is not found, raises KeyError.
Syntax:-Dict.pop (key)
Example:-

It removes the item with key as 3 and returns its value as C


pop item ():-
 It eliminates an arbitrary element (the before element which is returned) from the
dictionary.
 Returns an arbitrary element (key, value) pair from the dictionary.
Syntax: -Dict.popitem ( )
Example:-

Example:-

Items ( ):-
It returns a view object that gives a list of a given Dictionary's (key, value) tuple pair.
Syntax:-
Dict.items ()
Example
Example

Keys ( ):-
The method keys ( ) gives a list of all the available keys in the given dictionary.
Syntax:-Dict.pop (key)
Example:-

Fromkeys (seq [, v]):-


It creates a new dictionary with keys from seq and values set to value.
Syntax:-Dict.fromkeys ( )

Example:-

Example:-

Values ():-
It returns a list of all the values available in a given dictionary
Syntax:-Dict.values ( )
Example:-
Example:-

Set default (key d]):-


It is very similar to get (), but it will set dict [key] =default if key is not already in dict
Syntax:- Dict.setdefault(key[, default value])
Example:-

Example:-

Update ([other]):-
It adds dictionary dict2's key-values pairs in to dict. This function does not return
anything.
Syntax: - dict. Update ([other])
Example:-
Built-in functions in Dictionary:
Dictionary supports following built-in methods they are as follows given below table

Len( ) It returns the number of items of an object


Sum( ) It returns the sum of start and items of the given iterable.
Min( ) Returns smallest among the given arguments
Max ( ) Returns biggest among the given arguments

Important functions of dict:


Dict has following important built-in functions they are as follows
 Len( )
 Max( )
 Min( )
 Sum( )

1. len( ) function:
It Returns the number of elements present in the dictionary
Syntax:
dict_name=len (dict_name)
Example:
2. max () function:
It Returns the maximum number of item in the dictionary
Syntax:
dict_name=max (dict_name)
Example:

3. min ( ) function:
It returns the minimum number of item in the dictionary
Syntax:
dict_name=min (dict_name)
Example:

4.sum( ) function:
It return the sum of items of dictionary, when keys are integer values
Syntax:
dict_name=sum (dict_name)
Example:

Dictionary Comprehension:
Dictionary comprehension is an elegant and concise way to create new dictionary from
an iterable in Python. Dictionary comprehension consists of an expression pair (key: value)
followed by for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.
Syntax:
d= {dict-comprehension}
Example: Print the keys and squares for a Dictinary
Example: Conversion of string according to length by the help of len function in
dictionaries

A dictionary comprehension can optionally contain more for or if statements .An optional if
statement can filter out items to form the new dictionary .Here is some examples to make
dictionary with only odd items.
Example: Program to print odd squares using key and values

What is Nested Dictionary in Python?


In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries
into one single dictionary.
Example:
nested_dict = {‘dictA’: {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two
dictionaries each having own key and value.
Create a Nested Dictionary
Here we can create a dictionary inside another dictionary as follows
Example 1: How to create a nested dictionary

In the above program, Dict is a nested dictionary. The internal dictionary 1 and 2 is assigned to
Dict. Here, both the dictionary has key Name, Place, and Subject with different values. Now, we
print the result of Dict
Access elements of a Nested Dictionary
To access element of a nested dictionary, we use indexing [ ] syntax in Python.
Example 2: Access the elements using the [ ] syntax
Chapter 7: Functions
7.1 Introduction:
A function is a reusable and modular code to perform a set of specific actions. In python have
two types of functions 1.built-in functions 2.user defined functions

In python have many built-in functions like input(), print(), len(), count(),dir(),abs(). etc…

User defined functions in python:

You can also create your own functions to do more specific tasks that are called user-defined
functions.

7.1.1 Defining a function and calling a function:


Using the def statement is to create a function in python. This is a single clause with compound
statements.

Syntax:
def <function_name>(parameters):
Statements
function_name is known as the identifier of the function. A function definition is an executable
statement its execution binds the function name to the function object which can be called later
on using the identifier.
Parameters are an optional. The list of identifiers that get bound to the values supplied as
arguments when the function is called. A function may have number of parameters which are
separated by commas.
A statement is also known as the function body. Statements are non empty statements executed
each time the function is called. It means function body can’t be empty, like any indented block.

Example 1: the following example to display the welcome to Naresh It name.

Let call a nit() function let purpose a welcome to Naresh IT.

Output:

Types of function arguments in python:

Python allows function with 5 types of arguments.

1. Function arguments
2. Default arguments
3. Keyword arguments
4. Positional Argument
5. arbitrary arguments (variable length arguments)

7.1.1 Function arguments


Parameters are specified within the pair of parentheses in the function definition, separated by
commas. When we call the function, we supply the values in the same way. Note the
terminology used - the names given in the function definition are called parameters whereas the
values you supply in the function call are called arguments.
argument (actual parameter): the actual variable being passed to a function;
parameter (formal parameter): the receiving variable that is used in a function.

Example: the following example to find out max value using function

Output:

Explanation: here declare a find_max(a,b) function with a and b parameters, in function body
checking the condition which parameter is big by using if .. elif condition. So 40 and 55 numbers
are passed to the function if 40>55 condition is false elif 55>40 condition to execute elif body.
55 is greater than 40.
Example 2: the following example to pass different type of data type parameters.
Output:

Note: we can’t compare elements of set and dictionary because order is not reserve.

Example 3: the following example swap a two numbers by using functions


Output:

Nested function in python:


 A function which is defined inside another function is known as nested function.
 The nested functions can access the variables of the enclosing scope. It can use the
nonlocal keyword explicitly with these variables in order to modify them.

Example 1: the following example to square a next number to pass the arguments.

Example 2: the following example to pass a function as argument


Output:

7.1.2 Default argument in Python:

You may 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. You can specify default argument values for
parameters with the assignment operator (=) followed by the default value.

Example 1: the following example to find the volume of sphere

Output:

Note: non default argument follows default arguments in python


Example 2: the following example shows an error non default argument follows default
arguments.

Example 3: the following example to find simple interest


Output:

7.1.3 Keyword arguments


 You can give values for parameters by naming them - this is called keyword arguments.
 We use the name instead of the position which we have been using all along.

There are two advantages of keyword arguments


1. Don’t worry about the order of the arguments.
2. We can give values to only those parameters which we want provided that the other
parameters have default argument values.

Example 1:

Output:

Example 2: the following example displays parameter values. Default argument values
Output:

Example 3: when we pass the arguments shows an error positional argument follows keyword
arguments.

7.1.4 Positional Argument


A positional argument is a name that is not followed by an equal sign (=) and default value.
Example: The following ex

amples find the area of rectangle

Output:
200

7.1.5 Arbitrary arguments (variable length arguments)


This is very useful when we do not know the exact number of arguments that will be passed to a
function. Or we can have a design where any number of arguments can be passed based on the
requirement.
In python arbitrary arguments are two types
1. Arbitrary number of positional arguments
2. Arbitrary number of keyword arguments

Arbitrary number of positional arguments


An arbitrary number of arguments can be done by prefixing one of the argument with a *
(asterisk)
Example 1: the following example read a number of arguments and sum values.

Output:

Example 2: the following example to read with a list and display list type of arguments

Output:

Example 3: the following example to read with a list and displays sum values
Output:

Example 4: the following example shows a common letter in a string or list

Output:

Note:
 We can’t provide a default argument. It will raise a syntax error
 We can’t provide by names when calling the function. It will raise type error.

The following examples:


Example 1: syntax error
Example 2: Type error

Output: It shows a Type error

Arbitrary number of keyword arguments


It can take an arbitrary number of arguments with a name by defining an argument in the
definition with ** (two asterisks)
Example: the following example to read arguments.

Output:

Example 2: the following example


Output:

The following table to understand the function type arguments

Syntax meaning
function_name(value) function argument
function_name(name=value) Keyword argument: matched by name
def function_name(name) positional argument: matches any by position or name
def function_name(name=value) Default argument value, if passed in the call
def function_name(*name) Matches remaining positional args (in tuple)
def function_name(**name) matches remaining keyword args (in a dictionary)

Note:
You can follow the below order to pass an argument inside the function
1. Whenever we want to pass an argument to function positional/keyword come first.
(Required arguments).
2. 2nd priority is for arbitrary or variable length (*args) arguments. (Optional)
3. 3rd priority is for keyword-only argument. (required)
4. Finally the arbitrary keyword (**kwargs) come. (Optional)

Example:

7.2 Variable Scope and binding in Python

Variable scope has defined two types


1. Global scope variable
2. Local scope variable
Global scope variable:
 It declared an outside a function. It can be reached anywhere in the code is called a global
variable.
 The lifespan lasts as long as script is running.
For example: built-in functions as global like function print()

Example:

Output:

Changing the global variable:

Output:

Local variable Scope in python:


 It declared inside a function. It access only inside the function body is called a local
variable.
 The lifespan is temporarily as long as function they are defined in is active.
Example:

Output:
Welcome to Naresh It

LEGB rule in python:


 In python searches three scopes - used to follow the LEGB (Local, Enclosing function
local, Global and Built-in).
 First local searches then global searches.
 It is possible to override the variables by creating a local one.

7.3 global and nonlocal keywords


nonlocal variables:
Python 3 added a new keyword called nonlocal. The nonlocal keyword adds a scope override to
the inner scope.
Example:
The following example show an error UnboundLocalError without using nonlocal keyword
Output:

Example:

Note: nonlocal keyword will you to assign to variables in an outer scope, but not a global scope.
So you can’t use nonlocal in our increment_val function because then it would try to assign to a
global scope it get an error syntaxError instead we must use nonlocal in a nested functions.

global Keyword in Python:


The global keyword is useful to create global variable or change variable in a local context.
Example 1: the following example observes the variables.

Output:

Example 2: the following example to export a global variable within function


Output:

The global keyword means that assignments will happen at the modules top level, not at the
program’s top level. Other modules will still need the usual dotted access to variables with the
module.

Note: to know whether a variable x is local to a function,


1. If we are found global x, then x is global variable.
2. If we are found nonlocal x, then x belongs to an enclosing function and is neither local
nor global.
3. If we are found x=10 or for x in range(5) or some other binding then x is a local variable.
4. Otherwise x is fallows to LEG B rule ( local scope, Enclosing scope, global scope or
built-ins)
Example 2: the following example to modify a math module constant variable e by using global
keyword.

Example 3: the following example to add names


Output:

Example 4:

Output:
7.4 Return statement in python:
Function bodies can contain one or more return statement. They can be situated
anywhere in the function body .If the return statement is without an expression, the special value
none is returned. If there is no return statement in the function code, the function end
Syntax:
def <function name>(parameter):
statements 1
statements 2
Return [expression]

Example:

In above example we are return the value of function with the help of print function, whenever
we are not returning anything it will return None value as following example
Example:

Here we are not returning anything so it return None value


Single value returns statements in Function:
In this it will return only single value either it is int or string
Example
Here in above example with the help of return statement and function called fun is used to print
welcome to naresh it
Multiple value return statements in Function:
Function body contains multiple return statements as given example below
Example:

Example:

Return statement in loops:


If you have a loop inside a function, using return from inside that loop is equivalent to having a
break as the rest of the loop is not executed
Example:
In above example here we are using return statemennt inside the for loop to terminate the
function after satisfy the condition is true
Example:

7.5 Functional programming in python:


Python is not a functional programming language, but it is a multi-paradigm language
that makes functional programming easy to perform, and easy to mix with other programming
styles Functional programming decomposes a problem into a set of functions. Ideally, functions
only take inputs and produce outputs, and don’t have any internal state that affects the output
produced for a given input

Purpose of Lambda functions in Python:


In Python, anonymous function means that a function is without a name. As we already know
that def keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions
 This function can have any number of arguments but only one expression, which is
evaluated and returned.
 One is free to use lambda functions wherever function objects are required.
 You need to keep in your knowledge that lambda functions are syntactically restricted to
a single expression.
 It has various uses in particular fields of programming besides other types of expressions
in functions.
 lambda function is used for creating small, one-time and anonymous function objects in
Python.
Syntax:
lambda arguments: expression
Example 1: The following example cube a function

It may also using define lambda the following

Output:

Here in above example lambda is a keyword x is argument it will take 6 and return its cubical
value 216
Example 2:

Example 3:

From above examples it is clearly mention that her we are multiply the 3 and 4 value and adding
it to 12 o resultant value is 24 and in second example it print the string Nareshit
Example 4:
By the help of lambda functions we are performing arithmetic operations as given above
example

Lambda functions can be used along with built-in functions like


 filter()
 map()
 reduce()
Use of lambda () with filter ():
The filter () function in Python takes in a function and a list as arguments. This offers an elegant
way to filter out all the elements of a sequence “sequence”, for which the function returns True.
Here is a small program that returns the odd numbers from an input list we can use filter function
in following ways
 Filter with Number
 Filter with String

Syntax:
filter (function, iterable_object)
Filter with Number:
We can use filter method for number data types as follows
Example:
Filter with String:
We can use filter method for string data types as follows

Example:

Use of lambda () with map ():


The map() function in Python takes in a function and a list as argument. The function is
called with a lambda function and a list and a new list is returned which contains all the lambda
modified items returned by that function for each item.
 Map applies function to each element of iterable and creates a list of the results.
 You can optionally provide more iterable as parameters to map and it will place tuples in
the result list.
 Map returns Iterators which can be cast to list.
Syntax:
map (function, iterable)
Example 1:

Example 2:

Example 3:
Output:

Use of lambda () with reduce ()


The reduce () function in Python takes in a function and a list as argument. The function
is called with a lambda function and a list and a new reduced result is returned. This performs a
repetitive operation over the pairs of the list. This is a part of functools module
Example:

From above example by the help of functools we are reduce the given list by addition of all the
number
Example:

From above example by the help of functools we are reduce the given list by modulus of all the
number so it return reminder value
Example: explain about the overview of lambda functions
7.6 Python Recursive Function
Recursion is a way of programming in which a function calls itself one or more times in its
body. Usually, it is returning the return value of this function call.
 A complex task can be broken down into simpler sub-problems using recursion.
 Sequence generation is easier with recursion than using some nested iteration.
Example:
Example:

In above example we are printing a reverse of a string in two ways one is by the help function
and slicing operator in string

An example of a recursive function to find the factorial of a number


Following is an example of recursive function to find the factorial of an integer. Factorial
of a number is the product of all the integers from 1 to that number. For example, the factorial of
4(denoted as 4!) is 1*2*3*4 = 24.
Example:
In the above example, factorial () is a recursive functions as it calls itself. When we call this
function with a positive integer, it will recursively call itself by decreasing the number. Each
function calls multiples the number with the factorial of number 1 until the number is equal to
one. This recursive call can be explained in the following steps.
8. Object Orientation
Introduction:

In computer world, who isn’t interested in learning some new styles of writing code? Most
programming languages are uses a one coding style which reduces flexibility and readability for
the programmer.

In python, is a different, you can use a number of coding styles with it to achieve different effects
among various coding styles. There are four main coding styles
1. Functional
2. Imperative
3. Procedural
4. Object-oriented

These are four forms valid or useful. Let see the all available what

Functional:

Every statement is a thought of a mathematical equation and any mutable data are avoided. The
main purpose of this is lends itself well to use parallel processing activity. Many developers use
this coding style regularly. In python so many implements the functional ways such as Functions,
lambda functions/anonymous functions, higher order function (Types of function), closure, data
immutability and pattern matching.

Example:

import functools
lst1 = [10, 20, 30, 40, 50]
sums = functools.reduce(lambda i, j: i + j, lst1)
print(sums)

 To call a functools.reduce() and return all sum values.


 The lambda expression is shorter than a procedural approach.

Imperative:
The imperative style is performing arithmetic operations as a direct change to program state.
This style is useful when modifying data structures and produces element.

Example:
sums=0
for i in range(1,10):
sums += i
print(sums)
Here sum += i is the imperative style, the value of sums changes with each iteration of the loop.

Procedural:
The procedural styles, where tasks are proceed a step at a time. Most of them are used for
iteration, sequencing, selection and modularization. To run this function, our main program is
simply a series of calls to the different functions.
Example:
lst1 = [10, 20, 30, 40, 50]
lst2 = [1, 2, 3, 4, 5]
def add(lst):
tot = 0
for i in lst:
tot += i
return tot
print(add(lst1))
print(add(lst2))

Here the add method works on systematically and code is easier to understand.

Object oriented:
Object oriented style is increasing an application's ability to reuse code and make it easier to
understand. Using object-orientation features as the follows

Encapsulation
Internally the object is hidden from view outside of the object's definition.

Polymorphism
It can be done overload operators so that they have appropriate behavior based on their Context.

Inheritance
It means implements subclasses that contain specialization of their parents.

Example:
lst1 = [10, 20, 30, 40, 50]
class sumlist(object):
def __init__(self,lst):
self.lst = lst
def add(self):
self.total = sum(self.lst)
obj = sumlist(lst1)
obj.add()
print(obj.total)
Here obj is instance of sumlist class.

Before introducing classes, first we know about python scope rules and namespaces.

Namespace in python:
What is name in python?
In python everything an object, a name is an identifier to something we use to access a python
object.
Example:

Here, ‘a’ is a name and assigns a value 10 and also python object. To get this object address in
RAM we use the id () function and value.

When we increment the value

Here, value of ‘a’ is incremented and b value also assign same value check the where we store
same.
Dynamic name binding:

First we check the example


Here, the address of x and the address of y is same before increment x. first assign x address, it
doesn’t create another object to hold 10 for y is called Dynamic name binding.

Built-in function names:

In python everything an object so python functions also you can associate them with names.

Example:

We associate the name ‘List’ with the built-in function list(). It another object name of the list.

Example 2:
In python, the function doesn’t return anything we get an object of class ‘NoneType’. The None
object indicates no value. The main function return a value integer so it would assign to ‘s’
object. it is an integer object.
What is python namespace?
A namespace is a mapping from names to objects. Most namespaces are currently implemented
as python dictionaries but that's normally not noticeable in any way and it may change in the
future.
The namespaces are three types
1) Built-in names (such as abs())
2) The global names in a module.
3) Local names (Function)

The set of attributes of an object also form a namespace.


there is no relation between names in different namespaces for example a instance to define a
function with two different modules, to access variable the modules must prefix it with the
module name.
We use the word attribute for any name following a dot. Example: z.real real is an attribute of the
object z. references to names in modules are attribute references. For example
datetime.MAXYEAR
in the expression
modname.funcname modname is a module object and funcname is an attribute of it. forexample
datetime.strftime

Namespace created at different moments


1. It containing the built-in names is created when the python interpreter starts up, and is never
deleted.
2. The global namespaces for a module is created.
3. The local namespace for a function is created.

Scope of variable:
A scope is a textual region of python program where a namespace is directly accessible. it means
that an unqualified reference to a name attempts to find the name in the namespace.

The scopes are determined statically, they are used dynamically. At the execution time there are
three nested scopes are directly accessible.

1) The current function variable scopes i.e. the local names.


2) The scope of any enclosing functions contains global names.
3) The outermost scope of is the namespace containing built-in names.

If a name is declared global then all references and assignments go directly to the middle scope
containing the module's global names.

To rebind variables found outside of the innermost scope, the nonlocal statement can be used.
If not declared nonlocal, those variables are read-only.

Example: the following example demonstrating how to reference the different scopes and
namespaces and how global and nonlocal affect variable binding.
Output:

The above example, declare a name test is the local name of the current function, outside
functions (local_test(), nonlocal_test() and global_test()) the local scope references the same
namespace as the global scope the module’s namespace. Class definitions place yet another
namespace in the local scope.

8.1 Class & Object

In python, classes are following information


 Class is a python object with several characteristics.
 We can call a class as it where a function and this call return a new instance of the class.
 A class has arbitrary named attributes that can be bound, unbound a referenced.
 Class attributes can be descriptors (including functions) or normal data objects.
 The class attributes bound to functions is also known as methods.
 A method can have special python-defined meaning , they’re named with two leading and
trailing underscores)
 A class can inherit from other classes, meaning it delegates to other classes the look-up of
attributes that are not found in the class itself.

The simple class definition:

class ClassName:
<statement-1>
.
.
.
<statement-N>

Class definitions is like function definitions (def statements), it must be executed before they
have any effect. Class created a key word class.
The statements are usually being function definitions. The function definitions inside a class
normally have a particular order form of argument list because calling for method.
The following are represents a statements.
 We can write a class to represent properties (attributes) and actions (behavior) of object.
 Properties can be represented by variables
 Actions can be represented by Methods.
 Hence class contains both variables and methods.
Variables: instance variables, static and local variables
Methods: instance methods, static methods, class methods

A reference is a name that refers to the specific location in memory of a value called an object.

A class object supports two kinds of operations.


1) Attribute references.
2) Instantiation.

Attribute references:
An attribute of an object is denoted by a reference to the object, followed by a period (.), and
followed by identifier called the attribute name
i.e classname.name refers to the attribute of object classname that is named name.
An item of an object is denoted by reference to the object, followed by an expression with in
brackets ([ ]). Within brackets expression is called the index or key to the item and the object is
called the container of the item
i.e name[expr] refers to the item at key or index expr in container object name.
Example:

Output:

Here ClassDemo.a, ClassDemo.lst and ClassDemo.fun are valid attribute references and
returning an integer, list and function object respectively. Class attributes can also assigned to, so
we can change the value of ClassDemo.a and ClassDemo.lst[2] by assignment operator.

Instantiation:
Class instantiation uses a function notation. It listen that the class object is a parameter less
function that returns a new instance of the class.
Example:
i.e obj=ClassDemo()
Instance Object:

Instance object is referring to their attributes. There are two attributes apply
1. Data attributes
2. Method attributes
Data attributes:
 Data attributes are an instance variable. Need not declared. They have values.
 It is like a local variable inside a function when first assigned.
 It can be assigned and printed and deleted.

Example:

Obj.b and c.c is data attributes.


Method Attributes:
In python, a method is an object. All the def functions defined in a class define corresponding
methods of its instances.
Example:
Obj.f() is a valid method object since the def f is function was created in the parent c definition.

Accessing the instance attributes:


It always is used a dot notation with the instance name as defined in the initiation.
For example
We will use the instance name and dot.
Obj.b is data attribute accessing
obj.f() is method accessing.

Instead of we are using some built-in functions to access, assign and del attributes in python.

getattr(obj, name[, default]) : it access the attribute of object, if doesn’t exists return default
value.
hasattr(obj,name) : it check if an attribute exists or not.
setattr(obj,name,value) : it is set an attribute. If doesn’t exist, then it would be created.
delattr(obj, name) : it delete an attribute.
Example:

Built-In Class Attributes:


It can be accessed using dot operator, the following built-in attributes
__dict__: Dictionary containing the class's namespace.
__doc__: if undefined return None otherwise return documentation string class.
__name__: Class name.
__module__: which class is defined the module name. In interactive mode is __main__.
__bases__: it containing empty tuple base classes, in the order of their occurrence in the base
class list.
Example:

Output:

It creates a new instance of the class and assigns this object to the local variable obj.
Before knowing instantiation to know about the self and __init__() methods.
Create Instantiation are two types.

1) Old style by using __init__() method.


2) New style by using __new__() method.

What is __init__ () method?

when running a python program, a call to that class i.e. the class name with a couple of
enclosures after it with at least zero arguments inside the parentheses this process known as
creation of a new instantace of a class happens. It is an old style of creation and also called as
constructor.
It returns only None value. If return other object, it will raise TypeError.
Here is the example:
classname (argv1, argv2, … . argvn)
The instance creation also called as instantiation is handle by __init__ () or constructor method.
1) First step create instance with an empty .__dict__ attribute that will contain the instance’s
values.
2) Second step calls the constructor. The list of argument for this call always has the special
first argument self (the instance), followed by whatever arguments were used in the
initial call.
3) The third step executes the constructor method. The constructor will set up new instance
attributes by assignments of this form
self.argv1=expression
self.argv2=expression
4) The final step finishes the constructor executing, the instance is returned to the
constructor’s caller.

What is self in python?


 Class methods have a one different from ordinary functions i.e. the self added to the
beginning of the parameter list in class methods but we don’t give a value for this
parameter when you call the method, python will provide it.
 The self is particular variable refers to the object itself and by convention it is given the
name self.
 If you give any name for this parameter, the IDEs can help you use self.
 In other languages is equivalent java, C# this and c++ is pointer.

Example:

Here, calling the class object creates two arguments of instance. Many classes like to create
objects with instances customized to specific initial state. May define a class a special method
name __init__() this is called a instance operation.

Note: if you have a method which takes no arguments, then you still have to define the method
to have a self argument.

__new__ ():
The __new__ ( ) is a special method name that is called on instantiation before the constructor. It
handles the creation of a new instance.
Steps to the when an instance is created by using .__new__ ()
1) When instance is created called as a __new__()
2) It is always a static method. You don’t specifically create it a static method.
Example:
Classname(*argv,**kargv)
Here it can pass any number of positional arguments and any number of keyword
arguments.

It is look like the following __new__() method.


def __new__(cls, *argv,**kargv):
…..
Here the first argument cls must be the class being created. It can pass any number of
positional arguments and any number of keyword arguments.
3) Create a new instance of the class by invoking the super class’s __new__ () method using
super ().__new__ () with appropriate arguments and then modifying the newly created
instance as necessary before returning it.
4) The __new__( ) returns an instance of cls, the __init__() method will be invoked like a
__init__(self[,….]), where self is the new instance and the remaining arguments are the same
as were passed to __new__().

Example:

5) The __new__() doesn’t return instance of cls, then that new instance’s __init__() method
will not be invoked.
6) The main intention of __new__ () is to allow subclasses of immutable types(like int, str,
or tuple) to customize instance creation. It is also commonly overridden in custom meta
classes in order to customize class creation.

Class variables and instance variables:


Instance variable are unique for a particular instance.
Class variable are shared by all instances of a class.
Example:

The above example y has to shared by all instances of the cls class has to be stored in a class
variable. The following example all the instances created can have access to it.

Output: 3000
2700

The above example how to reduce the discount amount 10% without creates class variables.

We would create class variables to contain data read a discount_price().

Class customer:
Discount_amount= 1000

Now we are on apply to discount_price()


Def discount_price(self):
Self.price=int(self.price-self.discount_amount)
We want to pass discount_amount because it’s a class variable and can be accessed by all
instances within the parent class
Print(Customer.discount_amount)
Print(cust1.discount_amount)
Print(cust2.discount_amount)

We can prove that class variables could be accessed by your class and at the same time instance
of the class.

How can we access an attribute on an instance?

First checks the instance contains the attribute. If it doesn’t contain it checks if the parent class or
any class it inherits from contains the attribute.

Example: the example we could use a class variable in another place, what happen to class
variable.

Output:
0
2
2
2500
4500

Properties in python:
Properties are defined using built-in @property decorator function. When applied to a method, it
forces the method to be called whenever the function's name is accessed as an attribute name.

Example:

The last line gives AttributeError because properties defined this way only retrieve attribute
values, not assign them. The name () function calls are only one way so assign to the value, we
will add another method.

In order to mark the new method as the setter for a property, it's decorated much like the getter
property. The setter property defines an assign values. Let see the example.
Another property delete, it can also delete the current value using a decorator similar to the
setter. By applying Fullname.deleter to a method that only accepts the usual self, we can use that
method to delete values from the attribute.

@Fullname.deleter
def Fullname(self):
del self.fname
del self.lname

It clear they both fname and lname.

Methods:
There are two distinct methods
1) Unbound methods
2) Bound methods

Unbound methods:

It is an unbound method when accessing a function on a class. The descriptor receives the class,
but methods require the instance, so they're referred to as unbound when accessed without one.
Example:
When accessing the method on a class is just the function object itself.

It’s callable like any other standard function, but it also carries information about what class it's
attached to.
Note: the self argument in an unbound method isn't passed automatically, there's no instance
object available to bind to it.

Bound method:

Once the class instance created each method descriptor returns a function that is bound to that
instance. It’s backend by the same function and the original unbound method is available on the
class but the bound method receives the instance object as its first argument.

Example:

The difference only is that bound methods have an instance to receive as the first argument. it is
important to that the instance object is passed as a positional argument, so the argument name
doesn't need to be self in order to work properly. It’s best established standard that you should
follow whenever possible.

In python, there are four types of methods

1) Decorators
2) Instance methods
3) Static methods
4) Class methods

Instance method:
 When we create an instance method, the first parameter is always self.
 There is no needed decorator.
Example:

The name variable is accessed through self. When disply_name () method is called, you don’t
have to pass self, it can’t access the variable

Advantages of instance methods.

 We can able to access data and properties unique to each instance.


Static methods:
 Static methods are related to a class in some way but we don’t need to access any class-
specific data.
 To declare a static method use a built-in staticmethod function.
 We don’t have to use self instance.
 We don’t call an instantiate an instance directly call classname with method.
Example:
Output: Result: 70

 Static methods perform a task in isolation. It can’t access data.


 This is completely self-contained and work with data only passed in as arguments.

When to use static method:


 It is more than a function defined inside a class.
 It is callable without instantiating the class first.
 It is definition is immutable via inheritance.
 Python doesn't have to instantiate a bound-method for object.
 It eases the readability of the code that the method does not depend on the state of object
itself.
Class methods:

 Class method is similar to static method. The difference is passing the instance cls (class)
as first parameter. We are passing the class itself as first parameter.
 To declare a class method, use a built-in classmethod function.
 Don’t need a self an argument.
 There are two ways of to call a class methods
1. Using its classname.methodname
2. Using an instance.
Using class is passed as the cls argument of the method.
Using instance is passed as the cls argument.

Example:
Here, actually the __init__ is an initialize of python class instance but which receives arguments
an instance method, having the self argument that holds a reference to a newly created instance.
Advantages:
 Implements a date string in one place and it's reusable now.
 Encapsulation work done.
 The cls is an object that holds the class itself, not an instance of the class because if we
inherit our date class, all children will have split_date defined also.

When to use class methods:

 It is also callable method without instantiating the class.


 It is follow the sub class, not parent class via inheritance.
 It can be overridden by subclass because the first argument for @classmethod function
must always be cls(class).
 Factory methods are used to create an instance for a class using. Example: sort of pre-
processing.
 In the event that you split a static method in several static methods, you shouldn't hard-
code the class name yet to use class methods.

The difference between classmethod and instance method

@classmethod @staticmethod
it can be called via instance and class itself it can be called via instance and class itself
E.x: class cs: E.x: class cs:
@classmethod @staticmethod
def fun(cls,argv1,argv2,…): def fun(argv1,argv2,…):
…… ……
then the call is then the call is
cs.fun() or cs().fun() cs.fun() or cs().fun()

it supports inheritance it supports inheritance


It is not mandatory, neither self nor cls is
passing a instance argument (cls)
implicitly passed.
It can form inside class, it only way to write
It can't form inside a class. method in class without (cls, self) implicitly
passing the object is being called.

Inheritance:
Without supporting inheritance, the object oriented is not worth for implements Applications
because it’s enables us to use the member attributes and methods of one class into another.

Syntax for Inheritance:

class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
The BaseClassName must be defined in a scope containing the derived class definition. In place
of BaseClassName other arbitrary expressions are also allowed. The BaseClassName is not with
in place we use the following syntax.

class DerivedClassName(modname.BaseClassName):
modname means module name or saving filename
Execution of a derived class definition precedes the same as for a base class. When the class
object is constructed, the base class is remembered. This is used for resolving attribute
references. If requested attribute is not found in the class, the search proceeds to look in the base
class. This rule is applied recursively if the base class itself is derived from some other class.
Example:
Explanation:
contacts is a class variable and list, it is shared by all instances of this class it means
contact_info.contacts. if we call self.contacts on any object, it will refer to that single list. the
initialize careful that whenever create a new contact, the list automatically have the new object
added.
we could add an reader method to the Add_contact class that would allow contacting details.
Add_contact class that acts like a Contact_info but has an a reader method.

Python has two built-in functions that work with inheritance:

isinstance(obj, int):
 To check an instance's type.
 If obj.__class__ is int, it will be True or some class derived from int.

issubclass(bool, int):
 To check class inheritance.
 issubclass(bool, int) is True since bool is a subclass of int.
 issubclass(float, int) is False since float is not a subclass of int.

isinstance(object, classinfo)

 If the object argument is an instance of the classinfo argument or of a subclass it returns


true.
 If object is not an object of the given type, the function always returns false.
 If classinfo is a tuple of type objects (or recursively, other such tuples), return true if
object is an instance of any of the types.
 If classinfo is not a type or tuple of types and such tuples, a TypeError exception is
raised.

Example:

Output:

issubclass(class, classinfo)

 Return true if class is a subclass (direct, indirect or virtual) of classinfo.


 A class is considered a subclass of itself.
 classinfo may be a tuple of class objects, in which case every entry in classinfo will be
checked. In any other case, a TypeError exception is raised.

Example:
super([type[, object-or-type]])

 Return a proxy object that delegates method calls to a parent or sibling class of type.
 It search order is same as that used by getattr() except that the type itself is skipped.
 It is useful for accessing inherited methods that have been overridden in a class.

Method overriding in python:


The method overriding a class may copy another class, avoiding duplicated code and at the same
time enhance or customize part of it. it is strict part of the inheritance class.

Example:

Example 2:
Output:

Multiple Inheritances:
Python supports a multiple inheritance it means a class definition with multiple base classes.
Syntax:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
<statement-N>
The purposes of multiple inheritance, if you can search an attribute is not found in
DerivedClassName, it is searched for base1,if it is was not found there, it was searched for in
base2 and so on.
Python MRO (Method Resolution Order):
When we search an attribute in class that is involved multiple inheritance an order is
followed. First it searches in the current class, if not found then search parent1 class and searches
left-to-right parent classes and follow the set of rules are called MRO (Method Resolution
Order). You can get the MRO of a class, you can use either the __mro__ attribute or the mro()
method.
The method resolution order changes dynamically to support cooperative calls to super()
this approach is known in multiple-inheritance languages as call-next-method and is more than
the super call found in single-inheritance languages.
Example:
Encapsulation in Python
In object oriented programming we can restrict access to methods and variables. This can
prevent the data from being modified accidentally and is known as Encapsulation. We can
restrict the access to the class members (variables and methods) by making the private. There is
no private keyword similar to other programming languages. For making the class members
private, double underscore is placed before the name.
Syntax: __varibleName, __methodName ()
EXAMPLE:
Private Variables:
The private variables of a class are the variables which access is restricted to its particular
class. Making variables private prevents from changing the variable values accidentally. For
making a variable private double underscore is placed before the variable name.
Private Methods
In a class, private means the methods of a class are only available inside a class but not
outside. A Python method, or attribute is private or public is determined entirely by its name.
There are no keywords like private or public to represent a method or variable. The name of a
private method starts with double underscore but does not ends with underscores
Ex: __my Fun(). The methods without underscores are public.
Naming Type
Public, these attributes can be used freely or
Attribute
outside of a class.
Private, this kind of attributes are inaccessible
__attribute
or invisible outside the class
Polymorphism in Python
The word Polymorphism is a Greek word where poly means many and morphism means
forms. Polymorphism is an ability of defining multiple logics to perform the same operation.
Python is implicitly polymorphic In python polymorphism can be achieved by implementing
method overriding.
Method Overriding:
In Object oriented programming when a class is inherited from another class. The child
class inherits all the methods from the parent class and in some cases the method inherited does
not fulfill the functionality of the child class. In such cases the particular method is re-
implemented in the child class. This process is known as Method Overriding.
The overridden method is called basing on the type of object use for calling it. If a child
class method is used for calling the overridden method, the method in the child class is called
and if a parent class method is used for calling the overridden method, the method in the parent
class is called.

Example:

Abstract Base Classes (abc):

Why use Abstract Base Classes?


abstract base classes are a form of interface. it checks the individual hasattr() for particular
methods. when we create an abstract base class and also define a common API for a set of
subclasses. In your application where we use a third-party module is going to implementation,
when working on large code-base applications where keeping all classes in your applications to
find is not possible.
10. Exception in python
In python code file, developers take a few errors and mistakes but python to handle errors with
help of exception handling.

What is error in python?

In python, errors are nothing but mistakes in the code. There are two kinds of errors

1) SyntaxError
2) Exception

Syntax error:
Syntax errors also known as parsing errors, those errors are caused while writing the code
structure.

Example:

The colon (‘:’) is missing the before print statement.

Exception:

During the program execution it detects an error are called an exceptions.

Example:

Here the exception comes in different types ZeroDivisionError and TypeError but we need not
define user exception in python define a built-in exceptions.

The following types are called built-in exceptions hierarchy


Exception
Descripction
Class
KeyboardInterrupt During execution the user interrupts program execution, by pressing (Ctrl+c).
It raised by built-in function next() and iterator's __next__() method to signal that
StopIteration
there are no future items produced by the iterator.
IOError It gets raised when an input/output operation fails.
ArithmeticError it raised when numeric calculations fail
ZeroDivisionError it raised when modulo by zero takes place for all numeric types
FloatingPointError it raised when the floating-point calculation fails
ImportError it raised when import module is not found
IndexError it raised when the sequence of index is out of range
IndentationError it raised when there is incorrect indentation
AssertionError it raised when the assert statement fails
OverflowError It raised when the result of an arithmetic operation is too large to be represented.
NameError it raised when an identifier is not found in the local or global namespace
SyntaxError It raise when parser is incorrect.
KeyError It raised when the specified key is not found in the dictionary.
ValueError It raised when the function gets argument of correct type but improper value.
TypeError It raised when a function or operation is applied to an object of incorrect type.
RuntimeError It raised when a generated error does not fall into any category.

Exception Handling:
It is possible to write programs that handle selected exceptions.
Example:

The above example the user enter a valid integer and program terminated, the user enter a
character value it will raise a ValueError exception.

In python, the exceptions are defined various ways

1) try .. except …
2) try .. except ... else ..
3) try ... except ... else .. finally
4) raise
5) assert
1. try …. Except …
The try statement works as following
1) First, the try clause is executed (between try and except statements).
2) If no exception occurs, execute the try clause statements and except clause skipped.
3) If an exception occurs during execution of the try clause, the rest of the statements are
skipped. If its type matches the exception named after except keyword, except clause is
executed and then execution continues after try statement.
4) if an exception occurs which does not match the exception named in the except clause, it
is passed to outer try statements, if no handler is found, it is an unhandled exception and
execution stops with a message as shown above.
Example:

Output:

Here, the printing the out of index value it will execute the exception block.

Handling multiple exceptions with one except block

Multiple exceptions have two ways to handle.

1) All exceptions placing in the form of a tuple.


Syntax:
except (Exception1, Exception2, .. exceptionN) as e:
statements.
Example:
OUTPUT:

2) It mentioned individual wise.

Syntax:

try:
statements
except1:
statements
except2:
statements

Exceptn:
Statements

Example:

Output:

2. try … except … else:


We can include an else clause when catching exceptions with a try statement. the else block
executed when the inside try block doesn't generate an exception.
Syntax:
try:
Statements
except:
Statements
else:
Statements

Example:

When to use the else clause:

We use an else clause after the try-except block. There is no exception thrown in try clause it
will get else clause. The else statement should always proceed except block.

3. Finally clause
Python code is run in all situations then inside the finally block will always run the instructions
coded. An exception error occurs in the try clause, it will run except block and then it would run
the finally clause.

Note: the finally block will always run even if you have returned ahead of it

Example:
Output:

4. Raise exceptions:
It can throw an exception in python with the keyword raise. It is done for the purpose of error-
checking. In python 3 there are four different types of syntax

1) raise exception(args)
2) raise exception
3) raise
4) raise exception(args) from original_exp

1) raise exception(args):

Here the raise statement uses an exception class name, args is an optional parameter that will be
contained in the exception generally this is a string.
Example:

Output:

2) raise exception
Example:

Output:

3) raise
 Without any argument passes the raise statement, it re-raises the last exception.
 Raise statement can raised anywhere, including except clause of a try statement.
 If there was exceptions occur before catching the exception and then you want to re-raise it.
 If there was no exception before catching the exception, raise statement raises the TypeError
exception.
Example:

Output:

4) raise exception(args) from original_exp:

 It is also a user defined exception.


 It is used to create exception chaining in which an exception that is raised in response to
another exception can contain the details of the original exception.

Example: the following example to find the quadratic equation roots and create user defined
exceptions.

Output:

Example 2: the following example to create user exception object information demo
Output:

Here exobj object created and property also created through object

Example: the following example to convert the predefined to user defined exception
Output:

5. Assert:

What is assert statement in python?


In python, the assert statement is tests a condition in your code. It is Boolean expression that
confirms the Boolean output of a condition.

Why use assert in python?

 It is a debugging tool.
 If the condition to be true in python code, there is nothing it needs to do it moves the next
line of the code.
 If the condition to be false in python code, it throws an error and stops all operations.

Flow chart of Assert statement:

Assert condition
Stop a program and
AssertionError raised
False

True

Syntax of assertion:
assert <condition>
assert <condition>, <error message>
Example: the following example without error message.

Example 2: the following example to display error message

Where it is used in assert in python?

 Checking the values of arguments.


 Checking the valid input or types.
 Checking testing code.
 Detecting abuse of an interface by another programmer.
 A debugger to halt where an error occurs.
 Checking outputs of functions.

Example: the following example to test the programmatically


Output:
12 date and time in python

The datetime module supplies classes for manipulating dates and times in both simple and
complex ways.

In general, date and time represents two types of categorized


1. The data saving time information for use of algorithmic and political time adjustments
called aware objects or knowing time.
2. A naive object represents Coordinated Universal Time (UTC), local time, or time in
some other timezone is purely up to the program, just like it is up to the program whether
a particular number represents metres, miles, or mass. Naive objects are easy to
understand and to work with, at the cost of ignoring some aspects of reality.
3. DST refers to Daylight Savings Time.

There are two constants of datetime module.


1. MINYEAR
2. MAXYEAR

Datetime.MINYEAR:
 It allowed the smallest year in a date or datetime object.
 The default MINYEAR is 1(One).

Example: the following example to read a MINYEAR constant variable and changes to the
default value.

Datetime.MAXYEAR:

 It allowed the largest year in a date or datetime object.


 The default MAXYEAR is 9999.

Example: the following example to read a MAXYEAR constant variable and changes to the
default value.
The following module available types

class datetime.date
It is an idealized naive date, assuming the current Gregorian calendar always was, and always
will be, in effect. The attributes are year, month and day.

class datetime.time
It is any particular day. It has exactly 24*60*60 seconds. The attributes are hour, minute, second,
microsecond and tzinfo.

class datetime.datetime
It is combination of a date and a time. The attributes are year, month, day, hour, minute, seconds,
microsecond and tzifo.

class datetime.timedelta
Difference between the two date, time or datetime instances to microsecond resolution.

class datetime.tzinfo

An abstract base class for time zone information objects. These are used by the datetime and
time classes to provide a customizable notion of time adjustment.

class datetime.timezone
A class that implements the tzinfo abstract base class as a fixed offset from the UTC.

timedelta Objects:
A timedelta object represents duration, the difference between two dates or times.
Syntax:
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0,
hours=0, weeks=0) :

 All arguments are optional and default to 0.


 Arguments may be integers or floats, and may be positive or negative.
Only days, seconds and microseconds are stored internally. Arguments are converted to those
units:
 A millisecond is converted to 1000 microseconds.
 A minute is converted to 60 seconds.
 An hour is converted to 3600 seconds.
 A week is converted to 7 days.

days, seconds and microseconds are then normalized so that the representation is unique, with

 0 <= microseconds < 1000000


 0 <= seconds < 3600*24 (the number of seconds in one day)
 -999999999 <= days <= 999999999

Example: the following example to calculate hours and days passing arguments and also using
on days and seconds methods.

Timedelta.days: returns the number of days default is 0.


Timedelta.seconds: returns the number of seconds. Default is 0.

Example2: the following example to read the values and assign to dictionary and list.
The following methods only read only
timedelta.min
It is minimum days of the timedelta. Timedelta(days=-999999999).

timedelta.max
The most positive timedelta object, timedelta(days=999999999, hours=23, minutes=59,
seconds=59, microseconds=999999).

Example: the following example to read the max and min of timedelta object.

timedelta.resolution
The smallest possible difference between non-equal timedelta objects,
timedelta(microseconds=1).

timedelta.total_seconds()
Return the total number of seconds contained in the duration.

The following table instance attribute read only values.

Attribute Value
Between -999999999 and 999999999
days
inclusive
seconds Between 0 and 86399 inclusive
microsecond
Between 0 and 999999 inclusive
s
Operations on timedelta object:

Example 1: the following example sum of two dates using + operand.

Note: we can’t operate multiplication operation on timedelta object. But we can do through their
methods because return integer type value.

Example 2: the following examples works on built-in functions str function.

date Objects:
It represents a date (year,month,day).

datetime.date(year, month, day)


All arguments are required.
Year represents to a year integer type. The ranges is MINYEAR <=year<=MAXYEAR.
Month represents to month integer type. The range is 1<=month<=12.
Day represents to a day given integer type. The range is 1<=day <= number of days in the given
moth and year.
If any argument out of those ranges is given, it will raise value error.
date.today()
Return the system date.

Example:

The following attributes of date object.

date.min  it represent the date object, date(MINYEAR, 1, 1).


date.max  it represent the date object, date(MAXYEAR, 12, 31).

Instance attributes (read-only):


date.year  Between the MINYEAR and MAXYEAR inclusive.
date.month  Between 1 and 12 inclusive.
date.day  Between 1 and the number of days in the given month of the given year.

The following Supported Operations on Date object:

1) date2 = date1 + timedelta:


date2 is timedelta.days days removed from date1.
Note:
dt2 is moved forward in time if timedelta.days > 0, or backward if timedelta.days < 0.
2) date2 = date1 – timedelta :
date2 is like that date2 + timedelta == date1.

3) timedelta = date1 - date2:

This is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and
date2 + timedelta == date1 after.
Example:

4) date1 < date2:


date1 is considered less than date2 when date1 precedes date2 in time.
The following methods are date object.

date.replace(year=self.year, month=self.month, day=self.day):


Return a date with the same value, except for those parameters given new values by whichever
keyword arguments are specified.

Example: the following example replaces the values.

date.weekday()  Return the day of the week as an integer,


where Monday is 0 and Sunday is 6.
date.isoweekday()  Return the day of the week as an integer,
where Monday is 1 and Sunday is 7.
date.isocalendar()  Return a 3-tuple, (ISO year, ISO week number, ISO weekday).
Example:

date.isoformat()
 Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’.
 It is equivalent to str(d1)
Example:

date.ctime()  Return a string representing the date

date.strftime(format)
Return a string representing the date, controlled by an explicit format string.

Example: to find the how many days remaining your birthday.

Time object:
A time object represents a (local) time of day, independent of any particular day, and subject to
adjustment via a tzinfo object.

datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0):


All arguments are optional. tzinfo may be None.

the following ranges of the all arguments.


 0 <= hour < 24,
 0 <= minute < 60,
 0 <= second < 60,
 0 <= microsecond < 1000000,
 fold in [0, 1].

Example:

datetime object:
A datetime object is a single object containing all the information from a date object and a time
object.
Syntax:
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0,
tzinfo=None, *, fold=0)

The year, month and day arguments are required remaining are optional.
The arguments fallowing ranges

 MINYEAR <= year <= MAXYEAR,


 1 <= month <= 12,
 1 <= day <= number of days in the given month and year,
 0 <= hour < 24,
 0 <= minute < 60,
 0 <= second < 60,
 0 <= microsecond < 1000000,
 fold in [0, 1].
If an argument outside those ranges is given, ValueError is raised.
classmethod datetime.today() Return the current local datetime, with tzinfo None.
classmethod datetime.now(tz=None)
 Return the current local date and time.
 If optional argument tz is None or not specified, this is like today()
classmethod datetime.utcnow()
Return the current UTC date and time, with tzinfo None.

Example:

The following are supported operation on datetime object.

1) datetime2 = datetime1 + timedelta:


datetime2 is a duration of timedelta removed from datetime1, moving forward in time if
timedelta.days > 0, or backward if timedelta.days < 0.
2) datetime2 = datetime1 - timedelta
Computes the datetime2 such that datetime2 + timedelta == datetime1

3) timedelta = datetime1 - datetime2

Subtraction of a datetime from a datetime is defined only if both operands are naive, or if both
are aware. If one is aware and the other is naive, TypeError is raised.

Example:
4) datetime1 < datetime2
datetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time.

The following instance methods:

datetime.date()  Return date object with same year, month and day.
datetime.time()  Return time object with same hour, minute, second, microsecond and fold.
datetime.replace( ) Return datetime with same attributes, and replaced values.
Formatting Dates and Times

Chapter 13: Iterators, Generators, Decorators & Closers


What is iteration?
Iteration is process of reading elements sequentially.

What is sequence in python?


An iterable which supports efficient element access using integer indices via the __getitem__ ()
special method and defines a __len__ () method that returns the length of the sequence called a
sequence.
Strings, list and tuple are sequence types. Dictionaries, sets and many other iterables are not
sequence type.

Note: sequences data type has indexes from 0 to one less than their length. We can access for
and while loop but sets can’t access while loop.

What is iterable in python?


 In python, an iterable is any object that you can loop over with for loop.
 Iterables are not always indexable.
 Don’t have lengths and not a finite.

Example: the following example creates infinite iterable which provide every multiple of 10.
Example: the following example we are using for loop, we can access the element from the
beginning of the iterable.

Note: If we remove the break condition from that for loop, it could go on printing forever.

 Iterables can be infinitely long.


 We can’t always convert an infinite iterable to list (any other sequence) before we loop
over it.

What is iterator?
The built-in iter function can read an all iterables to get an iterator from them.

Example: the following example create an Iterators

Why use iterator in python?

1) Iterators can save the memory and time also instead of list, set and other iterable data structure.
Example:

Here create an iterator 1000 times 5 elements. Each element take 2 bytes so 2000 bytes store on
machine now check it
While check it on list how much take space

2) In python, file object are also implemented as Iterators. It is best way for reading because save
memory and time.
It read data into memory one line at a time. If we use instead of read lines method as see the
following example to understand.

Example:

3) When we can create an iterator through object oriented way but it’s not best way. When we want
an iterator we can use a generator.

Example: first we create checking prime number value function save it as chkprimeiterfunction.

Next step an iterator implementing using class.


Now check in your IDLE

4) The main disadvantage of iterator is it can iterate over once. If you try to iterate once again no
value returned. It will behave like empty.

How to access iterator?


We can access element by using next() function of iterator.

next() function in python:


It can be receive a value from any iterator (including a generator and iterator).

Syntax:
next(iterator[, default])
In case the iterator is over the default value returned. The default value was not provided it
raised StopIteration.
Example:

Built-in functions on iterator:


Once applied built-in functions on iterator after that the empty iterator.
The following are
1. sum(iterable[, start]) :
 Sums start and the items of an iterable from left to right and returns the total.
 The iterable’s items are normally numbers, and the start value is not allowed to be a
string.
 start defaults to 0.

2. max: return the largest element in the iterable or the largest of two or more arguments..
Syntax:
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
Itertools Module:
We can create iterator using itertools module. The following are
1) itertools.combinations
2) itertools.dropwhile
3) itertools.takewhile
4) itertools.islice
5) itertools.groupby
6) itertools.permutations
7) itertools.repeat
8) itertools.accumulate
9) itertools.cycle
10) itertools.product
11) itertools.count
12) itertools.chain
1) itertools.combinations(iterable,n)
It returns a generator of tuple all the possible combination of n-wise of the input list.

Example:
2) itertools.dropwhile(predicate,iterable):
It enables you to take the items from the sequence after a condition is false.

In lst element 0,3 is multiple by 3 but 4 is not multiple by 3 so it enable reaming elements to res
variable
3) itertools.takewhile(predicate,iterable)
It enables you to take the items from the sequence after a condition is true.

4) itertools.islice
Syntax:
Itertools.islice(iterble,stop)
Itertools.islice(iterble,start,stop,[step])
 Make an iterator that returns selected elements from the iterable.
 If start is non-zero, then elements from the iterable are skipped until start is reached.
Afterward, elements are returned consecutively unless step is set higher than one which
results in items being skipped.
 If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise,
it stops at the specified position.
Example: the following example stop is 10
Example 2: the following example start is 10 stop is 100 step 10

5) itertools.groupby
syntax:
itertools.groupby(iterble,[,keyfunc])
itertools.groupby(key,subiterator)

 It creates an iterator that returns consecutive keys and groups from the iterable.
 The key is a function computing a key value for each element. If not specified or is None,
key defaults to an identity function and returns the element unchanged.
Example:

6) itertools.permutations
It returns a generator with successive r-length permutations of elements in the iterable.
syntax: itertools.permutations(iterable,[,r])
Example:

7) itertools.repeat(object,[,times])
Repeat the object some times.
Example:
8) itertools.accumulate

It is cumulative sum (or product) of numbers accumulate yields.

Syntax: itertools.accumulate(iterble,[,func])

Example:

9) itertools.cycle:
cycle is an infinite iterator
Syntax: itertools.cycle(iterble)

Example:

When you print above code the output following


Hellohellohello…………… infinite

10) itertools.product:
It is iterate over the Cartesian product of a list of iterables.
Syntax: itertools.product(*iterbles, repeat=1)
Example:
11) itertools.count:
It is generate infinite series of numbers.
Syntax: itertools.count(start=0,step=1)
Example:

It is infinite elements reading.

Example 2:

12) itertools.chain(*iterble):

It generates a single generator which will yield the values from several generators in sequence.

Example:
Example 2: chain.from_iterble(iterable)

2 Generators in python:
Generators are define generate an Iterators. They are two categories of generators
1. generate functions.
2. Generate expression.
Generate functions:
Generator functions is similar to general functions but that have a yield statement in their body is
called generate functions.
The above two examples is same output.
What is yield in python?
 Yield is inside a function and it causes an exit from the function.
 When next time the function is called where you before stopping the line it will
resume the function variables and all local variables also resume.
 There are several yield statements in a function.
 It returns a generator.
 We can also have a return statement.
The following diagram to understand the

Function
Return next object
Value

return yield next


Resume
Terminate preserves
All variables All
Recall
return variable

Example: the following example file name


Example 2: the following example to display Fibonacci series.

Output:

Example 3: the following example to read the multiple yield

Connect to generator:
It is python 3.3 feature it allows generator to connect to another generator and delegate to sub-
generator.
Syntax: yield from <expr>
Where <expr> is an expression evaluating to an iterable, from which an iterator is extracted. It
defines the delegating generator.
Example:

Output:

Explanation:
First create even_gen function with even numbers yields , second function create odd_gen with
odd numbers range with yield statement
Third function creates delegate_demo, call to even_gen and odd_gen and generates expression to
yield with their values.
Last there lines print the tuple, set and list in the screen previously defined the generators

Exception with generator:


The yield keyword is not permitted in the try part of a try/finally construct because the generators
should allocate resource with caution.

Example:
Output:

The result is multiplication of table when while condition false (11<11) it goes finally clause it
add number 5.
Generate expression:
1) generator expression is similar to list comprehension but enclosed with parenthesis.
2) generator expressions as a high performance, memory efficient generalization of list
comprehensions and generators functions.

Example:

List comprehensions have shown their widespread utility throughout python. However, many
times don’t have a full list created in memory instead of we need iterate over the elements one at
a time.
The following example will build a full list of squares in memory, iterate over those values, and,
when the reference is no longer needed, delete the list:

By using a generator expression, it is memory conserved. Let see example


It is especially useful with functions like sum(), min() and max() that reduce an iterable input to a
single value.
Generator expression also creates a functional coded with lambda.

Example: The following examples to sum of 5 values by using reduce function.

Now simplify with generator expression

When to use generator in python?


Generator is an advance tool. It is use many cases for increase efficiency as following
 It processing large amounts of data.
 It generates a stacked manner similar to a UNIX pipe command.
 It can be used to generate a concurrency.

Why generator expression is better than list comprehension?


 As the data is larger, generator expressions is better performance because they don’t
exhaust cache memory and they allow python to re-use objects between iterations.
 A generator expression always needs to be directly inside a set of parentheses and cannot
have a comma on either side in syntax wise.

Decorators:
In python, objects are used to modify functions or classes so these types of special object are
called as decorator these are also called as callable object.
In python, function and classes are callable objects because it accepts some arguments and
returns some objects.
There are two types
1. Decorator Functions.
2. Decorator classes.
Decorator Functions:
In Python, everything is object. When function object has passed to argument the behavior of
other functions and returns an argument function can be used as a decorator.
Example: the following example to understand the decorator
Example 2: the following example

Decorator class:

Example:
Output:

Why learn decorators:

In python fully understand the following concepts after those decorators.


1. Clousers in python.
2. Types of function arguments. How to work function.
3. Variable arguments on functions
4. The arguments unpacking.
5. How to loads the python source code.
These are know about we learn decorators easy to understand. The following are reasons to learn
decorators.

1) Large applications, we don't know about what is going on and what different activity of
function or methods is so decorator can handle easily and readably for requirement. It
means python code analyzing.
2) In python system is a strong type it means some bugs can try creep in at compile time.
You may want to checks on data going in or out. Decorators can handle this and apply it
to many functions at once.
3) You are creating a framework. You will be easy to use simple syntax. Python able to
extend the syntax itself. There are many open source frameworks are there.

For example RESTFull service.


4) Python code reusing impossible to reuse because python gives some tools for
encapsulating code into an easily reusable form. There is some python library patterns of
code reuse we can't captured.

For example: RESTFull service return a JSON format, in python use make_api_call (), and they
are called all over codebase.

5) Create your best career.

Clousers in python

In python, when we create closures we calls the function. The following example is to
understand clarity of the clouseres.

Example:
Here, the call to outer_fun create a binding for x that is referenced inner function the inner_fun
creates a new instance (inst_var) of this function is called a clousere but each instance has a link
to a different binding of x.

Rules for define python closures.

Python closuer defines a when a nested function references a value in its enclosing scope the
following conditions

1. We need nested functions.


2. The nonlocal variable refers to a nested function.
3. It must return a function within enclosed scope.

Why use python clousers in python?

1) We need not use a global value because we refer to a nonlocal variable.


2) Data hiding purpose.
3) Clousers implements a python decorator.
4) It invokes python function outside its scope.

Example:
Output: 400

Here we remove nonlocal x keyword it will raise error UnboundLocalError: local variable 'x'
referenced before assignment so we must use nonlocal keyword when you assign argument
variables.
14. Working with files in Python
Define a file?
File is collection of related information. It is used to permanently store data in a non-
volatile memory (e.g. hard disk).RAM is volatile which loses its data when computer is turned
off, we use files for future use of the data.
File operations?
In Python, a file operation takes place in the following order.
1 Open a file
2 Read or write a file (perform operation)
3 Append a file
4 Close the file
Opening a file
Python has a built-in function open () to open a file. This function returns a file object. It
returns a "file handle" - a variable used to perform operations on the file. File handle has ==>
1. Open
2. Write
3. Read
4. Close

f=open ("AnyName.txt") #Open file in current directory(Relative Path)


f=open ("C:/Python33/AnyName.txt") #SpecifyingFullPath (AbsolutePath)

Syntax
File object = open (file_name [, access_mode][, buffering])
Parameter details:
file_name: It contains the name of the file. It is always string
access_mode: Default file access mode is read (r).
Buffering: If the buffering value is set to 0, no buffering takes place. If 1, line buffering
is performed.
Example:

Note:

Whenever we want to open a file it should exist in a Relative path (i.e. current directory) or
provide full path i.e. Absolute path

File Different Modes:


Modes Description
r Opens a file for reading only.
'b' Open in binary mode.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w Opens a file for writing only.
a Opens a file for appending.
a+ Opens a file for both appending and reading.
't' Open in text mode. (default)
x Open a file for exclusive creation. If file already exists
Operation fails.

The file Object Attributes:


Once a file is opened and you have one file object, you can get various information
related to that file.

Attribute Description
File.closed Returns true if file is closed, false otherwise.
File.mode Returns access mode.
File.name Returns name of the file.

Open a file Method-I

NOTE:
When working with files in text mode, it is highly recommended to specify the encoding
type. Example as f = open ("test.txt", mode = 'r', encoding = 'utf-8')

Open a file and Close a File


NOTE:
This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file. A safer way is to use a try...finally
block.

Writing to a File
In order to write into a file we need to open it in write 'w', append 'a' or exclusive creation
'x' mode.
NOTE:
We need to be careful with the 'w' mode as it will overwrite into the file if it already
exists.
Write () Method:
Using this method we can write a specific line in the file.
Syntax:
Object.write ("Text")
Writelines () Method:
Using this method we can write a specific multiple lines in the file.
Syntax:
Object.writelines ("Text lines")
Example:

This program will create a new file named 'python.txt' if it does not exist. If it does exist, it is
overwritten. We must include the newline characters ourselves to distinguish different lines.

Reading from a File


To read the content of a file, we must open the file in read mode. There are various methods
available for this purpose.
1. Read () method:
It can read the data depends on size of characters read (size). If size parameter is not
specified, it reads and returns complete the file.

Syntax:
fileObject.read ([count]);

Example:

Example:

Output:

Example: Reading the file and displaying number of characters

readline(): to read individual lines of a file


Syntax:
fileObject.readline ()

Example:

readlines()==> Returns a list of remaining lines of the entire file.


Syntax:
fileObject.readlines ()
Example:

Example: Reading the file and displaying number of Lines

NOTE:
All these reading method return empty values when end of file (EOF) is reached.

Appending a file:
We can able to append a file with the help of 'a'. Append means add the data to an
existing file, under existing data.
Example:
File cursor Positions
The tell () method tells you the current cursor position within the file.

Syntax:
fileObject.tell ()

Example:

seek() Method:
This method changes the cursor position in the file.
Syntax:
seek(offset[, from])

Example:
Working with CSV (Comma Separated Values) Files:
A CSV file is plain text file which stores spreadsheet or database information in a very
simple format. Normally it contains one record on each line, and each field within that record
separated by a comma or another delimiter.

Define Delimiter:
It is a sequence of one or more characters used to specify the boundary between separate.
Example:
A delimiter is the comma character, or Space, or Gap or Colon etc.. a CSV file in
Notepad, Microsoft Excel, OpenOffice Calc, and Google Docs.

Syntax: CSV formated text..!!


Fname, lname, age, salary
Nancy, davolio, 33, $30000
Erin, borakova, 28, $25250
Tony, Raphael, 35, $28700

Bracket delimiters (Also called block delimiters, Region delimiters or balanced delimiters)
() Parentheses.
{} Braces (also called curly brackets.
[] Brackets (commonly used to denote a subscript)
<> Angle brackets.
"" commonly used to denote string literals.
'' commonly used to denote character literals

The first line in a CSV file might contain the names of the columns of data, and is generally
referred to as header. It is most popular format to store data. for large amounts of data we are
using RDBMS
for small amounts of data we are using sperad sheets. But cvs files are replaced both for bigdata,
they are simple, convenient, no drivers, special APIs not required. Python making more simpler
using CSV module.
In PYTHON Environment we can able to work with csv files, we can use built-in module is
called CSV. We can perform the following:
1. Open the file on required mode
2. Create the csv file represented object
3. Read or write or update the data
4. Finally Closed the file
Syntax:
import csv
print(dir(csv)) #To display all properties and methods from csv module
CSV Functions
The CSV module includes all the necessary functions built in. They are:
csv.reader
csv.writer
csv.register_dialect
csv.unregister_dialect
csv.get_dialect
csv.list_dialects
csv.field_size_limit
Example: Creating and Writing in CSV File

Output:

Example: Reading CSV File

Simply Reading: A CSV File


OS Module in Python:

Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.

List Directories and Files


Listdir () ==> It list all files and sub directories inside a directory.

Example:
The rename () Method
It takes two arguments, the current filename and the new filename.

Syntax
os.rename (current_file_name, new_file_name)

Example:

Output:

The remove() Method


You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.
Syntax
os.remove(file_name)

Example

Directories in Python
All files are contained within various directories, and Python has no problem handling
these too. The os module has several methods that help you create, remove, and change
directories.

The mkdir() Method


You can use the mkdir() method of the os module to create directories in the current
directory. You need to supply an argument to this method which contains the name of the
directory to be created.

Syntax
os.mkdir("newdir")

Example

The getcwd() Method:


The getcwd() method displays the current working directory.
Syntax
os.getcwd()

Example

The chdir() Method:


You can use the chdir () method to change the current directory. The chdir() method takes
an argument, which is the name of the directory that you want to make the current directory.

Syntax
os.chdir ("Existingdir")

Example:

The rmdir() Method:

The rmdir () method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed.

Syntax:
os.rmdir ('dirname')

Example:
Os. Walk () Method:
OS. Walk () generate the file names in a directory tree by walking the tree either top-
down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it
yields a 3-tuple (dirpath, dirname, filenames).
Example:

root: Prints out directories only from what you specified.


 dirs : Prints out sub-directories from root.
 files : Prints out all files from root and directories.
15. Working with Database

15.1 Working with Mysql Database:


The interface language of the MySQL database is the standard SQL (Standard Query
Language) which allows for inserts, updates and queries of data stored in relational tables. The
SQL language is also used for the administration of the database for the creation and
modification of tables, users and access privileges

Benefits of Python Database Programming:

 Programming in Python is considerably simple and efficient with compared to other


languages, so as the database programming
 Python database is portable, and the program is also portable so both can give an
advantage in case of portability
 Python supports SQL cursors
 It also supports Relational Database systems
 The API of Python for the database is compatible with other databases also
 It is platform independent
How can I connect MySQL database?
Steps to connect to your database remotely
 Open MySQL Workbench.
 Click New Connection towards the bottom left of MySQL Workbench.
 In the "Set up a New Connection Dialogue" box, Type your Database connection
credentials. ...
 Type your password and click the "Save Password in Vault"
How do I download using MySQL?
You can install MySQL anywhere, such as a portable USB drive (useful for client
demonstrations).
 Step 1: download MySQL. ...
 Step 2: extract the files. ...
 Step 3: move the data folder (optional) ...
 Step 4: create a configuration file. ...
 Step 5: test your installation. ...
 Step 6: change the root password.

How to install mysql connector through command prompt in python:


 Type windowskey+r + r =run
 Type cmd
 It will redirect to cmd
 Type pip install mysql. Connector
 After type pip list , you will find mysql. Connector
 By the help import we will import as follows
Ex:

15.2 Using MySQL for Python:


Import the SQL interface with the following command: >>> import mysql.connector
establish a connection with the database with the following command:
>>> conn=mysql.connector. Connect (host='local host', user='root',passwd='')
Create a cursor for the connection with the following command:
>>>cursor = conn.cursor()
Ex:

Output:

15.3 Retriving All Rows from a Table:

Retrieving Multiple Columns


Now you'll try another simple SELECT statement, this time on the products table. You can
retrieve the values from two columns in the same query by specifying a list of columns after
the SELECT keyword, separating them with a comma.
15.4 Inserting row into a table:
The main goal of database systems is to store data in the tables. The data is usually
supplied by application programs that run on top of the database. Towards that end, SQL has the
INSERT command that is used to store data into a table. The INSERT command creates a new
row in the table to store data. Let's look at the basic syntax of the SQL INSERT command shown
below.

Ex:

15.5 Deleting rows from a table:


If you want to delete a record from any MySQL table, then you can use the SQL
command DELETE FROM. You can use this command at the mysql> prompt as well as in any
script like Python. The following code block has a generic SQL syntax of the DELETE
command to delete data from a MySQL table.

 If the WHERE clause is not specified, then all the records will be deleted from the given
MySQL table.

 You can specify any condition using the WHERE clause.

 You can delete records in a single table at a time.

The WHERE clause is very useful when you want to delete selected rows in a table. This will
use the SQL DELETE command with the WHERE clause to delete selected data into the
MySQL table – tutorials_tbl.

Example:
The following example will delete a record from the nareshit database

15.6 Updating rows in table:

There may be a requirement where the existing data in a MySQL table needs to be modified.
You can do so by using the SQL UPDATE command. This will modify any field value of any
MySQL table. The following code block has a generic SQL syntax of the UPDATE command
to modify the data in the MySQL table

Ex:

You can update one or more field altogether.

 You can specify any condition using the WHERE clause.


 You can update the values in a single table at a time.
The WHERE clause is very useful when you want to update the selected rows in a table.
15.7Creating Database Tables
Here is a generic SQL syntax to create a MySQL table This will use the SQL UPDATE
command with the WHERE clause to update the selected data in the MySQL table tutorials_tbl.

Example
The following example will update the tutorial_title field for a record having the id
16 Regular Expressions
Regular expressions are essentially a tiny, highly specialized programming language embedded
inside Python and made available through the re module.
What is a regular expression?
Regular expression is used to find and replace patterns in a string or file. Each character in a
regular expression is either understood to be a metacharacter with its special meaning, or regular
character with its literal meaning.

What is metacharacter?
Metacharacter is to describe a string patterns and control characters that than strings themselves.

The following list of metacharactes.


Meta character meaning
It matches a set of characters.
Example: [abc] will match 'a', 'b', or 'c'
[]
[a-c] will match 'a', 'b', or 'c'
[a-zA-Z0-9] match characters and numbers.
It matches the last character of the class.
$ If we use $ in [ ], $ is itself a character.
Example:[abc$] matches a, b, c or $
It matches the first character of the class.
^ Matches the beginning of the line in re.MULTILINE
Example: [^n] will matches any character except 'n'
It matches 0 or more possible characters.
*
Example: ab*c --- ac abc abbbc abbbbbc
It matches to 1 or more possible characters.
+
Example: ab+c possiblities abc abbc abbbbbbbc
It matches the 0 or 1 repetitions.
?
Example: ab?c possible are ac abc
It matches that exactly m times.
{ m}
Example: ab {3} c -- abbbc
It matches to m to n times as possible.
{m, n}
Example: ab {3, 5} c --- abbbc abbbbc abbbbbc
\ Backslash \ is string literals in python.
A|B, it matches either A or B. it means once A matches, B will not
|
test further.
() It is used for grouping regular expression.
It matches all characters except the new line character. It is an
. alternate mode re.DOTALL.
Example: a.c -- abc adc afc
Sequence Characters in Regular Expressions:

The following table is Sequence Characters in Regular Expressions

patter meaning equality


n
It n matches the same text as that group.
\n Example: r'([a-zA-Z0-9]+):\1' matches
string 'abc123:abc123'
It used boundary of a string.
\b
Example: r'abc\b' matches 'abc' but not 'abcd'
\B It used empty string means no boundary.
\d Matches any decimal digit. [0-9]
\D Matches any non-digit characters. [^0-9]
\s Matches any whitespace character. [ \t\n\r\f\v]
\S Matches any non-whitespace character. [^ \t\n\r\f\v]
Matches any alphanumeric character plus the
\w [a-zA-Z0-9_]
underscore '_'.
\W Matches any non-alphanumeric character. [^a-zA-Z0-9_]
\A Matches start of the string.
\Z Matches end of the string.
\\ Matches a backslash (\) character.

The following table is whitespace character patterns

Escape English ASCII nam


sequence name e
'‘ space SP
'\n' newline NL
'\r' carriage CR
return
'\t' horizontal tab HT
'\f' form feed FF
'\v' vertical tab VT

How to use regular expression in Python?


In python, we can use the regular expression re module.

What is re module in python?

The re module provides an interface to the regular expression engine, allowing you to compile
REs into objects and then perform matches with them.

How to compile regular expression?


Regular expression pattern are compiled into a regular expression object, which can be used for
methods for various operations such as searching or string substitutions.
In python provided re.compile() for compile the regular expression pattern.

Syntax:
re.compile(pattern,flag=0)

 It returns a regular expression object.


 In python regular expression functions and methods take an optional argument called a
flags. It can be modifies the given regex pattern.
Example:

Advantage of re.compile():
 By using re.compile() and saving the resulting regular expression object.
 We can use several times in a single program.

For example we can use match method.

The following are regular expression methods and function:

Method description
match() from beginning of the string
search() It matches any location through a string.
findall() It finds all substrings and returns them as a list.
finditer() It finds all substrings and returns them as an iterator.
split() It returns a list.
sub() Replace the string. Return new string.
subn() Replace the string. Returns a tuple.
escape() New string return.

re.findall(pattern, string, flags=0)

 Return all non-overlapping matches of pattern in string, as a list of strings.


 The string is scanned left-to-right, and matches are returned in the order found.
 If one or more groups are present in the pattern, return a list of groups; this will be a list
of tuples if the pattern has more than one group. Empty matches are included in the
result.
Example:

Example: the following example in the pattern presents one or more groups, it return a list of
tuple groups.

Example:

The following table is python flags.

Flag long flag meaning


re.I re.IGNORECASE ignore a case
re.M re.MULTILINE Consider the each line begin/end like {^, $}
re.S re.DOTALL Match a newline also.
re.U re.UNICODE It follow the Unicode rules ( {\b,\B,\w,\W})
re.L re.LOCALE It follow the locale ( {\b,\B,\w,\W})
re.X re.VERBOSE Comment allow in regex.
re.I
re.IGNORECASE

It performs matching case-insensitive. For example expression like [A-Z] will match lower case
letters also.

Example:

re.M
re.MULTILINE
When specified the pattern character ‘^’ matches at the beginning of the string at the each line.
When specified the pattern character ‘$’ matches at the ending of the string at the each line
before new line.

Example:

re.S
re.DOTALL

Make the '.' special character match any character at all, including a newline; without this flag, '.'
will match anything except a newline.

Example:
re.U
re.UNICODE

Make the \w, \W, \b, \B, \d, \D, \s and \S sequences dependent on the Unicode character
properties database. Also enables non-ASCII matching for IGNORECASE.

re.L
re.LOCALE

Make \w, \W, \b, \B, \s and \S dependent on the current locale.
re.X
re.VERBOSE
 This flag allows you to write regular expressions that look nicer and are more readable by
allowing you to visually separate logical sections of the pattern and add comments.
 Whitespace within the pattern is ignored, except when in a character class, or when
preceded by an unescaped backslash, or within tokens like *?, (?: or (?P<...>.
 When a line contains a # that is not in a character class and is not preceded by an
unescaped backslash, all characters from the leftmost such # through the end of the line
are ignored.

Example:

Output:
Match() and search() methods:

If no match can be found, match() and search() method returns None. If can match object
instance returned.

re.match(pattern, string, flags=0):


If zero or more characters at the beginning of string match return a MatchObject instance
otherwise return None.

Example:

re.search(pattern, string, flags=0)

It returns MathObject when pattern string matches any location of the first occurrence otherwise
returns None.
Example:

Example: the following example to search by using regular expression.


Match objects methods:
Match objects always have a boolean value of True. Since match() and search() return None
when there is no match.

The following are match objects methods.

Method Description
group() Return a string or tuple contains all matched by the RE.
groups() Return a tuple containing all matched by the RE.
groupdict() return the dictionary
start() Return the starting position of the match
end() Return the ending position of the match
span() Return a tuple containing the (start, end) positions of the match
group([group1, ...]):

It take an arguments should be integers and returns one or more subgroup of the match otherwise
not matched return a None. If there is a single argument return string otherwise tuple. If there is a
0 argument the whole matched pattern. (One) 1 is the first captured string etc.

Example:
Note: if group number is larger or negative number of groups defined in the pattern, an
IndexError exception is raised.

Example 2:

groups ([defaults]):
It Returns a tuple containing all the subgroups of the match.

Example:
Name capturing group:
Python re module first offer to solution named capturing groups and named backreferences.

(? P<name>regexp)
It captures the string matched by regexp into the group name.
The name can having a letters and numbers but must be start with a letter.

Example:

(?P<PhoneNo>98$){2,4} matches 988 or 9888 or 98888. The group PhoneNo matches 98$.
(? P=name)
Question mark, P and equal sign are syntax part but don’t any capturing or group. It is just a back
reference through syntax.

Example:
(? P<gender>M|F)=(?P=gender) matches M=M or F=F but not F=M or M=F.

2nd example is HTML tag

< (? P<tag> [A-Z][A-Z0-9]*) \b [^>]*>.*?</(?P=tag)>.

groupdict([default]):

Return a dictionary containing all the named subgroups of the match, keyed by the subgroup
name.

Example:
start([group])
end([group])

 It returns the indices of the start and end of the substring matched by group.
 Defaults to zero means whole matched substring.
 If did not match exists group, it return -1.

Example:

Explanation:
Here bcdf whole group is 0 by matching regular expression,
1st subgroup string is cdf start index position 2 and end index position is 5,
2nd subgroup string is df start index position 3 and end index position is 5.

span([group]):

 It return the tuple (re.start(group),re.end(group)).


Example:
The following are match object attributes:

Attribute Description
passed to the search() or match() method of the
pos
RegexObject.
endpos passed to the search() or match() method of the RegexObject.
lastindex The integer index of the last matched capturing group
lastgroup The name of the last matched capturing group, or None
re produced MatchObject instance.
string The string passed to match() or search().
String:
The string passed to match() or search().

Example:

pos
 The value of pos which was passed to the search() or match() method of the
RegexObject.
 This is the index into the string at which the RE engine started looking for a match.

endpos
 The value of endpos which was passed to the search() or match() method of the
RegexObject.
 This is the index into the string beyond which the RE engine will not go.

Example:
lastindex
 The integer index of the last matched capturing group, or None if no group was matched
at all.

For example, the expressions (a)b, ((a)(b)), and ((ab)) will have lastindex == 1 if applied to the
string 'ab', while the expression (a)(b) will have lastindex == 2, if applied to the same string.

lastgroup
 The name of the last matched capturing group or None if the group didn’t have a name,
or if no group was matched at all.

re
 The regular expression object whose match () or search () method produced this
MatchObject instance.

String modifications:
The following are string modification methods.
Method description
split() It returns a list.
sub() Replace the string. Return new string.
subn() Replace the string. Returns a tuple.

re.split (pattern, string, maxsplit=0, flags=0)


Split the string by occurrence of pattern.

If parentheses are in pattern, then the text of all groups in the pattern is also returned as
part of the resulting list.
 If maxsplit is nonzero, at most maxsplit splits occur and the remainder of the string is
returned as the final element of the list.
Example:
Here each word split in individual string and return a list.
Example 2: the following example to split a string return a numeric values.

Explanation:
‘1A2B3C’, each character removes and return a numeric value. The last character is string return
null.
Example 3: the following example separated sub group wise.

re.sub(pattern, repl, string, count=0, flags=0)

 Return the string obtained by replacing the leftmost non-overlapping occurrences of


pattern in string by the replacement repl.
 If the pattern isn’t found, string is returned unchanged.
 repl can be a string or a function;
 If it is a string, any backslash escapes in it are processed.

Example: the following example string starting and ending letter r replaced
Example 2: the following example replaces digits to strings places

Example: the following example to remove digits from string.

Example: the following example to remove non word characters.

Example: the following example digit number square value by using function
re.subn(pattern, repl, string, count=0, flags=0)

Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made).

Example:

Example 2: the following example using with lambda function

re.finditer(pattern, string, flags=0)


 Return an iterator yielding MatchObject instances over all non-overlapping matches for
the RE pattern in string.
 The string is scanned left-to-right, and matches are returned in the order found.
 Empty matches are included in the result.

Example:

What is raw string notation?

 Raw string notation (r"text") keeps regular expressions sane.


 Without it, every backslash ('\') in a regular expression would have to be prefixed with
another one to escape it.

For example identify the functionality

 When one wants to match a literal backslash, it must be escaped in the regular
expression.
 With raw string notation, this means r"\\".
 Without raw string notation, one must use "\\\\".

Example: the following example to identical functionality


19. Applications of Python
Now a day’s python implements a many different types of Applications. As see the following

1. Console Application
2. Web application development
3. GUI designing
4. Games Development
5. Network programming
6. Robotics
7. Scientific and numeric field
8. Data Analysis
9. Business Applications
10. Artificial intelligence
11. Machine Learning
12. Audio and video software development

Now let’s the brief details about Application of Python

1. Console Application in python


A console application is a simple application that can run inside the IDLE but the output has the
form of your programs is printed to the IDLE.

2. Web application development


Python is a scripting language. We can develop the large scale web application development and
also provides several frameworks like Django and Pyramid and micro-frameworks like Flask and
Bottle for easing the process of web development.

3. GUI Designing
Python offers a develop of GUI application such as PyQt, Tkinter, Kivy, etc using these
modules. Tkinter is the mostly used by the develops for the development of GUIs.

4. Games Development
Python programming language is specially intension of to make games and other multimedia
applications by using pygame library. It is an open-source module and it can run across many
platforms and operating systems.

5. Network programming
The network application is client-server application. The HTTP protocol is an application for
distributed, collaborative, hypermedia information systems.
In python3 urllib3 is a standard module provides most of the HTTP capabilities you need but the
API are thoroughly broken.
In python HTTP takes a request the following working
- making your integration with web services
- There is no need to manually add query strings to your URL's or to form-encode your POST
data.
- It 100% alive and HTTP connection pooling.

6. Robotics or automation
Python introduce various frameworks used in robotics such as robotic operating system (ROS),
image processing libraries (OpenCV)- Python and PyQT.

7. Data Scientific and numeric field


In python, so many libraries are active data science and ML. The following are top of the active
python libraries in the areas.

 MATPLOTLIB
 NUMPY
 SCIPY
 PANDAS
 SEABORN
 Bokeh
 plotly

MATPLOTLIB:
Matplotlib module is use for data visualization. For example we can quickly generate line
graphs, histograms, pie charts and much more with matplotlib. When we use Jupiter, it can take
advantage of interactive feature is like zooming and panning. It also supports multiple GUI
backend of all operating systems and is enabled to export leading graphics and vectors formats.
The following are can make any visualizations

Line plots
Scatter plots
Pie charts
Bar charts and histograms
Stem plots
Contour plots
Quiver pots
Spectrograms and creating a label, grids, legends and many other formatting entities with
Matplotlib.

NUMPY:

Numpy stands for Numerical python. It is an extension module that offers fast, precompiled
functions for numerical routines. As the result it becomes much easier to work with large
multidimensional arrays and matrices. When we use NumPy, we don't have to write loops to
apply standard mathematical operations on an entire data set. Therefore it doesn't provide
powerful data analysis capabilities or functionalities

SCIPY:

SciPy is used for linear algebra, integration, optimization, statistics and other frequently used
tasks in data science. It's user-friendly and provides for fast and convenient N-dimensional array
manipulation.

Scipy's main functionality is built upon NumPy, so its arrays depend on NumPy. It also provides
numerical routines like numerical integration and optimization with the help of its specific sub
modules.

PANDAS:

Pandas are a python package that designed high-level data structures and tools that are perfect
for data wrangling and data munging. It is designed to enable fast and seamless data analysis,
easy data manipulation, aggregation and visualization. A panda makes it easy to handle missing
data by using Python and prevents common error resulting from misaligned data derived from a
variety of sources.

Example: there are two main data structures in the library

1) One dimensional
2) Two dimensional

One dimensional means is series of data

series
A X0

B X1
C X2

D X3

Two dimensional means data Frames

Data Frames

A B C D

0 A0 B0 C0 D0

1 A1 B1 C1 D1

2 A2 B2 C2 D2
When we want to receive a new Dataframe from
these two types of 3 A3 B3 C3 D3 structures, as a result we will
receive such DataFrame by appending a single
row to a DataFrame by passing a series the following table

Data Frames

A B C D

0 A0 B0 C0 D0

1 A1 B1 C1 D1

2 A2 B2 C2 D2
Here the list of that can do with pandas
3 A3 B3 C3 D3
1) it can easily delete and add columns from data
Frame 4 X0 X1 X2 X3
2) it convert data structures to Data frame
objects
3) it can handle missing data, represents as NaNs
4) Powerful grouping by functionality.
SEABORN:
Seaborn module is focused on the visualization of statistical models and essentially treats
Matplotlib as a core library (like Pandas with NumPy). We are trying to create heat maps,
statistically meaningful plots or aesthetically pleasing plots, it is done it all default.
As it understands the Pandas Data Frame, they both work well together. Seaborn can be easily
installed.
Bokeh:
It is also visualization library. it main aimed at interactive visualizations. it independent of
Matplotlib. The main focus of it is interactivity and makes its presentation via modern browsers
in the style of Data-Driven Documents.

Plotly:

The Plotly is a web-based toolbox for building visualizations, exposing APIs to some
programming languages. There is a number of robust, out-of-box graphics on the plotly website.
It is use plotly you will need to set up your API key. The graphics will be processed server side
will be posted on the internet, but there is a way to avoid it.

8. Data Analysis

Data is information of a raw format with increasing data size. It has become a need for inspecting
cleaning, transforming and modeling data with the goal of finding useful information, making
conclusions and supporting decision making these processes known as data analysis.

Data analytics using various domains


 Analysis
 Data analysis process
 Skills for data analysts
 Data mining
 Characteristics of Data Analysis

9. Business Applications
In recent year, python modules have growth in the business, e-commerce and trading sectors. It
is also quite feasible to make ERPs with help of modules provided by python. the python is used
for the qualitative and quantities analysis of stocks cryptocurrencies etc. the simple application of
python we use of module like Numpy, Pandas, scipy etc is prediction of stock prices and cryptos
in business world being easier to maintains and comparatively lesser code density and its ability
to easy to integrate with other platforms and languages.

10. Artificial intelligence


the father of Artificial Intelligence John McCarthy defines it is the science and engineering of
making intelligent machines, especially intelligent computer programs also intelligence separate
us from everything in the world it has to apply knowledge and also improve skills that played a
significant role in our evolution. the following domains draws a AI
Computer Science
Cognitive Science
Engineering
Philosophy
Physiology
Psychology
Statistics
Logic
Mathematics
Natural Sciences

11. Machine Learning

Machine learning is a science. It is to make the machine capable of taking the decision itself.
This system has ability to learn from past experience or analyze historical data. It provides
results according to its experience.

There three types of Machine Learning


1. Supervised learning
2. Unsupervised learning
3. Reinforcement learning

a. Supervised learning:
In the context of artificial intelligence (AI) and Machine learning (ML) is a type of system in
which both input and desired output data are provided. Input data and output data are labeled for
classification to provide a learning basis for future data processing called a supervised learning.

b. Unsupervised learning:
The unsupervised learning means, when a retailer wishes to find out what are the combination of
products, customers tends to buy more frequently. it may be used in pharmaceutical industry to
predict which diseases are likely to occur along with diabetes. For example is k-means clustering
algorithm.

c. Reinforcement learning:
In this reinforcement, where the machine is trained to take specific decision based on the
business requirement with maximum performance.

The following libraries are used in ML


SciKit-Learn:
scikits is a package of scipy stack designed for specific functionalities like image processing and
machine learning facilitation. It is most prominent packages is scikit-learn. this package builds of
the scipy and make use of its math operation.

The scikit-learn exposes a consistent interface to the common machine learning algorithms,
making it simple to bring ML into production systems. Combines these libraries is a quality code
and good documentation, it is easy use of the high performance and de-facto industry standard
for machine learning with python.

12. Audio and video software development


In python, MoviePy is library. It is used for video editing, cutting, concatenations, title
insertions, video compositing, video processing and creation of custom effects. MoviePy can
read and write all the most common audio and video formats including GIF and runs on
Windows, mac and Linux with Python 2.7+ and 3.

The following diagram to understand the details about python implementation sectors

Web development Applications:

Python is an interpreter and high-level language. It also implements the basic concepts of an
object-oriented programming language (oops). Python is different from other programming
languages such as Java, C++ and c and unique syntax. It is simple and easy to learn.

We can build a full-fetched web application in python. The present there are already some great
python frameworks that we can use for web development.

What is web frame work?


Present days to communicate with user using web develop applications. Most developers
develop a web application by using framework to create code and develop applications. The web
framework is a collection of packages and modules that allows easier development of websites.
The developers use the framework; they can focus on the core logic of the application rather than
on the other elements.

Now let’s to start a develop web application in python, we will require a platform or framework
to code. To remember that considers the size and complexity of your application or project.

Python has supports two types of frameworks used while developing applications.
1. Full-stack Framework.
2. Non Full-stack framework.

1. Full-Stack Framework:
The full-stack framework provides complete supports to development software such as form
validation, form generators and template layouts. The following are full-stack framework.

a. Django:
Django is developed by Django Software Foundation. It is a full-stack python web framework
and it is an open source and free to use framework. It released in July 2005. It creates a complex
code and applications in easiest way for developers and less time to compare to other
frameworks. It follows a model-view-template architectural pattern.

It has a collection of libraries written in the python language. It is the reusability of components
and less code. It is main feature of Django are URL routing, object-relational mapper (ORM),
authentication mechanism, template engine and database schema migrations.

Django supports multiple databases such as PostgreSQL, MySQL, SQLite and Oracle. It becomes
easier for developers to transfer the code from one database to another.It also support for web
servers. Django is used by the most of the Instagram, Pinterest, Disqus, Mozilla etc.

The following are web2py features


 It is cross-platform framework that provides support for windows, unix/linux, mac, google
app engine and many other platforms.
 no additional installation and configuration
 It is built-in components to handle HTTP requests, HTTP responses, cookies and sessions as
well.
 it ability to read multiple protocols
 It security to data against all possible threats such as cross-site scripting, injection flaws and
execution of infected files.
 it follows a model-view-controller(MVC) pattern
 it supports for a role-based access control and internationalization
 It allows users to embed jquery for ajax and UI effects.
As the so many full-stack frameworks such as
a. CubicWeb
b. TurboGears
c. Pylon
d. Giotto

Non-Full-stack Framework:
Non-full-stack framework is not provide additional functionalities and features to the users. The
developers need to add a lot of code manually.

Flask:
Flask is developed by Armin Ronacher. it is a powerful python web application framework. it is
generally termed a microframework because it does not have the functionalites
 no specific tools and libraries
 no database abstraction layer
 No form validation
The functionalities provided by the above-mentioned elements are now provided by third-party
libraries. It depends on the Werkzeug WSGI toolkit.

 Built-in development server and debugger also


 It support for unit testing
 It incorporates RESTful request dispatching
 It establishes secure client-side sessions
 Compatible with Google App Engine
The following are also non-full-stack frame works
 Sanic
 CherryPy
 Bottle

Now we start the web application by using Django

What is Django?

Django is an open source web application framework. It is a set of components that helps you to
develop websites faster and easier.

Advantages of Django?

 It supports ORM (Object-Relation Mapping). Mapping means all the insert queries will take
up a lot of your time with an ORM like Django all you have to do define how certain
classes’ should be mapped to certain models.
 The components are integrated and it provides a fully featured and secure authentication
systems.
 Admin Interface: it manages the content of your website with an django interface. it
handling users, creating new users all can be done quickly with this smart interface.
 Language support: It provides multi-language support. Along with that is also provides
locale specific settings.

How to install Django on windows?

We can follow the below steps

Step 1:
We install python IDLE

Step 2: after install Python IDLE, we follow steps for Django installation

Step 3: open window power shell in start button and run as administrator

Step 4: we need to virualenvwrapper. It is used for creating isolation environments. it id used for
each ne django project
Step 5: next we are install Django with the pip command

Step 6: now let’s check the django version the following command

Step 7:
Now we create a new directory to store the new project that we are going to create web

Step 8: let's we start healthcare project with django-admin startproject projectname.

Step 9: let’s check the directories

Step 10: it automatically created some files let’s check by command ls –r


Step 11: we can run the manage.py file

Step 12: now check in chrome

How to uninstall django?


We want uninstall the django just pip uninstall django
What is django file in python?
healthcare/
manage.py
healthcare/
__init__.py
settings.py
urls.py
wsgi.py
 Healthcare/ is a root directory. It is a container for your project. We can rename it to
anything.
 manage.py is a command-line utility. it is a interact with this Django project in various
ways. we can read all the details about manage.py in django-admin and manage.py
 The sub directory healtcare/ is a python package for your project. This is the python
package name we will need to use to import anything inside it for example
healthcare.urls.
 healthcare/__init__.py is an empty file. it is a constructor in python class and should be
considered as a python package. if you want more details, reads a class object class.
 healthcare/settings.py is a settings/configuration for this Django project. Django settings
file will tell you about all how settings work.
 healthcare/urls.py is declarations of URL for this Django project. it is a table of contents
of your Django-powered site. we can read a more about URLs in URL dispatcher.
 healthcare/wsgi.py is an entry-point for WSGI-compatible web servers to serve your
project.

What is wsgi.py in Django?


wsgi is stands for web server gateway interface. The authored by Philip J Eby and published on
December 2003. It is how communicates with web applications and how the application can be
changed and to generate requests.

It is designed for only one fast CGI, mod_Python. The CGI or other API is a specific web server
and they didn't allow for interoperability. mod_python, and an Apache module and it were not an
official specification and there was little security. Developers needed a new solution to combine
the execution of python web application.

Where is WSGI placed in, it had a standard interface for routing web apps and frameworks to
web servers. The framework traces its main origin to common gateway Interface (CGI) and the
CGI is success because it is work with many languages in the early days of the internet but the
downside was slow and limited.

There are two sides to the WSGI framework


1. WSGI Application made from python script
2. WSGI Server/gateway like Apache or Nginx
Client
Respon Requ
se est

Server

WSGI
return start_ response application_ callable
iterator (status, header, (environ, start_response)
exe_info)

Application
The WSGI paces two arguments through a __call__ method they are

1) WSGI environment is first argument


2) Functions that starts the response

When receive a request from the HTTP clients, it directed towards the application that an
application callable is invoked by the gateway or server. Finally the WSGI became the accepted
approach for running python application.

It is the server that triggers the web app and transmits data with callback function to the app.
The processing of the request on the application side while the server receives the response by
making the callback function. WSGI supports are Django, web2py, Flask, TuroGears and
CherryPy for python frameworks.

Advantages of WSGI:

1) simple:
The WSGI is a simple learning and easier to pick up and with no configuration or installation
hassles.

2) Flexibility:
The flexibility means, we can change the web stack components without changing the codes at
all and without changing the application that runs the WSGI servers.

3) Scalability:
Many requests can't handle a framework but WSGI servers can handle thousands of requests
concurrently and route them from the web server.

4) Speed:
WSGI is helps to speed up the python web application development because don't need to know
any complicated things just basic knowledge about the how the interface works. we can combine
multiple platforms like node.js and wsgi server to become a part of micro-service architecture so
it as the strength of the each platform.

5) reusable middleware:
We can enhance the functionality of WSGI through existing middleware components like
authentication or authorization, sessions, caching, filtering etc. it also saves the time.

Creating first web application in python:

We can follow the below steps creating web application


You are first time create web application using Django, you have to follow some initial setup
files. We need to auto-generate some code that establishes a Django project.

step1: where we would like to store your code and go to that location using command prompt for
drive.

Step2: It will create mydemo folder in F:\ drive and the following directory files check

mydemo/
manage.py
mydemo/
__init__.py
settings.py
urls.py
wsgi.py

Step3: now let’s check the develop server and find the url

Step4: creating a polls


What is a polls?
The polls is a generate some consists of python package that follows a certain convention. Here
the following Django generates the basic directory structure of an application.

The following are directory structure


polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
step5: now let’s create a under polls/view.py write the following python code.
Step6: now create urls.py file under polls directory (folder) and write following code
It is call the view and we need to map it to a URL for this we need a URL configuration.

Step 7: in mydemo/urls.py is the root URL configuration and an import for django.urls.include
and insert an include() in the urlpatterns list and write the following code.

Step8: now let’s run the application and write the following

Step9: copy the url and browse the type the server
Path( ) function in python:

The path() function is passed a four arguments. Two arguments are required that are route and
view another two are optional that are kwargs and name. Here the explanation below

1. path() argument: route


route argument is a string that contain a URL pattern. When process a request, when the Django
start at the first pattern in urlpatterns. The pattern don't search the GET and POST parameters or
the domain name.
Example: in request https://www.nit.com/mycourse, the URLconf will look for mycourse
In another request https://www.nit.com/mycourse/?page=3, the URLconf will also look for
mycourse/.

2. Path() argument: view


When Django finds a matching pattern, it calls the specified view function with an HttpRequest
object as the first argument and any "captured" values from the route as keyword arguments.

3. Path() argument: kwargs


It can be a passed arbitrary keyword arguments in a dictionary to the target view. it is an optional
argument.

4. Path() argument: name


This is a great feature allows you to make a global changes to the URL pattern of your project
while only touching a single file. The Naming your URL lets refer to it unambiguously from
elsewhere in Django, especially from within templates.

Example: the following example to mapping view to display the data

The above example adding a function to the view under poll/view.py


After urls.py file to change the url under polls/urls.py file

Next we have to run the program in power shell command prompt

Copy the url and type route string

You might also like