Python Hand Book
Python Hand Book
Python Hand Book
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.
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
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
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.
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.
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.
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.
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
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.
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.
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.
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN
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
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
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)
print(i)
Print n odd numbers Output
for i in range(1,10,2):
13579
print(i)
print(i*i)
print(i*i*i)
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.
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
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.
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
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:
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.
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
Example:
Output:
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:
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:
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
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 ( )
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.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
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.
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
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.
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
Or Truth table
operand1 operand2 Operand1 or operand2
True True True
False True True
True False True
False False False
Ex:
Ex:
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]
Example:
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:
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
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:
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:
title () - Return a title (first character of each word capitalized, others lowercased) cased string.
Ex:
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:
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.
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
Example:
Output:
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.
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.
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+.
It more complicated actions you can code in if statement but it dictionaries are good at
associating values with key.
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
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.
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.
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:
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
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?
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.
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:
>>>list1=[10,20,30,40,50,60]
Example 1:
Output:
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:
Output:
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.
Output:
6.1.8 operations on list
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:
Example:
Output:
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:
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
Output:
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:
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.
Example 1:
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:
Explanation:
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:
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:
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:
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:
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)
Example:
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.
Syntax:
List1= [ […..], [……], […..] etc.]
Example 1: the following example customer order table, there is online and offline users stored
into another lists.
Output:
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
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:
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:
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:
Nested if condition:
Syntax:
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.
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.
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
Output:
Example2:
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.
Or, tuple is created with a comma separated list of values using parentheses for quickly
understand in python code as tuple
Output:
b. With argument pass to tuple function, the argument is a sequence (string, list or
tuple).
Example:
d. Create a tuple with data items as list, tuple, string and int
Output:
6.2.3 Accessing elements using slicing operator:
“:”( 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.
Example:
tuple unpacking:
the values on the right side of assignment operator (=) are called tuple unpacking
Example 1:
Note: tuple can’t directly assign an item because tuple an immutable data type. i.e you can’t
modify the elements.
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.
Example:
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:
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:
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:
Output:
Output:
Output:
6.2.7 Methods on tuple
In tuple there are two methods
1. Count
2. Index
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.
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
Example 2:
Note: nested tuple elements can’t convert to set.
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 ().
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.
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:
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).
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.
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:
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:
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
Example:
Example 2: the following example we compare & 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
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.
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 1:
The following table we can understand the details information update methods and methods.
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
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)
Syntax:
Set1 = {comprehension}
Fset1 = frozenset({comprehension})
Example 1:
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.
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.
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:
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).
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.
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:
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:
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
Example:
Example 2: the following example we compare & 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
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.
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 1:
The following table we can understand the details information update methods and methods.
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
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)
Syntax:
Set1 = {comprehension}
Fset1 = frozenset({comprehension})
Example 1:
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:
6.4.7. Deleting the Dictionaries
To delete dictionaries we use the del keyword and after deleting the dictionaries it raises
the error
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
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:
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:-
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:-
Example:-
Example:-
Values ():-
It returns a list of all the values available in a given dictionary
Syntax:-Dict.values ( )
Example:-
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
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
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…
You can also create your own functions to do more specific tasks that are called user-defined
functions.
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.
Output:
1. Function arguments
2. Default arguments
3. Keyword arguments
4. Positional Argument
5. arbitrary arguments (variable length arguments)
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 1: the following example to square a next number to pass the arguments.
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.
Output:
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.
Output:
200
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:
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.
Output:
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:
Example:
Output:
Output:
Output:
Welcome to Naresh It
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.
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.
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:
Example:
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
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:
Example 2:
Example 3:
Output:
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
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)
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.
Here, value of ‘a’ is incremented and b value also assign same value check the where we store
same.
Dynamic name binding:
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)
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.
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.
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.
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:
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:
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.
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.
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.
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.
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.
Class customer:
Discount_amount= 1000
We can prove that class variables could be accessed by your class and at the same time instance
of the class.
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
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.
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
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.
@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()
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.
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.
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)
Example:
Output:
issubclass(class, classinfo)
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.
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:
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:
Exception:
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.
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.
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.
Syntax:
try:
statements
except1:
statements
except2:
statements
…
Exceptn:
Statements
Example:
Output:
Example:
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:
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:
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.
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.
The datetime module supplies classes for manipulating dates and times in both simple and
complex ways.
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:
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) :
days, seconds and microseconds are then normalized so that the representation is unique, with
Example: the following example to calculate hours and days passing arguments and also using
on days and seconds methods.
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.
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:
Note: we can’t operate multiplication operation on timedelta object. But we can do through their
methods because return integer type value.
date Objects:
It represents a date (year,month,day).
Example:
This is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and
date2 + timedelta == date1 after.
Example:
date.isoformat()
Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’.
It is equivalent to str(d1)
Example:
date.strftime(format)
Return a string representing the date, controlled by an explicit format string.
Time object:
A time object represents a (local) time of day, independent of any particular day, and subject to
adjustment via a tzinfo object.
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
Example:
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.
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
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.
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.
What is iterator?
The built-in iter function can read an all iterables to get an iterator from them.
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.
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.
Syntax:
next(iterator[, default])
In case the iterator is over the default value returned. The default value was not provided it
raised StopIteration.
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])
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
Syntax: itertools.accumulate(iterble,[,func])
Example:
9) itertools.cycle:
cycle is an infinite iterator
Syntax: itertools.cycle(iterble)
Example:
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:
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
Output:
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
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:
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:
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 return a JSON format, in python use make_api_call (), and they
are called all over codebase.
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.
Python closuer defines a when a nested function references a value in its enclosing scope the
following conditions
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
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
Attribute Description
File.closed Returns true if file is closed, false otherwise.
File.mode Returns access mode.
File.name Returns name of the file.
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')
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.
Syntax:
fileObject.read ([count]);
Example:
Example:
Output:
Example:
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.
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:
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.
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:
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.
Syntax
os.mkdir("newdir")
Example
Example
Syntax
os.chdir ("Existingdir")
Example:
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:
Output:
Ex:
If the WHERE clause is not specified, then all the records will be deleted from the given
MySQL table.
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
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:
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 re module provides an interface to the regular expression engine, allowing you to compile
REs into objects and then perform matches with them.
Syntax:
re.compile(pattern,flag=0)
Advantage of re.compile():
By using re.compile() and saving the resulting regular expression object.
We can use several times in a single program.
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.
Example: the following example in the pattern presents one or more groups, it return a list of
tuple groups.
Example:
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.
Example:
It returns MathObject when pattern string matches any location of the first occurrence otherwise
returns None.
Example:
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.
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]):
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.
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.
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 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:
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 "\\\\".
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
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.
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.
1) One dimensional
2) Two dimensional
series
A X0
B X1
C X2
D X3
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.
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.
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.
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 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.
The following diagram to understand the details about python implementation sectors
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.
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.
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.
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.
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
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.
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
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.
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
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