Complete Python With Numpy and Panadas
Complete Python With Numpy and Panadas
Garbage collector: A garbage collector is one of the software components in python software,
which is running in the background of a regular python program and whose role is to collect /
remove unused memory space.
Hence Garbage collector is taking care about automatic memory management.]
ii) Python programming provides an inbuilt facility called “Garbage collector”, which
collects unused memory space and improves the performance of python based
applications.
iii) Python provides developer friendly syntaxes. So that we can develop error free
programs in a limited span of time.
7. Extensible:
The other languages (C, C++, Java..etc.,) are integrating the code / snippets /
scripts of python. The facility is called extensible.
8. Embedded:
The python code can also integrate the code of other languages. This property is
called Embedded.
10. Portable:
Python is one of the portable languages because applications / projects can run on
any OS / platform without considering the hardware (processor) and software (OS) bench
marks.
1. Identifier’s
2. Literal’s
3. Object Referencing
4. Data types
Definition of Variable:
A variable is one of the identifiers, Whose value can be changed during execution
of the program.
1) int():
=> This function is used for converting any valid other type value into int type value.
syntax:- varname2=int(varname1)
Examples:-
>>>a=12.34 # float value
>>>b=int(a) # converting float value into int value
>>>print(b, type(b))------ 12 <class,'int'>
>>>a=True
>>>b=int(a)
>>>print(b, type(b))------1 <class,'int'>
>>>a=2+3j
>>>b=int(a)---------------TypeError----unable to convert complex into int
b) oct()
=>This function is used for converting Decimal Number System data into Octal number System
data.
syntax:- varname= oct(decimal number System data)
Examples:
>>>a=19
>>>b=oct(a)
>>>print(b)--------0o23
c) hex()
=>This function is used for converting Decimal Number System data into HexaDecimal number
System data.
Syntax:- varname= hex(decimal number System data)
2) float()
=> This function is used for converting any valid other type value into float type value.
syntax:- varname2=float(varname1)
Example:
>>> a=12
>>> b=float(a)
>>> print(b, type(b))-----------12.0 <class 'float'>
>>> print(float(True))--------------1.0
>>> print(float(False))-------------0.0
>>> print(float("12.34"))---------12.34
>>> print(float(2+3j))-----can't convert complex to float
>>>print(float("4x.4y")---error
>>>print(float("12"))---------12.0
Note:- print(int(0b1111))-----------------15
print(float(0b1010.0b1010))--------error
print(float(0b1111))-------------15.0
3)bool()
=>This function is used for converting any valid other type value into bool type value.
syntax:- varname2=bool(varname1)
Examples: ( HINT:-Every Non-Zero value is True and Zero value is False )
>>>print(bool(10))-------------True
>>>print(bool(12.34))---------True
>>>print(bool(0))--------------False
>>>print(bool(0.0))------------False
>>>print(bool(2+3j))----------True
>>>print(bool("python"))-----True
>>>print(bool("0"))------------True
>>>print(bool(" "))------------True
>>>print(bool(""))-------------False
>>>print(bool("0.0"))---------True
5) str()
=>This function is used for converting any valid other type value into str type value.
syntax:- varname2=str(varname1)
Examples:
>>>a=10
>>>b=str(a)
>>>print(b, type(b))--------10 <class,'str'>
>>>print(str(12.34))--------'12.34'
>>>print(str(True))---------'True'
>>>print(str(2+4j))---------'2+4j'
1) str:
=>'str' is one of the pre-defined class
=>The purpose of this data type is to store string /character either in the form of a single line of
text (or) multi line of text.
b)String slicing:
=>The process obtaining range of characters / substring from the given main String is called
String Slicing.
Syntax:- str object[begin:end]
This syntax gives range of chars from begin index to end-1 index provided begin index < end
index otherwise we never get any output(' ')
Examples:
>>>s="PYTHON"
>>>print(s[1:5])-----YTHO
>>>print(s[2:4])-----TH
>>>print(s[0:4])-----PYTH
>>>print(s[-6:-3])---PYT
>>>print(s[-5:-1])---YTHO
>>>print(s[12:1])---no output
>>>print(s[-6:-12])---no output
Special Points:
=>If we don't specify end index then python environment takes no.of chars-1 as end index
position
Example:-
>>>s="PYTHON"
>>>print(s[1:50])-----YTHON
>>>print(s[-100:-2])---PYTH
>>>print(s[1:])-----YTHON
>>>print(s[ : 4])----PYTH
>>>print(s[:])----PYTHON
Examples:
>>>l=[10,20,256]
>>>b=bytes(l)-------error bcoz exceeds the range(0,256)
>>>l1=[10,20,255]
>>>b=bytes(l)
>>>type(b)----------<class, 'bytes')
>>> for x in b:
print(x)------10 20 255
>>>print(b[0])-------10---- indexing allowed
>>>for x in b[0:3]:
print(x)-------10 20---slicing allowed
>>>b[0]=122---------Error-- bcoz bytes object is immutable.
Note:- The functionality of bytearray is exactly similar to bytes but an object of bytearray data
type is mutable and bytes object is immutable.
Examples:-- >>>ls=[10,20,30,40]
>>>ba=bytearray(ls)
>>>print(type(ba))--------<class,'bytearray'>
>>>for x in ba:
>>>print(x)----------- 10 20 30 40
>>>id(ba)-------------------xxxxxx248
>>>ba[0]=12 # updating an object 'ba'
>>>for x in ba:
>>>print(x)-------------- 12 20 30 40
>>>id(ba)-------------------xxxxxx248
Syntax-1:
1) range(start):
This syntax generates a range of values from 0 to start-1 values.
Example:- >>>r=range(6)
>>>print(type(r))-----<class,'range'>
>>>print(r)------------range(0,6)
>>> for x in r:
>>>print(x)------- 0 1 2 3 4 5 (default step value is 1)
Syntax-2:
2) range(start,stop):
This syntax generates a range of values from start to stop-1 values.
Example:- Generate the values 10 to 20
>>> for x in range(10,21):
print(x)---10 11 12 13 14..... 20
Note:- On the object of range,we can apply indexing and slicing operations.
1)List:
➔ List is one of the pre-defined class
➔ An object of list type allows us to store multiple values of the same type or different type
of both types.
➔ An object of list type allows us to organise both unique and duplicate values.
Functions in List:
1. append()
2. insert()
3. pop()
4. remove()
5. index()
6. copy()
7. reverse()
8. sort()
9. clear()
10. Extend()
1) Append() :-
➔ This function is used for adding an element to the object at the end of the list object.
Syntax: list obj.append(element)
2) Insert() :-
➔ This function is used for inserting an element in the list object by specifying valid existing
position.
Syntax: listobj.insert(valid pos, element)
3) b) pop()
➔ This function is used for removing the top most / latest element from the list object
without specifying valid existing position.
Syntax:- list obj.pop()
Examples:- >>> l1.append(10.3)
>>> print(l1)-------------[10, 'rs', True, 10.3]
>>> l1.insert(2,"Naveen")
>>> print(l1)-------------[10, 'rs', 'Naveen', True, 10.3]
>>> l1.insert(8,"KVR")
>>> print(l1)-------------[10, 'rs', 'Naveen', True, 10.3, 'KVR']
>>> l1.append(123)
>>> print(l1)-------------[10, 'rs', 'Naveen', True, 10.3, 'KVR', 123]
>>> l1.pop()-------------123
>>> print(l1)-------------[10, 'rs', 'Naveen', True, 10.3, 'KVR']
>>> l1.pop(3)------------True
>>> print(l1)-------------[10, 'rs', 'Naveen', 10.3, 'KVR']
4) Remove():-
➔ This function is used for removing the specific element from list (first occurrence only)
provided the element must present otherwise we get value error
Syntax:- listobj.remove(element)
Example:- >>>l1=[10,20,10,20,30]
>>>l1.remove(20)
>>>print(l1)----------------[10,10,20,30]
>>>l1.remove(100)-------Value error
5) Index() :-
➔ The function is used for finding an +ve index of a specified element of a list provided
element present in the list otherwise we get Value error.
Syntax:- list obj.index(element)
Example:- >>> l1=[10,20,10,20,30,40,-15]
>>> l1.index(20)--------------1
>>> l1.index(30)--------------4
>>> l1.index(200)------------ValueError: 200 is not in list
>>> l1.index(-15)-------------6
➔ Initial content of source and dest list objects are the same.
➔ Address of source and dest list objects are different
➔ Modification are reflected (Independent)
7) Reverse():-
➔ This function is used for obtaining reverse of given elements of list objects.
Syntax:- listobj.reverse()
Example:- >>> l1=[10,"HYD"]
>>> l1.reverse()
>>> print(l1)---------------['HYD', 10]
8) Sort():-
➔ This function is used for sorting the element of list objects in ascending order
provided elements must be homogeneous.
Syntax:- listobject.sort()
Example:- >>> l1=[10,2,-12,65,-65,-10,2]
>>> l1.sort()
>>> print(l1)---------[-65, -12, -10, 2, 2, 10, 65] #Ascending
>>> l1.reverse()
>>> print(l1)---------[65, 10, 2, 2, -10, -12, -65] #Descending
9) Clear() :-
➔ This function is used for removing / clearing all the elements of list objects (Object
remains same)
Syntax:- list obj.clear
Example:- >>>l1=[10,20,30]
>>>print(len(l1)-------3
>>>l1.clear()
>>>print(len(l1)-------0
>>>print(l1)------------[ ]
Special points:
del() - is one of the pre-defined functions present in the built-in module and it is by default
imported.
del() is used for deleting the values of any iterable object (list,str,...etc) and object also.
Syntax:- del(object name)
or
del(object name[index])
10) Extend() :-
➔ This function is used for adding the content of dest list object to the source list
object content.
Syntax:- sourcelistobj.extend(destlistobj)
Example:- >>> l1=[10,20,30]
>>> l2=["python","AI"]
>>> l1.extend(l2)
>>> print(l1)---------[10, 20, 30, 'python', 'AI']
>>> print(l2)---------['python', 'AI']
Special Points:
We can use operator + for extending the functionality of different source
list objects into deest list objects.
Example: Create a list with an inner list for representing student details as list elements, subjects
as inner list and marks another inner list.
>>> l1=[10,"RS",["c","cpp","python"],[20,30,4],"ANU"]
The Diagrammatic representation for list an inner list is given below
Tuple:-
➔ Tuple is one of the pre-defined class
➔ An object of tuple type allows us to store multiple values of the same type or different
type of both types.
➔ An object of tuple type allows us to organise both unique and duplicate values.
➔ The elements of the tuple must be enclosed within square brackets ( ) and the values must
be separated by comma ( , )
➔ An object f tuple maintains insertion order.
➔ On the object of the tuple, we can perform both indexing and slicing.
➔ An object of tuple is Immutable.
➔ To convert one type values into tuple type values, we use tuple().
➔ Empty tuple object can be created as follows
Example: >>>tp=() or >>>tp=tuple()
>>>print(tp)----------( )------Empty tuple
Note:- On a tuple object, we use index() and count() of list objects but not other functions
of list because tuple object belongs to immutable.
Functions in SET:-
1) add():
➔ This function is used for adding an element to set object
Syntax:- set obj.add(element)
Example:- >>>s={10,”Hyd”}
>>>s.add(“India”)
>>>print(s)----------------{10,’India’, ‘Hyd’}
2) clear():
➔ This function is used for cleaning / removing all elements from set objects
Syntax:- setobj.clear()
Example:- >>>s1={10,20,”Hyd”}
>>>len(s1)-----------3
>>>s1.clear()
>>>print(s1)---------set()--->empty
>>>len(s1)--------0
4) Remove():-
➔ This function is used for removing a value from a set object. If the value is unable
to be removed we get “KeyError”.
Syntax:- setobj.remove(value)
Example:- >>>s1={”apple”,”kiwi”,”banna”}
>>>s1.remove(“apple”)
>>>print(s1)-----{‘kiwi’,’banna’}
5) Pop():-
➔ it is used for removing any random element from set object
Syntax:- set obj.pop()
Example: >>>s1={'e', 'u', 'a', 'i'}
>>>s1.pop()-----------------------e
>>>print(s1)----------------------{'u', 'a', 'i'}
6) issubset()
➔ This function returns true provided one set is the subset of another set otherwise it
returns False
Syntax:- setobj1.issubset(setobj2)
7) issuperset()
➔ This function returns true provided one set is the superset of another set otherwise
it returns False
Syntax: setobj1.issuperset(setobj2)
Example:- >>>s1={10,20,30,40}
>>>s2={20,10}
>>>s1.issubset(s2)------False
>>>s2.issubset(s1)------True
>>>s1.issuperset(s2)-----True
>>>s2.issuperset(s1)-----False
K.V. RAO NARESH ITECHNOLOGIES
Naveen Kumar Velanati 24
P HO
Special cases:
>>>set().issubset(s1)------True
>>>s1.issubset(set())------False
>>>set().issubset(set())---True
8) isdisjoint():
➔ This function returns true provided both sets are having different elements. This
function returns False provided both sets are having at least one common element.
Syntax: setobj1.isdisjoint(setobj2)
Example: >>>s1={10,20,30,40}
>>>s2={“java”,”python”}
>>>s3={10,True}
>>>s4={“java”,12.34}
>>>s1.isdisjoint(s2)--------True
>>>s1.isdisjoint(s3)--------False
>>>s1.isdisjoint(s4)--------True
9) union():
➔ This function obtains all the elements from those sets which are used in Union
operation
Syntax:- setob3=set obj1.union(setobj2)
10) intersection():
➔ This function obtains common elements from any no of sets.
Syntax: setobj3=setobj1.intersection(setobj2)
11) Difference():
➔ This function is used obtaining only the elements of setobj1 by removing common
elements from setobj1 and setobj2 (i.e., Exclusive element of setobj1)
Syntax:- setobj3=set obj1.difference(setobj2)
Example:- >>>s1=setobj1.difference(setobj2)
>>>s1={10,20}
>>>s2={20,30}
>>>s3=s1.union(s2)
>>>s4=s1.intersection(s2)
>>>print(s4)------{20}
>>>s5=s1.difference(s2)
>>>print(s5)-------{10}
>>>s6=s2.difference(s1)
>>>print(s)-----------{30}
12) symmetric_difference():-
➔ This function is used for obtaining exclusive elements of both the sets by removing
common elements and placing those elements in the resultant set object.
Syntax:- resultant set obj=setobj1.symmetric_difference(setobj2)
Example:- >>>s1={10,20,30,40}
>>>s2={30,40,45,65}
>>>s3=s1.symmetric_difference(s2)
>>>print(s3)---------(10,20,45,65}
13) symmetric__difference_update():
➔ This function is used for obtaining exclusive elements of both the sets and update
source set objects by removing common elements and never place the element in
the resultant set object.
Syntax:- sourcesetob.symmetric_difference_update(s2)
Example:- >>>s1={10,20,30,40}
>>>s2={30,40,45,65}
>>>s3=s1.symmetric_difference_update(s2)
>>>print(s3)-------------None
>>>print(s1)------------{65,10,45,20}
14) update():-
➔ This function updates the elements of the source set with elements of the
destination set object.
Syntax:- sourceset obj.update(destsetobj)
Example:- >>>s1={10,20}
>>>s2={“Java”,”python”}
>>>s1.update(s2)
>>>print(s1)------------[20,10,’java’,’python’]
15) copy():-
➔ This function copies the elements source set object into destination set object
(perform shallow copy)
Syntax:- destsetobj=sourceobj.copy()
Example:- >>>s1={10,20}
b) Frozen Set:-
➔ ‘FrozenSet’ is pre-defined class
➔ An object of the frozenset allows us to store multiple values of the same type or different
type and both types.
➔ An object of a set organizes only Unique elements.
➔ An object of the frozenset never maintains insertion order.
➔ An object of frozenset is immutable
➔ On the object of the frozenset, we can’t apply indexing and slicing operations.
➔ To convert one type of elements into frozenset type, we use frozenset( )
➔ To create an empty frozenset we use frozenset( )
Example: >>>fs=frozenset()
>>>print(fs,type(fs))----------frozenset() <Class ‘frozenset’>
Note:- The functionality of frozenset is similar to set but an object of frozenset belongs to
immutable and object of set is both immutable (item assignment) and mutable (add()).
Functions in Dict:
1) Get():
➔ This function is used for obtaining value of value from dict object by passing value
of Key. if the key does not exist we get KeyError.
Syntax: var=dictobj.get(key)
Example: >>>d1={10:”OUCET”, 11:”JNTUH”}
>>>val=d1.get(10)
>>>print(val)--------OUCET
2) Values():
➔ This function is used for obtaining all the values of dict objects.
Syntax: var=dictob.values
Example: >>>keys=d1.keys()
>>>print(keys)------[10,11]
3) keys():
➔ This function is used for obtaining all the keys of dict objects.
Syntax: var=dictob.keys
Example: >>>keys=d1.keys()
>>>print(keys)------[10,11]
4) pop():-
➔ It is used for removing the (key,value) by passing value of key
syntax: dictobj.pop(key)
Example: d2.pop('qual')
5) clear():
➔ This function clears/ removes all elements from the dict object and it becomes
empty.
Syntax: dictobj.clear()
Example: d1.clear()
6) update():
➔ This function updates the one dict obj elements with another dict object elements.
Syntax: dictob1.update(dictobj2)
b) input(message):
➔ This function is used for reading any type of data dynamically from keyboard and
returns in the form str by prompting the message to end user on the console
➔ Syntax: varname=input(user prompting message)
➔ Ex: print(“Enter any value:”)
a=input() or
a=input(“Enter any value:”)
★ 1) Program Input
★ 2) Program:
Output:
Output:
4) Program
Output
5) Program Input
Output
1) Arithmetic operators:
➔ These operators are used for performing arithmetic operations i.e., (add, sum,
mul,..etc)
➔ If arithmetic operators are connected with literals / operands / variables then it is
called arithmetic expression.
➔ The following gives a list of arithmetic operators.
6) Program input
Write a python program using Arithmetic operators:
Output
2) Assignment operators:
➔ The symbol of assignment operator is “=”
➔ This operator is used for assigning RHS value / expression value to the LHS
variable
➔ In python programming two types of assignment operators.
1) Single line assignment
2) Multi line assignment
Syntax: LHS variable=RHS var/value/literal (or) LHS variable=RHS expression
Example:
>>>a=10
>>>b=a
>>>x=10
>>>y=20
>>>z=x+y
7) Program Input:
Write a python program which will accept any two values and interchange them without
using third variable
Output:
3) Relational operators:
➔ The purpose of these operator is that compare two values of variables
➔ If two operands are connected with relational operators then it is known as relation
expression.
➔ The following table list of relational operators.
8) Program Input:
Write a python program which demonstrate the concept of relational operators
Output
4) Relational Operators:-
➔ The purpose of Logical operators is to combine two or more relational expressions.
➔ Logical operators are used for forming compound conditions (multiple condition.
➔ If two or more relational expressions are connected with logical operators then it is
called Logical expression.
Syntax: (rel expr1) logical operator (rel expr2)
9) Program input:
Write a python program which will swap two integer values
Output
5) Bitwise OR operator(|):
➔ Syntax: res = var1 | var2
➔ Concept:This operator returns 1 provided if any one of bits of var1 or var2
is 1. Otherwise returns 0.
6) Membership operator:
➔ Purpose: The purpose of Membership operators is that “To check the extension of
value in an iterable object”. If the element / value present in iterable object then we
get “True” otherwise we get “False”
➔ We have 2 types of membership operators in python. They are
a) In
b) Not in
a) In:
➔ Syntax: value in table_object
➔ “In” operator returns True provided specified value present in
iterable_object otherwise it returns False.
b) Not in:
➔ Syntax: value not in iterable_object
➔ “Not in” operator returns True provided specified value not present in
iterable_object. Otherwise it returns False.
➔ Example: >>>s1={“AI”, “PYTHON”, “JAVA”}
>>>”python” not in s1------------> True
>>>s1[2] not in s1-----------------> False
>>>s1[2][1:3]in s1[2][:]----------> True
7) Identify operators:
➔ The purpose of Identify operators is that “To check the memory addresses of two
objects”.
➔ We have two types of identity operators. They are
K.V. RAO NARESH ITECHNOLOGIES
Naveen Kumar Velanati 45
P HO
1) Is
2) Is not
1) Is:
➔ Syntax: var1 is var 2
➔ This operator returns True provided both var1 and var2 points have the same
memory address. (id(var1) and id(var2) is different) otherwise it returns False.
2) Is not:
➔ Syntax: var1 is not var 2
➔ This operator returns True provided both var1 and var2 points have the different
memory address. (id(var1) and id(var2) is different) otherwise it returns False.
Example: >>>a=234
>>>b=234
>>>a is b -------->True (0-256)
>>>a is not b-------->False
>>>a=257
>>>b=257
>>>a is b--------> False(More than 256)
>>>a is not b------>True
>>>a=-5
>>>b=-5
>>>a is b--------> True(-1 to -5)
>>>a is not b------>False
i) Simple if statement:
Explanation:
➔ Here “test condition” evaluates first.
➔ If the test condition is true then Python Virtual Machine executes
statement-1, statement-2, …….statement-n, (known as block of statements)
and also executes other statements in the program.
➔ If the test condition is false then Python Virtual Machine executes other
statements in the program only without executing a block of statements.
Explanation:
➔ If the condition is true then execute Block of statement-1 and also execute other
statements in the program.
➔ If the condition is False then execute Block of statement-2 and also execute other
statements in the program
(or)
Output:
Explanation:
➔ Here test condition 1 is evaluated. If test condition 1 result is True then PVM will execute
Block of statements 1 and other statements in the program.
➔ If test condition 1 is False and PVM control goes to test condition 2 and if test condition 2
is True then execute Block of statements 2 and other statements in the program.
➔ If test condition 2 is False and PVM control goes to test condition 3 and if test condition 3
is True then execute Block of statements 3 and other statements in the program.
K.V. RAO NARESH ITECHNOLOGIES
Naveen Kumar Velanati 50
P HO
➔ This process will continue until all test conditions are evaluated.
➔ If all test conditions are False then execute else block of statements which are written
under else block and also execute other statements in the program.
Output:
Flow chart
Output:
Output:
Output:
Explanation:
➔ ‘For’ and ‘in’ are keywords.
➔ Varname is one valid variable name.
➔ Iterable_object represents any object containing more number of values such as
sequential type (str, bytes, bytearray, range), list type (list, tuple), set type (set,
frozenset), dict type (dict).
➔ The execution behaviour of for loop is that every value of iterable_object is placed
in varname one by one and executes block of statements.
(Statement-1, Statement-2,--------------,Statement-n).
➔ In general if an iterable_obect contains ‘n’ values then n-times block of statements
will execute by placing value by value in varname n-times.
➔ Example1:
➔ Example3:
➔ Example4:
Output:
Output:
Output2:
1) Break:
➔ The break statement is used for logical termination of repetition of loop and comes
out of loop and executes other statements in the python programs.
Syntax1: While(test condition):
……………
if(another test condition):
break
……………
…………….
….Other statements in python
Example1: Example2:
Output:
Example1:
Write a python program which will display the multiplication table for the selected +ve
numbers by rejecting -ve and 0 numbers.
Output:
Definitions of Functions:
➔ A part of the main program is called a function.
➔ (or) Sub program of the main program is called a function.
➔ The aim of functions is to provide re-usability and to perform some operations.
Parts of functions:
➔ At the time of dealing with functions, we must ensure 2 parts. They are,
1) Functional definition
2) Function call
➔ Function definition exists only once.
➔ Function calls can exist many times.
➔ For every function call, there must exist a function definition otherwise we get errors.
Explanation:
1) ‘def’ is a keyword used for defining a function.
2) ‘function name’ is one of the valid variable names treated as the name of the function.
3) ‘list of formal parameters’ represents variable names used in function heading and they are
used for storing the input which is coming from the function calls.
4) ‘doc string’ stands for documentation string and this represents description of the
functionality of code used in the function (nothing but comment) and it is optional.
5) Statement1, Statement2, Statement3,....Statement-n (called block of statements) represents
a set of executable statements which is providing a solution to the given problem.
6) In some circumstances, we use some special variables inside the function body and those
variables are local variables. The purpose of a local variable is to store temporary results.
7) The values of formal parameters and local variables can be used / accessed inside of
corresponding function definitions only but not possible to access in other function
definitions. (Known as scope of local and formal parameters)
Approach-2
Approach-4
Note: In python programming, return statement can return one or more no.of values.
(Program pending)
Write a python program which can find max and min elements from the given list of elements
Work
1) Write a python program which will accept a numerical +ve integer value and generate a
multiplication table by using functions.
2) Write a python program which will accept a list of elements and sort the elements of both
ascending and descending order using functions.
3) Write a python program which will accept numerical +ve integer values and find the
square root of a given value using functions.
Arguments:
➔ Arguments are the variables used in function calls, which also acts as global variables.
Local variables:
➔ Local variables are those, which are used inside of the function body for storing temporary
results and whose values can be accessed within the corresponding function definition but
not accessed outside of the function.
Here the mechanism of passing the data is that the values of arg1, arg2,...arg-n are placed
in param1, param2,...param-n by position, order and meaning.
Here the formal param name(s) must used as keywords in the function call and
hence this
Syntax:(function definition)
Def functionname(param1, param2,.... param_n-1=val1, param_n-2=val2):
----------------------------
----------------------------
Output:
Program:
Write a python program which demonstrates the concept of variable length
parameters. (or) Write a python program which will accept and display variable no.of
values.
Output
Output:
Input:
Write a python program which will display keyword variable no of values
Output:
Input:
Write a python program which will find total marks of various students who are securing different
subjects, who are studying in different classes.
Output:
Input
Write a python program which makes understand scope of global variables
Global Variable:
Global variables are those, which are defined before all the functions definitions. The
purpose of global variables is to place common values, which are accessed by all the function
definitions.
Input
Write a python program which makes understand scope of local variables
Globals():
➔ Whenever the global variable names and local variables are same then to do the operations
both global and local variables directly, Python virtual machine gets ambiguity (there is no
clarity between multiple duplicate var names).
➔ To differentiate between global variable names and local variables in corresponding
functions, the global variables must be retrieved / extracted by using globals().
➔ globals() returns all global variables in the form dict.
Syntax:
globalvar1=var1
--------------------
globalvar-n=val-n
Def functionname():
---------------
--------------
K.V. RAO NARESH ITECHNOLOGIES
Naveen Kumar Velanati 85
P HO
varname1=globals()[‘globalvar1’]
varname2=globals()[‘globalvar2’]
-----------------------------------------
varname-n=globals()[‘globalvar-n’]
Input:
Write a py program which perform the operations on local and global variables (add the values of
global and local variables)
Ex-i)
Ex-ii)
➔ Syntax:
varname=lambda args-list:expression
➔ Explanation:
◆ Varname is the valid name of python, which is treated as Anonymous function
name.
◆ Lambda is a keyword / operator used for defining Anonymous functions.
◆ args-list represents formal params
◆ Expression represents a single executable statement
Input:
Define a Lambda function or Anonymous functions for finding sum, sub and mul operations on
two numbers
Input:
Define a lambda function for finding biggest among two numbers
Input:
Write a python program which will filter +ve elements and -ve elements separately (With
Anonymous (or) Lambda functions).
2) Map():
➔ The purpose of map() is to generate / create a new iterable object from an existing iterable
object by applying existing elements of the iterable object to the particular function.
➔ Syntax for map():
varname=map(function name ,iterable obj)
➔ Explanation:
1) Varname is an object of <class, ‘map’>
2) map() is a pre_defined function. The execution behaviour of map() is that it applies
each element of an iterable object to a specified function and generates a new
iterable object based on the logic we write in the function (normal function,
anonymous function).
3) Function name can be either normal function or anonymous function.
4) Iterable objects can be either sequence, list, set, dict type.
Input:
Write a python program Which will accept a list of integer values and square all the values of the
list with normal function
Input:
Write a python program Which will add the contents of two lists with map(). (The list may
contain different sizes of elements).
3) Reduce():
➔ The purpose of reduce() is to obtain a single element / result from the iterable object by
applying it to the function.
➔ The reduce() present in a predefined module called “function tools”
➔ Syntax:
varname=reduce(function name,iterable obj)
➔ Explanation:
1) Varname can be either fundamental data types and strings.
2) Function names can either be normal function or lambda function.
3) Iterable objects can be either sequence, list, set, dict type.
Input:
Write a python program which will find highest and lowest elements from the given list of
elements.Accet the list of elements dynamically.
Write a python program which will find the product of n natural numbers using reduce function.
Where n must be the +ve integer value.
1) Write a python program which will calculate the sum of first n natural numbers using
reduce().
2) Write a python program which will find the sum of squares of first n natural numbers
using reduce().
3) Write a python program which will find the sum of cubes of n natural numbers using
reduce()..
4) Write a python program which will accept different lists of words and convert into a single
sentence using reduce().
Definition of Module:
➔ A module is a collection of variables(Data), Functions and classes
Types of Modules
➔ We have 2 types of modules. They are
a) Pre-defined / build-in modules
b) Programmer / user / custom defined modules.
Re-using the variables, functions and classes of the modules in other programs:
➔ We have two approaches to re-use the variables, functions and class of modules in other
programs. They are
1) By using import statement
2) By using from …… import statement
a)
b)
c)
Syntax 3:- from module name import variable name1 as alias name1..variable
nam-n as alias name-n, function name 1 as alias name-1….function name-n as
alias name-n
Example Program:
Write a python program for calculating all arithmetic operations with modules in the form of
menu driven approach.
1.
2.
3.
Syntax:
Import importlib
-----------------
-----------------
importlib.reload(modulename)
-----------------
-----------------
1.
2.
Packages in python:
=> except block will execute provided an exception occurs in try block
=>Even though we write multiple except blocks, PVM can execute
appropriate except block depends on on type of exception occurs in try
block.
=>Industry is highly recommended to write multiple except blocks for
generating multiple User-friendly errors messages.
=>except block to be written after try block and before else block (if we
write else block)
=====================================================================
3) else block:
---------------------
=> It is the block , In which we are recommended to write block of
statements for generating results and hence this block
is called Result block
=> else block will execute provided there is no exception occurs in try
block.
=> Writing else block is optional
=>The place of writting else block is after except block and before
finally block( if we write finally block)
============================================================
4) finally block:
------------------------
====================================================
Exception Handling
====================================================
=>The aim of Exception Handling is that to develop Robust (Strong)
Applications.
=> In Real Time , To develop any real time project, we need to choose a
lang / tech.
=>With the language, we can develop programs, comiple and execute those
Programs, During this process, we get 3 types of errors. They are
a) Compile Time Errors
b) Logical Errors
c) Runtime Errors
=======================================================
a) Compile Time Errors:
------------------------------------
=>These errors occurs during Compilation(.py------>.pyc) time
=>These errors occurs due to syntaxes are not followed.
=>These errors solved by Programmers at Development Level
b) Logical Errors:
---------------------------
=>These errors occurs during execution time
=>These errors occurs due to wrong represenation / mis-interpretation of
logic and we get wrong Results
=>These errors solved by Programmers at Development Level
c) Runtime Errors
----------------------------
=>These errors occurs during execution time
=>These errors occurs due to wrong Input entered by Application User / end
user
=>Runtime errors solved by Programmers at Implementation Level.
=============================================================
Points to be Remembered
-----------------------------------------
=>When The application user enters invalid / wrong input then we get
Runtime Errors
(Invalid Input------------->Runtime Errors)
=>All Runtime errors are called Exceptions
(Invalid Input----->Runtime Errors---->Exceptions )
Hence all invalid inputs gives exceptions.
=>All exceptions gives by default "technical Error Messages "
=>Exception Handling:
---------------------------------
The Process of Converting Technical Error Messages into User-Friendly
Error Messsages is called Exception handling
=> When the exception occurs in the python program, Internally 3 stpes
takes place
a) PVM terminates the program execution abnormally
b) PVM comes out of Program flow
c) By default, PVM generates Technical Error Messages
=>To do (a),(b) and (c) steps, " PVM creates an object of one exception
class "
"Technically, all exceptions of python are treated as objects"
=>When the exception occurs in python program then PVM creates an object
of appropriate exception class and by default generates technical error
messages.
--------------------------------------------------------------------------
-------------------------------------------------
==================================
Types of exceptions in Python
==================================
=>In python Programming, we have two types of exceptions. They are
#ex2.py
a="$"
print("Val of a(str)=",a)
b=int(a) # invalid input---exception-->object-->ValueError
print("Val of b(int)=",b)
===================================================
Handling The Exceptions
====================================================
=>Handling The Exceptions are nothing but converting Technical error
Messages into User-friendly error messages.
=>To Convert Technical error Messages into User-friendly error messages,
In python programming, we have 5 key words. They are
1) try
2) except
3) else
4) finally
5) raise
-------------------------------------------------------
syntax for handling the exceptions:
-------------------------------------------------------
try:
block of statements causes
exceptions in the program
except <exception class name-1>:
block of statements provides
User-Friendly Error Messages
except <exception class name-2>:
block of statements provides
User-Friendly Error Messages
--------------------------------------------------
--------------------------------------------------
except <exception class name-n>:
block of statements provides
User-Friendly Error Messages
else:
block of statements--recommended
provide display results
finally:
block of statements which will
execute compulsorily
==================================================
1) try:
---------------
=> It is the block , In which we write block of statements causes
problems at runtime
In otherwords, what are all the statements generating exceptions then
those statements must be written within try block. Hence try block is
called "exception Monitoring block"
=> When the exception occurs in try block then PVM comes out of try block
and executes appropriate except block(if found otherwise PVM goes
out of program flow)
=> After executing appropriate except block PVM never comes to try block
to execute rest of the statements in try block.
=>Each and Every Try block must have alteast one except block(otherwise we
can't give User friendly Error Messages)
=>Each and Every Try block must be immediately followed by except block.
==========================================================
2) except block:
-----------------------
=> It is the block , In which we write block of statements provides
user-friendly error messages. In otherwords except block
supresses the technical error messages and generates
user-friendly error messages. Hence this block is called "exception
Processingh block".
=> except block will execute provided an exception occurs in try block
=>Even though we write multiple except blocks, PVM can execute
appropriate except block depends on on type of exception occurs in try
block.
=>Industry is highly recommended to write multiple except blocks for
generating multiple User-friendly errors messages.
=>except block to be written after try block and before else block (if we
write else block)
=====================================================================
3) else block:
---------------------
=> It is the block , In which we are recommended to write block of
statements for generating results and hence this block
is called Result block
=> else block will execute provided there is no exception occurs in try
block.
=> Writing else block is optional
=>The place of writting else block is after except block and before
finally block( if we write finally block)
============================================================
4) finally block:
------------------------
=> It is the block , In which we are recommended to write block of
statements which will relinquish (close / release / terminate / clean-up)
the resources (file / databases) which are obtained in try block.
=>Writting the finally block is optional
=>finally block will execute compulsorily ( if we write )
=>finally block to be written after else block (if we write else block)
====================================================================
====================================================
Various forms of except block
====================================================
=> We know that except block is used for supresssing the technical error
messages and generating User frinedly error messages.
=>We can have various except blocks. They are
Flavour1:- This approach displays the messages caused due that exception
occurence
--------------
syntax:
--------------
try:
-----------
-----------
-----------
except exception class name as varname:
print(varname)
Example:
--------------
try:
a=10
b=0
c=a/b
except ZeroDivisionError as kvr: # here kvr is a var name holds
the msg
print(kvr) # division by zero # which is generated due to
ZeroDivisionError
--------------------------------------------------------------------------
------------------------------------------
Flavour2:- This approach makes us understand single except handles
multiple specific exceptions and displays multiple specific
Messages at a time
--------------
Syntax2:
--------------
try:
-----------
-----------
-----------
except ( exception class name1, exception class name2...exception
class name-n)
bock of stataments provides
User-friendly error Messages.
Example:
#program cal division of two numbers by accepting the values dynamically
from KBD
#div3.py
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1)
b=int(s2)
c=a/b
except ( ValueError, ZeroDivisionError) :
print("\nDon't enter Strs / Alpha-numeric / Special Symbols as
Values :")
print("\nDon't enter zero for Den....")
else:
print("===========================")
print("\tResult")
print("===========================")
print("Val of a={}".format(a))
print("Val of b={}".format(b))
print("Div={}".format(c))
print("===========================")
finally:
print("i am from finally block:")
====================================================================
Flavour3:- This approach makes us understand single except we can
display generic messages by handling all types of
exceptions.
syntax:
------------
try:
-----------
-----------
-----------
except :
bock of stataments provides
generic Messages.
Example:
--------------
try:
a=10
b=0
c=a/b
except :
print("exception occured:")
======================================================================
====================================
raise keyword
====================================
=>raise kwd is used for hitting / raising / generating the exception which
is occured as part of python program when certain condtion is satisfied.
=>Syntax1:-
raise exception class name
syntax2:
def functionname(list of formal params if any):
------------------------------
------------------------------
if ( test cond ):
raise exception class name
------------------------------
-------------------------------
Program
#divdemo.py
from mathop import division
from hyd import KvrZeroError
try:
division() # handling the exception
except KvrZeroError :
print("DON'T ENTER ZERO FOR DEN...")
Step1:
class DepositError(BaseException):pass
class WithDrawError(Exception):pass
class InSuffFundError(Exception):pass
Step2:
#atmmenu.py----->treated as module name
def atmmenu():
print("----------------------------------")
print("\tATM Operations:")
print("----------------------------------")
print("\t1. DEPOSIT:")
print("\t2. WITHDRAW")
print("\t3. BALANCE ENQ..")
print("\t4. EXIT")
print("----------------------------------")
Step3:
#bank.py---treated as module
from bankexcept import DepositError
from bankexcept import WithDrawError
from bankexcept import InSuffFundError
acbal=500.00
def deposit():
damt=float(input("Enter the amount to deposit:")) #ValueError
if(damt<=0):
raise DepositError
else:
global acbal
acbal=acbal+damt
print("U Have Deposited Rs:{}".format(damt))
print("Available Bal after deposit: {}".format(acbal))
def withdraw():
wamt=float(input("Enter the amount to withdraw:")) # ValueError
if(wamt<=0):
raise WithDrawError
else:
global acbal
if(wamt>acbal):
raise InSuffFundError
else:
acbal=acbal-wamt
print("Take the cash and enjoy!")
print("Available Bal after with draw: {}".format(acbal))
def balenq():
print("UR AVAILABLE BALANCE: {}".format(acbal))
Step4:
#atmdemo.py
from atmmenu import atmmenu
from bankexcept import DepositError
from bankexcept import WithDrawError
from bankexcept import InSuffFundError
from bank import deposit
from bank import withdraw
from bank import balenq
import sys
while(True):
try:
atmmenu()
ch=int(input("Enter ur Choice:"))
if (ch==1):
try:
deposit()
except ValueError:
print("Don't try to deposit sts/alpha-numeric value
/ special symbols:")
except DepositError:
print("Don't try to deposit -ve and zero amount:")
elif(ch==2):
try:
withdraw()
except ValueError:
print("Don't try to withdraw sts/alpha-numeric
value / special symbols:")
except WithDrawError:
print("Don't try to withdraw -ve and zero
amount:")
except InSuffFundError:
print("U don't have sufficient Funds--read
python!")
elif(ch==3):
balenq()
elif(ch==4):
print("Thanks for this App!")
sys.exit()
else:
print("Ur Choice of Operation is wrong--Select Properly")
except ValueError:
print("Don't enter strs/ alpha-numeric / special symbols as
choice:")
===========================================
FILES IN PYTHON
===========================================
INDEX:
---------------------------------------------------------------------------------
=>Purpose of Files:
=> Def of File
=>Def of Record:
=>Types of Application in Files
a) Non-Pesrsistant Applications
b)Persistant Applications
=>Types of Operations on Files:
a) Write Operation
b) Read Operation
=>Types of Files in Python:
a) Text Files
b) Binary Files
=>Files Opening Modes:
a) r
b) w
c) a
d) r+
e) w+
f) a+
g) x
=>Functions used for Writting the data to the file:
a) write()
b) writelines()
=>Functions used for Reading the data from file:
a) read()
b) read(no. of chars)
c) readline()
d) readlines()
=> Random File Accesssing
a) seek()
b) tell()
=> Advanced Concepts in Files
a) Pickling
b) Un-pickling
==============================x=============================
==================================================
Introduction to Files of Python
==================================================
=>The purpose of files is that to store the data permanently.
=>Programatically , To store the data permanently we need file
name. Technically file name is one of the named location in
Secondary Memory (Hard Disk). Hence File name(s) always
resides in secondary memory(HDD)
=======================================================
=>In the context of files , we can develop two types of
applications. They are
a) Non-Persistent Applications
b) Persistant Applications
a) Non-Persistent Applications:
---------------------------------------------
=>In this application development, we can read data from key
board, store that data main memory and results are displayed
on Monitor.
Example: ALL OUR PREVIOUS PROGRAM COMES UNDER NON-PERSISTANT
APPLICATIONS
=>The Result stored in Main Memory (RAM) is temporary.
--------------------------------------------------------------
--------------------------------
b) Persistant Applications:
-----------------------------------------
=>In this application development, we can read data from files
/ database into main memory and results are displayed on
Monitor and they stored once again in files / data base.
Def of Record:
----------------------
=>Collection of Fields Values is called Record.
a) Write Operation:
----------------------------
=>Write Operation is used for Transfering Temporary Data from
main memory into file of Secondary Memory
=>To Perform Write Operation, we use 3 steps:
a) Choose the file name
b) Open the file name in Write Mode
c) Perform cycle of write operations
=================================
Opening the file
=====================================
=>In Python to open the file in specified mode, we have 2 syntaxex.
They are
1. by using open()
2. by using with....open()....as
-------------------------------------------------------------------
------------------------
1. by using open()
--------------------------------
Syntax:
------------
varname=open("file name", "file mode")
-------------------
Explanation:
-------------------
=>var name represents a valid var name and it is treated as file
pointer and it can be read pointer or write pointer.
=>open() is a pre-defined function , which is used for opening the
file in spefied file opening mode.
=>file mode can be r,a,w,r+,w+,a+ and x
=>With this syntax once we open the file, It highly recommended to
close the file in finally block for achieving the consistency.
===================================================================
=
2) by using with....open()....as
-------------------------------------------------
Syntax:
-------------
with open("File Name", "file mode") as <varname>:
---------------------------------------------
---------------------------------------------
---------------------------------------------
-------------------
Explanation:
-------------------
=>here 'with' and ' as ' are key words
=>var name represents a valid var name and it is treated as file
pointer and it can be read pointer or write pointer.
=>open() is a pre-defined function , which is used for opening the
file in spefied file opening mode.
=>file mode can be r,a,w,r+,w+,a+ and x
=>With this syntax once we open the file, It is automatically
closing the file provided the PVM control comes out of with ...
opne()...as syntax
================================================================
1) r :
-----------
=>'r' is used for opening the specified file in Read Mode provided
the specified file must exists in secondary memory otherwise we get
exception called FileNotFoundError
=>If we don't specify the file opening mode then by default file
opening mode is 'r'
------------
2) w :
-----------
=>'w' is used for opening the specified file in write mode newly
always. If we open existing file in 'w' mode then existing file
also opened in write mode newly by removing existing records.
-----------
3) a :
-----------
=>'a' mode is used opening the spefcied file in write mode, if file
does not exists add the records. If the file already exists then it
opened in write mode and new records will be appended.
-----------
4) r +
---------
=>'r+' mode is used for opens a file for performing reading and
writting.
------------
5) w +
------------
=>'w+' mode is used for opening the file in write mode always newly
and performs read and write operations. If the existing file is
opened in 'w+' mode then that file opened in write mode newly by
removing existing records
-------------------------------------------------------------------
----------
6) a +
-------------------------------------------------------------------
-----------------------------------------
=>=>'a+' mode is used for opening the file in write mode provided
if it is new file and performs read and write and append
operations. If the existing file is opened in 'a+' mode then that
file opened in write mode and we can write , read and append
operations.
-------------------------------------------------------------------
--------------------------------------------------------
7) x :
-----------
=>'x' mode is used for opening the file in write mode exclusively.
===================================================================
====
=====================================
Types of Files in Python
=====================================
=>In Python, we have two types of files. They are
1. Text Files
2. Binary Files
-------------------------------------------------------------------
--------------
1) Text File:
-------------------
=>Text files contains the data in the form Alphabets, digits and
special symbols
Example:-
sum.py, sum.java,
sum.c sum.cpp
resume.rtf...................etc
=>In python Text files are denoted by a letter 't'
2)Binary Files:
----------------------
=>Binary Files contains the data in the form bytes or bits (binary
format)
Examples:- .exe files
.jpeg, .jpg, .png, .gif -->Images
audio video files...etc
==========================================
Reading the data from files
==========================================
=>To read data from files, First we must open the file in read
mode.
=>To read the data from the file, we have 4 functions. They are
a) read()
b) read(no. of chars)
c) readline()
d) readlines()
a) read():
------------
=>This function is used for reading entire data from the file in
the form of str
syntax:
------------
data=filepointer.read()
-------------------------------------------------------------------
----
b) read(no.of chars):
-------------------------------
=>This function is used for reading specified no. of chars from the
file in the form of str.
syntax:
------------
data=filepointer.read(no. of chars)
-------------------------------------------------------------------
----
c) readline()
---------------------
=>This function is used for reading one line at a time from the
file in the form of str.
syntax:
------------
data=filepointer.readline()
-------------------------------------------------------------------
----
d) readlines():
-----------------------
=>This function is used for reading entire lines of data from the
file in the form of list type
syntax:
------------
data=filepointer.readlines()
-------------------------------------------------------------------
----
=============================================
Writting the data to the file
=============================================
=>To write the data to the file, the file must be opened in write
mode (w,a,w+,a+, x)
=>To write the data to the file, we have two pre-defined functions.
They are
1) write(str)
2) writelines(str)
1) write(str):
--------------------
=>This function is used for writting any type of data to the file
in the form of str
syntax:- filepointer.writelines(iterabel-object)
Example:-
lst=[10,"KVR",94.25,"HYD"]
tpl=(20,"RS",99.99,"NL")
wp.writelines(lst)
wp.writelines(tpl)
============================================
Pickling and Un-pickling
============================================
Pickling:
-------------
=>Let us assume there exists an iterable object with collection of
values. If we want to store / save them in file of secondary memory
with normal file programming then we need perform multiple write
operations. This process is one of the time consuming Processes.
=>To overcome this problem, we use the concept of Pickling.
=>The advantage of Pickling concept is that with Single Write
Operation, we save / store entire iterable object content in the
file of secondary memory.
=>Def. of Pickling:
---------------------------
=>The process of storing / saving entire iterable object content
into the file of secondary memory by performing single write
Operation is called Pickling.
=>Pickling Concept participates in Write operation.
=>Pickling and un-pickling concepts always deals with any file mode
with binary file
===================================================================
======
2) Un-pickling:
-----------------------
=>Let us assume, there exists a record in file of secondary memory.
To read record values, with normal file programming, we need to
perform multiple read operations. which is one of the time
consuming process.
=>To overcome this problem, we must use the concept of un-pickling.
=>The advantage of Un-pickling concept is that with single read
operation, we read entire record from the file of secondary memory.
=>Def. of Un-Pickling:-
--------------------------------
=>The process of reading the entire record from the file of
secondary memory into object of main memory by performing single
read operation is called Un-pickling.
Note:
---------
=>Pickling and un-pickling improves the performance of ordinary
file programming of python.
=================================================================
PROGRAMS:
#FileEx1.py
try:
rp=open("stud.data")
print("type of rp=", type(rp)) # TextIOWrapper
except FileNotFoundError:
print("Files does not exists:")
else:
print("File opened in read mode successfully:")
print("-------------------------------------------------------
------")
print("File opening Mode=",rp.mode) # r
print("is readable ?=",rp.readable()) # True
print("is writable ?=",rp.writable()) # False
print("is files closed?=", rp.closed) # false
print("-------------------------------------------------------
------")
finally:
if rp!=None:
#fileex2.py
wp=open("stud.data","w")
print("File Opened in write mode successfully:")
print("Type of wp=",type(wp)) # TextIOWrapper
print("------------------------------------------------------------
-")
print("File opening Mode=",wp.mode) # w
print("is readable ?=",wp.readable()) #False
print("is writable ?=",wp.writable()) # True
print("------------------------------------------------------------
-")
#fileex3.py
wp=open("emp.data","r+")
print("File Opened in write mode successfully:")
print("Type of wp=",type(wp)) # TextIOWrapper
print("------------------------------------------------------------
-")
print("File opening Mode=",wp.mode) # a+
print("is readable ?=",wp.readable()) # True
print("is writable ?=",wp.writable()) # True
print("------------------------------------------------------------
-")
#fileex4.py
try:
wp=open("atten1.data","x")
print("File Opened in write mode successfully:")
print("Type of wp=",type(wp)) # TextIOWrapper
print("-------------------------------------------------------
------")
print("File opening Mode=",wp.mode) # x
print("is readable ?=",wp.readable()) # False
print("is writable ?=",wp.writable()) # True
print("-------------------------------------------------------
------")
except FileExistsError:
print("File already opened in write mode, we can't open
again")
#FileEx5.py
try:
with open("stud.data","r") as rp:
print("File opened in read mode successfully:")
print("--------------------------------------------------
-----------")
print("File opening Mode=",rp.mode) # r
print("is readable ?=",rp.readable()) # True
print("is writable ?=",rp.writable()) # False
print("line-9-->is files closed?=", rp.closed) # false
print("--------------------------------------------------
-----------")
print("i am out of with open()...line-11 is files closed?=",
rp.closed) # True
except FileNotFoundError:
print("File does not exists:")
else:
print("i am out of with open()...line-15 is files closed?=",
rp.closed) # True
finally:
print("i am out of with open()...line-17 is files closed?=",
rp.closed) # True
#FileReadEx1.py
rp=open("hyd.data","r")
fdata=rp.read()
print(fdata)
print("\n\ntype of fdata=",type(fdata))
#FileReadEx2.py
rp=open("hyd.data","r")
fdata=rp.read(3)
print(fdata)
print("------------------------------")
print("Pos of rp=", rp.tell())
fdata=rp.read(6)
print(fdata)
print("Pos of rp=", rp.tell())
rp.seek(0)
print("after seek, Pos of rp=", rp.tell())
#FileReadEx3.py
rp=open("hyd.data","r")
fdata=rp.readline()
print(fdata)
fdata=rp.readline()
print(fdata)
print("type of fdata=",type(fdata))
#FileReadEx4.py
rp=open("hyd.data","r")
fdata=rp.readlines()
for line in fdata:
print(line, end=" ")
#FileWriteEx2.py
wp=open("emp.data","a")
lst=[30,"Krishna",44.25,"Bang"]
tpl=(40,"Sampath","AP")
wp.writelines(str(lst)+"\n")
wp.writelines(str(tpl)+"\n")
s="Python\n is an\n oop lang"
wp.writelines(s)
print("Data written to the file--verify")
#FileWriteEx3.py
with open("hyd.data","a") as wp:
print("Enter Multiple Lines of Text (To stop press stop)")
while(True):
std=input()
if (std!="stop"):
wp.write(std+"\n")
else:
print("\n data written to the file sucessfully--
verify")
break
#pick.py
import pickle
with open ("emp.data","ab") as wp:
noe=int(input("Enter How Many Emplyees data u have:"))
for i in range(1, noe+1):
print("--------------------------------------------------
----")
print("Enter {} Employee Data:".format(i))
print("--------------------------------------------------
----")
eno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
lst=list()
lst.append(eno)
lst.append(ename)
lst.append(esal)
pickle.dump(lst,wp)
print("--------------------------------------------------
----")
print("{} Emp Data Record Saved in a file
successfully:".format(i))
print("--------------------------------------------------
----")
#unpick.py
import pickle
try:
with open("emp.data","rb") as rp:
print("---------------------------------------------")
print("\tEmplyee Records")
print("---------------------------------------------")
while(True):
try:
emprec=pickle.load(rp)
for val in emprec:
print("{} ".format(val), end=" ")
print()
except EOFError:
print("---------------------------------------
-")
break
except FileNotFoundError:
print("File does not exists")
#FileCopy.py
sfile=input("Enter The source File:")
try:
with open(sfile) as rp:
dfile=input("Enter Destination File:")
with open(dfile,"a") as wp:
sfdata=rp.read()
wp.write(sfdata)
print("{} data copied into {}--plz verify
".format(sfile,dfile))
except FileNotFoundError:
print("Source File does not exists")
=>mkdir() can create one folder at a time but not root folder, sub
folder, sub-sub folder etc
=>If the folder was already created then it can't create again and
we get pre-feind exception
FileExistsError
=>If the The Hierarchy of Folders does not exists then we OSError
as exception
---------------
Example:
---------------
import os
try:
os.mkdir("g:\Mango\apple\kiwi")
print("Folder Created--Verify")
except FileExistsError:
print("Folder was already created-it can't create again")
except OSError:
print("The Hierarchy of Folders unable create:")
=============================================================
Creating Root Folder, sub Folder, sub-sub Folders ecta at time
========================================================
=>To Creating Root Folder, sub Folder, sub-sub Folders etc at
time, we use a pre-defined function called makedirs()
-----------------
Example:
-----------------
import os
try:
os.makedirs("G:\mango/apple/grapes")
print("Folder Hierarchy Created..")
except FileExistsError:
print("Folder Hirrachy was already created:")
===================================================================
=
Remove a folder / Directory:
========================================================
=>To Remove a folder / Directory, we use rmdir()
=>Syntax:- os.rmdir("folder name")
PROGRAMS
#createfoldex1.py
import os
try:
os.mkdir("g:\Mango\apple\kiwi")
print("Folder Created--Verify")
except FileExistsError:
print("Folder was already created-it can't create again")
except OSError:
print("The Hierarchy of Folders unable create:")
#cwdex1.py
import os
cwdinfo=os.getcwd()
print(cwdinfo)
#listdirex1.py
import os
lst=os.listdir(".")
for x in lst:
print(x)
#listfiles.py
import os
kvr=os.walk(".")
for k,v,r in kvr:
print("Folder path={}".format(k))
print("sub folder path={}".format(v))
print("Files={}".format(r))
#renamefoldex1.py
import os
try:
os.rename("Hyderabad","HYD")
print("Folder Renamed---Verify")
except FileNotFoundError:
print("Old Folder Does not exists")
#rmdiresx.py
import os
try:
os.removedirs("G:\mango/apple/kiwi")
print("Folder(s) removed--verify")
except FileNotFoundError:
print("specifed folder hierarchy does not exists")
except OSError:
print("Specified Folder is not empty:")
#rmdirex.py
import os
try:
os.rmdir("G:\KV234")
print("Folder Removed-verify")
except FileNotFoundError:
print("Folder Name does not Exists")
except OSError:
print("Specified Folder Contains files-can't be removed")
=========================================
Introduction to Regular Expressions in Python
=========================================
=>Regular Expressions one of the Programming languages Independent
Concept and This concept can be used any programming lang.
----------------------------------------------
=>Def of Regular Expressions:
----------------------------------------------
=>A Regular Expressions is one of the string data, which is
searching / matching / finding in the Given Data and obtains
Desired Result.
===================================================================
===
=>To deal with Regular Expressions Programming, we use a pre-
defined module called "re"
=>The "re" module contains some pre-defined functions, which are
used develop regular exprssions applications.
===================================================================
Example:
----------------
Q) Search for thr word "Python"
Result
---------------
0 6-------------Python
20 26-----------Python
No. of occurence = 2
-----------------------------------------------------------------
----------
Example: Given Data: " aniket is studen of python whose mail id
is aniket@ibm.com and
ramesh is student of java whose mail id is ramesh@tcs.com, ram is
student data scienece whose mail id is ram@wipro.com. "
PROGRAM
#regexprex1.py
import re
strdata="Python"
givendata="Python is an OOP Lang. Python is an POP lang also"
matinfo=re.finditer(strdata,givendata)
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start Index: {}\t End Index: {}\t Value:
{}".format(mat.start(),mat.end(),mat.group()))
else:
print("-------------------------------------------------------
----------")
#regexprex2.py
#program for seraching the word "python"
# in the line "Python is an OOP Lang. Python is an POP lang also"
import re
noc=0
matinfo=re.finditer("a","Python is an OOP Lang. Python is an POP
lang also")
print("------------------------------------------------------------
------")
for mat in matinfo:
noc+=1
print("start Index: {}\t End Index: {}\t Value:
{}".format(mat.start(),mat.end(),mat.group()))
else:
print("-------------------------------------------------------
-----------")
print("No. of Occurences={}".format(noc))
print("-------------------------------------------------------
-----------")
#regexprex3.py
import re
matinfo=re.finditer("[kvr]","Ak#4v@R5$Vw%rP")
print("------------------------------------------------------------
------")
for mat in matinfo:
print("start Index: {}\t End Index: {}\t Value:
{}".format(mat.start(),mat.end(),mat.group()))
else:
print("-------------------------------------------------------
-----------")
#regexprex4.py
import re
matinfo=re.finditer("[^kvr]","Ak#4v@R5$Vw%rP")
print("------------------------------------------------------------
------")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
-----------")
#regexprex5.py
#search for all small alphabets only
import re
matinfo=re.finditer("[a-z]","Ak#4v@aR5g$Vw%rP")
print("------------------------------------------------------------
------")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
----------")
#regexprex6.py
#search for all except small alphabets only
import re
matinfo=re.finditer("[^a-z]","Ak#4v@aR5g$Vw%rP")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
---------")
#regexprex7.py
#search for all Capital alphabets only
import re
matinfo=re.finditer("[A-Z]","Ak#4v@aR5g$Vw%rP")
print("------------------------------------------------------------
----")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
---------")
#regexprex8.py
#search for all except Capital alphabets only
import re
matinfo=re.finditer("[^A-Z]","Ak#4v@aR5g$Vw%rP")
print("------------------------------------------------------------
------")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
-----------")
#regexprex9.py
#search for all digits only
import re
matinfo=re.finditer("[0-9]","Ak#4v@aR5g$Vw%8rP")
print("------------------------------------------------------------
----")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
---------")
#regexprex10.py
#search for all except digits only
import re
matinfo=re.finditer("[^0-9]","Ak#4v@aR5g$Vw%8rP")
print("------------------------------------------------------------
------")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
---------")
#regexprex11.py
#search for all Alphabets--small and capital
import re
matinfo=re.finditer("[A-Za-z]","Ak#4v@aR5g$Vw%8rP")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
----------")
#regexprex12.py
#search for all except Alphabets--small and capital
import re
matinfo=re.finditer("[^A-Za-z]","Ak#4v@aR5g$Vw%8rP")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
---------")
#regexprex13.py
#search for all except Alphabets--small and capital
import re
matinfo=re.finditer("[A-Za-z0-9]","Ak#4v@aR5g$Vw%8rP")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
---------")
#regexprex14.py
#search for all except Alphabets--small and capital
import re
matinfo=re.finditer("[^A-Za-z0-9]","Ak#4v@aR5g$Vw%8rP")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start Index: {}\t Value:
{}".format(mat.start(),mat.group()))
else:
print("-------------------------------------------------------
---------")
#regexprex15.py
#program searching space character
import re
matinfo=re.finditer("\s", " A#6aB^ 7@H Pa")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#regexprex16.py
#program searching all except space character
import re
matinfo=re.finditer("\S", " A#6aB^ 7@H Pa")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#regexprex17.py
#program searching digit character
import re
matinfo=re.finditer("\d", " A#6aB^ 7@H Pa")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#regexprex18.py
#program searching for all except digit
import re
matinfo=re.finditer("\D", " A#6aB^ 7@H Pa")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#regexprex19.py
#program searching for all word character
import re
matinfo=re.finditer("\w", " A#6aB^ 7@H Pa")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#regexprex20.py
#program searching for all special symbols except word character
import re
matinfo=re.finditer("\W", " A#6aB^ 7@H Pa")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#regexprex21.py
#program searching for all .
import re
matinfo=re.finditer(".", " A#6aB^ 7@H Pa")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#regexprex22.py
#program for searching only 'a'
import re
matinfo=re.finditer("a", "abaabaaab")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#regexprex23.py
#program for searching one 'a' or more 'a' s
import re
matinfo=re.finditer("a+", "abaabaaab")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#output
#start Index end index values
# 0 1 a
# 2 4 aa
# 5 8 aaa
#regexprex24.py
#program for searching zero or one 'a' or more 'a' s
import re
matinfo=re.finditer("a*", "abaabaaab")
print("------------------------------------------------------------
-----")
for mat in matinfo:
print("start index={}\t
value={}".format(mat.start(),mat.group()))
print("------------------------------------------------------------
-----")
#regexprex25.py
import re
#mobilenovalid.py
import re
while True:
mno=input("Enter Ur Mobile Number:")
if (len(mno)==10):
sres=re.search("\d{10}", mno)
if sres!=None:
print("Ur mobile Number Valid:")
break
else:
print("Ur Mobile Number is Invalid-bcoz It should
not contain str/ special symbols")
else:
print("Mobile Must Contain 10 digits")
#namesmarks.py
import re
studinfo="Arindam got 90 marks, Gosling got 99 marks, Rossum got 99
marks, Ramesh got 66, Ram got 88 marks and Jay got 77 marks"
print("-------------------------------------------------")
print("Student Marks")
print("-------------------------------------------------")
markslist=re.findall("\d{2}", studinfo)
for marks in markslist:
print("\t{}".format(marks))
print("-------------------------------------------------")
print("Student Names")
print("-------------------------------------------------")
names=re.finditer("[A-Z][a-z]+", studinfo)
for name in names:
print("\t{}".format(name.group()))
print("-------------------------------------------------")
==================================================
Pre-Defined Character Classes in Regular Expression
==================================================
=>These classes are already defined in Regular expressions and they
are used for preparing different search patterns.
=>Pre-Defined Character Classes in Regular Expression are given
bellow.
==================================================
Quantifiers in Regular Expression
==================================================
=>Quantifiers in Regular Expression are used for finding number of
occurences of special symobol / alphabet / digit.
=>We have the Quantifiers in Regular Expressions. They are
1) 'a'---->searching exactly for 'a'
2) a+--->searching for either one 'a' or more 'a' s
3) a*--->searching for either zero or one 'a' or more 'a' s
=======================================================
Note:
----------
1) \dddddddddd or \d{10}
2) [A-Za-z]+
3) \d{2}.d+
====================================================
Python Data Base Communication (PDBC)
(OR)
Communication Between Python and Data Base Softwares
====================================================
=>As we know that we achieved data persistency through the concept
of files and files are having some limitations.
1) Files of any Language are un-secured bcoz Files does not
provide user Name and password.
2) Files concept does not allows us to store large volume of
data.
3) The data of the file can be manipulated by any un-authrized
users bcoz Files does not provide user Name and password.
4) Querying the data from multiple file is complex
5) Structure of the File may differ from One OS to another OS.
===================================================================
=====
Steps for Developing Python Program to Communicate with Data
Base softwares(Oracle)
===================================================================
=====
1) import appropriate module of Data base Software and other
modules if required.
4) Design the Query, Place the Query in the Cursor object and send
Query to data base software by using Cursor object and
execute.
5) Python Program Process the Result , which came from Data Base
Software.
Syntax:- cx_Oracle.connect("username/password@DNS/serviceid")
------------
=>User Name---->Data base user name-----My System(KVR)---scott
=>password-----> Data base password------My System (KVR)---
tiger
=>DNS(Domain Naming Service)------->Name / IP address of the
machine where
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print(type(con)-------><class, cx_Oracle.Connection>
print("Python program objatins connection Oracle
db")
===================================================================
===
3) Create an object of cursor in python program, which is used to
carry the query from python program to data base
sodtware and Brings the result from data base software to the
python program.
-------------------------------------------------------------------
-------------------------------------------------------
===================================================================
=====
4) Design the Query, Place the Query in the Cursor object and send
Query to data base software by using Cursor object and
execute.
=================================================================
DDL Queries(Data Definition Language):
-----------------------------------------------------------
=>create, drop, alter...etc---
DML Queries(Data Maniplulation Langauge):
----------------------------------------------------------------
====>insert,delete,update
-------------------------------------------------------------------
-------------------------
DML Operations:
----------------------------------
=>These operations are used performing Operations on data or
records
=>we have 3 types of DML operations.
1) insert 2. delete 3. update
=>Once we execute any DML operation from Python program , we must
commoit()
1. Insert:
---------------
qry="insert into student values (10,'KVR',94.25,'OUCET')"
cur.execute(qry)
con.commit()
print("One Record Inserted--successfully")
PROGRAMS
#altertab1.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("Connection Obtained from Oracle DB")
print("-------------------------------------------------------
--")
cur=con.cursor()
kvrqry="alter table student add(cname varchar2(10))"
cur.execute(kvrqry)
print("Student Table altered in Oracle Db--verify")
except cx_Oracle.DatabaseError as de:
print(de)
finally:
if con!=None:
print("DB connection Closed:")
con.close()
#altertab2.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("Connection Obtained from Oracle DB")
print("-------------------------------------------------------
--")
cur=con.cursor()
kvrqry="alter table student modify(sname varchar2(15))"
cur.execute(kvrqry)
print("Student Table altered in Oracle Db--verify")
except cx_Oracle.DatabaseError as de:
print(de)
finally:
if con!=None:
print("DB connection Closed:")
con.close()
#createtab.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("Connection Obtained from Oracle DB")
print("-------------------------------------------------------
--")
cur=con.cursor()
kvrqry="create table student( sno number(3), sname
varchar2(10), marks number(5,2) )"
cur.execute(kvrqry)
print("Student Table created in Oracle Db--verify")
except cx_Oracle.DatabaseError as de:
print(de)
finally:
if con!=None:
print("DB connection Closed:")
con.close()
#dbcontest.py
import cx_Oracle
try:
kvrcon=cx_Oracle.connect("scott/tiger@localhost/kvrorcl")
except cx_Oracle.DatabaseError as da:
print("Problem in Getting Connection from Oracle DB")
else:
print("Python Program obtains connection from Oracle Data
base--Successfully:")
finally:
if kvrcon!=None:
print("Db connection Closed:");
kvrcon.close()
#droptab.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("Connection Obtained from Oracle DB")
print("-------------------------------------------------------
--")
cur=con.cursor()
kvrqry="drop table student"
cur.execute(kvrqry)
print("Student Table Dropped in Oracle Db--verify")
except cx_Oracle.DatabaseError as de:
print(de)
finally:
if con!=None:
print("DB connection Closed:")
con.close()
#recdelete1.py
#program for deleting record from table with static data
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("Connection Obtained from Oracle DB")
print("-------------------------------------------------------
--")
cur=con.cursor()
kvrqry="delete from student where sno=30"
cur.execute(kvrqry)
con.commit()
print("Student Record deleted from Student Table--verify")
except cx_Oracle.DatabaseError as de:
print(de)
finally:
if con!=None:
print("DB connection Closed:")
con.close()
#dynamicrecdelete1.py
#program for deleting record from table with dynamic data
import cx_Oracle
try:
sujcon=cx_Oracle.connect("scott/tiger@localhost/orcl")
sujcur=sujcon.cursor()
while(True):
try:
print("---------------------------------------------
------------")
stno=int(input("Enter Student Number for deleting a
record:"))
sujqry="delete from student where sno=%d "
sujcur.execute(sujqry %stno)
sujcon.commit()
print("---------------------------------------------
------------")
print("Student Record deleted:")
print("---------------------------------------------
------------")
ch=input("Do u want delete another record(yes/no):")
if(ch=="no"):
break
except ValueError:
print("Don't enter strs/ special symbols/ alpha-
numeric values:")
#dynamicrecinsert1.py
#program for inserting record in table with dynamic data
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
while(True):
try:
print("---------------------------------------------
-----")
stno=int(input("Enter Student Number:"))
stname=input("Enter Student Name:")
marks=float(input("Enter Student Marks:"))
colname=input("Enter College Name:")
#dynamicupdate.py
#program for updating a record in a table with dynamic data
import cx_Oracle
try:
sujcon=cx_Oracle.connect("scott/tiger@localhost/orcl")
sujcur=sujcon.cursor()
while(True):
try:
print("---------------------------------------------
------------")
stno=int(input("Enter Student Number for updating a
record:"))
stmarks=float(input("Enter Student Marks for
updating:"))
sujqry="update student set marks=%f where sno=%d"
sujcur.execute(sujqry %(stmarks, stno))
sujcon.commit()
print("---------------------------------------------
------------")
if(sujcur.rowcount>=1):
print("Student Record updated:")
else:
print("Student Number and its record does not
exists:");
print("---------------------------------------------
------------")
ch=input("Do u want update another record(yes/no):")
if(ch=="no"):
break
except ValueError:
print("Don't enter strs/ special symbols/ alpha-
numeric values:")
#recinsert1.py
#program for inserting record in table with static data
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("Connection Obtained from Oracle DB")
print("-------------------------------------------------------
--")
cur=con.cursor()
kvrqry="insert into student values(30,'MVR',39.25,'HCU')"
cur.execute(kvrqry)
con.commit()
print("Student Record Inserted In Student Table--verify")
except cx_Oracle.DatabaseError as de:
print(de)
finally:
if con!=None:
print("DB connection Closed:")
con.close()
#selectex1.py
#program for reading the records from table
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
sq="select * from student"
cur.execute(sq)
print("-------------------------------------------------")
print("Student Records")
print("-------------------------------------------------")
kvr=cur.fetchmany(2)
for rec in kvr:
for val in rec:
print("{}".format(val), end=" ")
print("\n")
print("-------------------------------------------------")
except cx_Oracle.DatabaseError as db:
print("Problem in Data base: ",db)
#testmy.py
import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
passwd='root')
if con.is_connected():
print("Python Program connected to My sql")
else:
print("no")
================================
Random Module In Python
================================
=>"random" is one of the pre-defined module.
=>The purpose of "random" module is used for perfoming some random
actions such as generating random number, selecting random element
from any iterable object, suffle the elements randomly...etc.
=>Some of the essential functions present in random module are
1) random()
2) randint()
3) randrange()
4) choice()
5) shuffle()
1)random():
-----------------
=> This function is used for generating any random number in the
float between 0.0 to 1.0
Syntax: random.random()
-----------------
Example:
-----------------
#rex1.py
import random
print(random.random())
Syntax:- random.randint(start,stop)
------------------
Example:
------------------
#rex2.py
import random
print(random.randint(1000,9999))
-----------------------------------------------------------------
3) randrange():
---------------------------
=>this function returns a randomly selected element from range
created by the start and stop. if we don't specify stop value then
it starts from 0 to start-1
Syntax1:
-------------
random.randrange(start)
Syntax:-
random.choice(iterable object)
Example:-
lst=[10,20,30,40,50]
print(random.choice(lst))
Example:
----------------
import random
lst=[10,20,30,40,50]
print(random.choice(lst))
print("--------------------------------------")
print(random.choice("PYTHON"))
print("--------------------------------------")
tpl=(10,"KVR","OUCET",34.56)
print(random.choice( tpl))
=============================================================
5) shuffle():
------------------
=>this function is used for re-ordering the elements of any
iterable object
=>this function is applicabe for only mutable objects.
Syntax:-
random.shuffle(iterable object)
===============================================
OOPS IN PYTHON
===============================================
=>In real time, to develop any project, we need a Language / Tech
and it can be satisfied two principles. They are
1) Procedure Oriented Principles
2) Object Oriented Principles
=>Python is one of the Procedure Oriented and Object Programming
Language. Even though python programming belongs to both,
internally all the values are treated as "objects".
===================================================================
==
" Benifits of Treating every thing is an Object in Python"
===================================================================
==
=>The confidential data transfered in the form cipher text /
encrypted format between client side application and server side
application. So that Security is enhanced.
=>The Large Volume of data transfered between Client Side and
Server Side application all at once ( in the form object) and
provides Effective Communication.
=>The data is available in the form of objects and we can apply
functions / methods on the objects to perform operations.
=========================================================
=>To Say a programming Language is object oriented , then it has
to satisfy object oriented Priciples.
=>The Object Oriented Priciples in Python are:
1. Classes
2. Objects
3. Data Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Message Passing
====================================================
==================================
Classes
==================================
=>The purpose of Classes concept is that "To Develop Programmer-
defined data Type + To Develop Real Time Applications ".
=>The pupose of Programmer-defined data Type is that to store
multiple values either of same type or different type or the both
types.
=>To develop programmer-defined data type with classes concept, we
use a keyword called "class".
=>Each and Every Meanigful applications in Python must be developed
by using classes concept.
-------------------------------------------------------------------
---------------------------------------
=>Def. of Class:-
------------------------
=>A class is a collection of Data Members(Instance Data memebrs and
Class Level Data Members) and Methods(3).
=>Here "Data Members" of Class are used for Storing data in the
objects(bcoz Data members of Class are available as it is as part
of object)
=>"Methods" of class are used for performing Operations(If we write
a Function inside class then those functions are called Methods).
-------------------------------------------------------------------
-------------------
Syntax for defining a class in python:
---------------------------------------------------------
class <clsname> :
@classmethod
def methodname(cls, ........):
----------------------------------------
Block of statements--Class Level Operations
----------------------------------------
@staticmethod
def methodname(...............):
----------------------------------------------
Block of statements--Utility Operations
----------------------------------------------
#studex1.py
#main program
so1=Student()
print("Id of so1=",id(so1))
print("content of so=",so1. __dict__) # { }
#add Instance Data members to an object so1
so1.stno=100
so1.sname="KVR"
so1.marks=55.55
#display the data
print("{}\t{}\t{}".format(so1.stno,so1.sname,so1.marks))
print("-----------------------------------------------------------
")
so2=Student()
print("Id of so2=",id(so2))
#add Instance Data members to an object so1
so2.stno=101
so2.sname="Omprkash"
so2.marks=65.55
print("Id of so2=",id(so2))
print("{}\t{}\t{}".format(so2.stno,so2.sname,so2.marks))
#studex2.py
#main program
so1=Student()
#add Instance Data members to an object so1
so1.stno=100
so1.sname="KVR"
so1.marks=55.55
#display the data
print("{}\t{}\t{}\t{}".format(so1.stno,so1.sname,so1.marks,so1.crs
))
print("-----------------------------------------------------------
")
so2=Student()
#add Instance Data members to an object so1
so2.stno=101
so2.sname="Omprkash"
so2.marks=65.55
print("{}\t{}\t{}\t{}".format(so2.stno,so2.sname,so2.marks,so2.crs)
)
==========================================
Types of Data Members in a Class of Python
==========================================
=>In python , we have 2 Types of Data Members in a Class. They are
=================================================
Types of Methods in a Class of Python
=================================================
=>In python programming, we have 3 types of methods. They are
1) Instance Methods
2) Class Level Methods
3) Static Methods
-------------------------------------------------------------------
--------------------------------------
1) Instance Methods:
-------------------------------
=>These methods are used for performing specific operations on
objects.
=>These methods can do the operations only on objects and hence
these methods are called Object Level Methods.
=>Instance methods Must written inside of calss definition by
taking "self" as a first formal parameter.
=>Instance Methods must be accesses w.r.t object name (or) w.r.t
self
objectname.Instancemethodname()
(or)
self.Instancemethodname()
================================
Object
================================
=>When we define a class, we don't get any memory for the data
members(Instance Memebrs) and methods(Instance Methods) but whose
memory space is created when we create an object.
=>To do any Data Processsing, We must create an object. In other
words, without creating any object, we can't do any meaningful
operations.
=>Programatically, to create an object , There must exists class
definition otherwise we get Error.
-------------------------------------------------------------------
------------------------------
Def. of Object:-- Instance of a class is called object (Instance
is nothing but allocating
-------------------- memory space for Data members and
Methods)
Creating an object:
----------------------------
=>To create an object, we use the following syntax
Syntax:
--------------
objectname=classname()
so=Student()
here so is called object name (or) reference vriable name
eo=Employee()
here eo is called object name (or) reference vriable name
===================================================================
===
PROGRAM
#program for cal area and perimeter of Circle using classes and
objects
#Circledemo.py
class Circle:
@classmethod
def setpi(cls): # class Level method
cls.pi=3.14 # class level data member
def circlearea(self):
print("--------------------------------------------------
---------------")
self.r=float(input("Enter Radious for cal Area of
Circle:"))
self.ac=Circle.pi*self.r*self.r
print("Area of Circle={}".format(self.ac))
print("--------------------------------------------------
---------------")
def circleperi(self):
print("--------------------------------------------------
---------------")
self.r=float(input("Enter Radious for cal Peri of
Circle:"))
self.pc=2*self.pi*self.r
print("Area of Circle={}".format(self.pc))
print("--------------------------------------------------
---------------")
#main program
Circle.setpi()
co=Circle()
co.circleperi()
co.circlearea()
#program for cal area and perimeter of Circle using classes and
objects
#Circledemo1.py
class Circle:
@classmethod
def setpi(cls): # class Level method
cls.pi=3.14 # class level data member
def readradious(self, op):
self.r=float(input("Enter Radious for {}:".format(op) ))
return self.r
class Hyderabad:
@staticmethod
def operations(c):
rad=c.readradious("area")
ac=3.14*rad*rad
print("Area of Circle={}".format(ac))
rad=c.readradious("peri")
pc=2*3.14*rad
print("\nperi of Circle={}".format(pc))
#main program
Circle.setpi()
co=Circle()
Hyderabad.operations(co)
class Employee:
@classmethod
def appendcompname(cls):
cls.compname="Wipro-HYD"
def appendempvalues(self):
print("Id in method=", id(self))
print("-------------------------------------------------
")
self.empno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
self.dsg=input("Enter Employee Designation:")
print("-------------------------------------------------
")
def dispempvalues(self):
print("Id in method=", id(self))
print("--------------------------------------------------
")
print("Employee Number : {}".format(self.empno))
print("Employee Name : {}".format(self.ename))
print("Employee Designation : {}".format(self.dsg))
print("Employee Salary : {}".format(self.sal))
print("Employee Comp Name :
{}".format(Employee.compname))
print("--------------------------------------------------
")
@staticmethod
def operation(a,b,ops):
if(ops=="+"):
print("{} {} {}={}".format(a,ops,b, a+b))
elif(ops=="-"):
print("{} {} {}={}".format(a,ops,b, a-b))
elif(ops=="*"):
print("{} {} {}={}".format(a,ops,b, a*b))
elif(ops=="/"):
print("{} {} {}={}".format(a,ops,b, a/b))
elif(ops=="//"):
print("{} {} {}={}".format(a,ops,b, a//b))
elif(ops=="%"):
print("{} {} {}={}".format(a,ops,b, a%b))
elif(ops=="**"):
print("{} {} {}={}".format(a,ops,b, a**b))
else:
print("U Don't Arithmetic Operators--plz learn")
#main program
Employee.appendcompname()
eo1=Employee()
print("Id of eo1 in main program=",id(eo1))
eo1.appendempvalues()
eo2=Employee()
print("Id of eo2 in main program=",id(eo2))
eo2.appendempvalues()
print("===================================")
eo1.dispempvalues()
eo2.dispempvalues()
print("===========================================")
print("Utility Operation")
print("===========================================")
eo1.operation(10,3,"*")
eo2.operation(10,3,"**")
#studex3.py
#main program
Student.crs="DS-AI"
so1=Student()
#add Instance Data members to an object so1
so1.stno=100
so1.sname="KVR"
so1.marks=55.55
#display the data
print("\n{}\t{}\t{}\t{}".format(so1.stno,so1.sname,so1.marks,so1.cr
s ))
print("-----------------------------------------------------------
")
so2=Student()
#add Instance Data members to an object so2
so2.stno=101
so2.sname="Omprkash"
so2.marks=65.55
print("{}\t{}\t{}\t{}".format(so2.stno,so2.sname,so2.marks,Student.
crs))
print("-----------------------------------------------------------
")
so3=Student()
#add Instance Data members to an object so3
so3.stno=102
so3.sname="dprasad"
so3.marks=66.55
print("{}\t{}\t{}\t{}".format(so3.stno,so3.sname,so3.marks,so3.crs)
)
=======================================
Introduction to Inheritance
=======================================
Def.. of Inheritance:
------------------------------
=>The process of obtaining the data memebrs and methods(features)
from one class into another class is called Inheritance
=>The Class which is giving data members and methods is called Base
/ super / parent class
=>The class which is taking data memebrs and Methods is called
Derived / sub / child class
==============================================================
=>Inheritance concept always follows Logical Memory Management.
=>This Memory Management Says "Neither we write Physical Source
Code nor It takes Physical Memory Space"
==============================================================
Advatanges of Inheritance:
-----------------------------------------
If we develop any python application with the concept of
inheritance, we get the following advantages.
class <clsname-1>:
-------------------
-------------------
class <clsname-2>:
-------------------
-------------------
class <clsname-n>:
-------------------
-------------------
Program
#InhProg1.py
class Company:
def getcompdet(self):
self.cname="Wipro"
self.loc="HYD"
#main program
eo=Employee()
eo.getempdet()
eo.getcompdet()
eo.dispempdet()
#InhProg2.py
class Company:
def getcompdet(self):
self.cname="Wipro"
self.loc="HYD"
class Food:
def getfooddet(self):
self.avfood="Biryani"
self.drink="apple juice"
#main program
eo=Employee()
eo.getempdet()
eo.getcompdet()
eo.getfooddet()
eo.dispempdet()
#InhProg3.py
class Univ:
def getunivdet(self):
self.uname=input("Enter Univ Name:")
self.uloc=input("Enter Univ Location:")
def dispunivdet(self):
print("-----------------------------------------------")
print("University Details:")
print("-----------------------------------------------")
print("University Name:{}".format(self.uname))
print("University Location:{}".format(self.uloc))
print("-----------------------------------------------")
class College(Univ):
def getColldet(self):
self.cname=input("Enter College Name:")
self.cloc=input("Enter College Location:")
def dispcolldet(self):
print("College Details:")
print("-----------------------------------------------")
print("College Name:{}".format(self.cname))
print("College Location:{}".format(self.cloc))
print("-----------------------------------------------")
class Student(College):
def getstuddet(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.crs=input("Enter Student Course:")
def dispstuddet(self):
print("Studet Details:")
print("-----------------------------------------------")
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Course:{}".format(self.crs))
print("-----------------------------------------------")
#main program
so=Student()
so.getstuddet()
so.getColldet()
so.getunivdet()
so.dispunivdet()
so.dispcolldet()
so.dispstuddet()
#InhProg4.py
class Univ:
def getunivdet(self):
self.uname=input("Enter Univ Name:")
self.uloc=input("Enter Univ Location:")
def dispunivdet(self):
print("-----------------------------------------------")
print("University Details:")
print("-----------------------------------------------")
print("University Name:{}".format(self.uname))
print("University Location:{}".format(self.uloc))
print("-----------------------------------------------")
class College:
def getColldet(self):
self.cname=input("Enter College Name:")
self.cloc=input("Enter College Location:")
def dispcolldet(self):
print("College Details:")
print("-----------------------------------------------")
print("College Name:{}".format(self.cname))
print("College Location:{}".format(self.cloc))
print("-----------------------------------------------")
class Student(College,Univ):
def getstuddet(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.crs=input("Enter Student Course:")
def dispstuddet(self):
print("Studet Details:")
print("-----------------------------------------------")
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Course:{}".format(self.crs))
print("-----------------------------------------------")
so=Student()
so.getstuddet()
so.getColldet()
so.getunivdet()
so.dispunivdet()
so.dispcolldet()
so.dispstuddet()
#InhProg5.py
class Univ:
def getunivdet(self):
self.uname=input("Enter Univ Name:")
self.uloc=input("Enter Univ Location:")
def dispunivdet(self):
print("-----------------------------------------------")
print("University Details:")
print("-----------------------------------------------")
print("University Name:{}".format(self.uname))
print("University Location:{}".format(self.uloc))
print("-----------------------------------------------")
class College(Univ):
def getColldet(self):
self.cname=input("Enter College Name:")
self.cloc=input("Enter College Location:")
so.getunivdet();
def dispcolldet(self):
so.dispunivdet()
print("College Details:")
print("-----------------------------------------------")
print("College Name:{}".format(self.cname))
print("College Location:{}".format(self.cloc))
print("-----------------------------------------------")
class Student(College):
def getstuddet(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.crs=input("Enter Student Course:")
so.getColldet()
def dispstuddet(self):
so.dispcolldet()
print("Studet Details:")
print("-----------------------------------------------")
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Course:{}".format(self.crs))
print("-----------------------------------------------")
so=Student()
so.getstuddet()
so.dispstuddet()
#InhProg6.py
class Univ:
def getunivdet(self):
self.uname=input("Enter Univ Name:")
self.uloc=input("Enter Univ Location:")
def dispunivdet(self):
print("-----------------------------------------------")
print("University Details:")
print("-----------------------------------------------")
print("University Name:{}".format(self.uname))
print("University Location:{}".format(self.uloc))
print("-----------------------------------------------")
class College(Univ):
def getColldet(self):
self.cname=input("Enter College Name:")
self.cloc=input("Enter College Location:")
self.getunivdet();
def dispcolldet(self):
self.dispunivdet()
print("College Details:")
print("-----------------------------------------------")
print("College Name:{}".format(self.cname))
print("College Location:{}".format(self.cloc))
print("-----------------------------------------------")
class Student(College):
def getstuddet(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.crs=input("Enter Student Course:")
self.getColldet()
def dispstuddet(self):
self.dispcolldet()
print("Studet Details:")
print("-----------------------------------------------")
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Course:{}".format(self.crs))
print("-----------------------------------------------")
so=Student()
so.getstuddet()
so.dispstuddet()
#university.py----->treated as module
class Univ:
def getunivdet(self):
self.uname=input("Enter Univ Name:")
self.uloc=input("Enter Univ Location:")
def dispunivdet(self):
print("-----------------------------------------------")
print("University Details:")
print("-----------------------------------------------")
print("University Name:{}".format(self.uname))
print("University Location:{}".format(self.uloc))
print("-----------------------------------------------")
#student.py---treated as module
from college import College
class Student(College):
def getstuddet(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.crs=input("Enter Student Course:")
self.getcolldet()
self.getunivdet()
def dispstuddet(self):
self.dispunivdet()
self.dispcolldet()
print("Studet Details:")
print("-----------------------------------------------")
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Course:{}".format(self.crs))
print("-----------------------------------------------")
#studcolluniv.py
from student import Student
so=Student()
so.getstuddet()
so.dispstuddet()
=================================
Polymorphism
=================================
=>Polymorphism is one of the distinct principle of OOPs
=>The process of representing "one form in multiple multiple forms"
is called Polymorphism
========================================
super()
========================================
=>super() is used for calling Base class Original methods from the
context of overridden method of derived class
=>super() is also used for calling Base class Constructor from the
context of overridden Constructor of derived class.
a) classname.methodname(self)
(OR)
classname.methodname(self, list of values)
Syntax: 3 (At constructor Level)
a) classname.__init__(self)
(OR)
classname.__init__(self, list of values)
===================================================================
====
Programs
#polyex1.py
class Circle(object):
def draw(self):#original method
print("Drawing Circle--Circle class:")
class Rect(Circle):
def draw(self): # overridden method
super().draw() # will call draw() of Circle class
print("Drawing Rect--Rect class:")
class Square(Rect):
def draw(self): # overridden method
super().draw() # will call draw() of Rect class
print("Drawing Square--Squar class:")
#main program
so=Square()
so.draw();
#polyex2.py
class Circle(object):
def __init__(self):#original constructor
print("Drawing Circle--Circle class:")
class Rect(Circle):
def __init__(self): # overridden constructor
super().__init__() #calling __int__() of Circle class
print("Drawing Rect--__init__(self):")
class Square(Rect):
def __init__(self): # overridden constructor
super().super().__init__() #calling __int__() of Rect
class
print("Drawing Square-- __init__(self):")
#main program
so=Square()
#polyex3.py
class Circle(object):
def draw(self):#original method
print("Drawing Circle--Circle class:")
class Rect:
def draw(self):
print("Drawing Rect--Rect class:")
class Triangle:
def draw(self):
print("Drawing Triangle--Triangle class:")
#main program
so=Square()
so.draw();
#polyex4.py
class Circle(object):
def __init__(self):#original constructor
print("Drawing Circle--Circle class:")
class Rect:
def __init__(self):
print("Drawing Rect--__init__(self):")
class Triangle:
def __init__(self):
print("Drawing Triangle--__init__(self):")
class Square(Rect,Circle,Triangle):
def __init__(self): # overridden constructor
print("Drawing Square-- __init__(self):")
Circle.__init__(self)
Rect.__init__(self)
Triangle.__init__(self)
#main program
so=Square()
#polyex5.py
class Circle:
def area(self,r):# original method
ac=3.14*r*r
print("Area of Circle=",ac)
class Square(Rect):
def area(self,s): # overridden method
as1=s*s
print("Area of Square=",as1)
print("----------------------------------------")
super().area(float(input("Enter Length of
Rect:")),float(input("Enter breadth of Rect:")))
print("----------------------------------------")
Circle.area(self,float(input("Enter Radious of
Circle:")))
# main program
so=Square()
so.area(float(input("Enter Side of Square:")))
#polyex6.py
class Circle:
def area(self,r):# original method
print("----------------------------------------")
ac=3.14*r*r
print("Area of Circle=",ac)
class Square:
def area(self,s): # overridden method
print("----------------------------------------")
as1=s*s
print("Area of Square=",as1)
class Rect :
def area(self,l,b=12):# overridden method
print("----------------------------------------")
ar=l*b
print("Area of Rect=",ar)
#main program
co=Circle()
so=Square()
ro=Rect()
lst=[]
lst.append(co)
lst.append(so)
lst.append(ro)
for obj in lst:
obj.area(3)
print("-------------------------------------------")
for obj in (co,ro,so):
obj.area(6)
#polyex7.py
class India:
def capital(self): # original method
print("Delhi is the capital of India")
class Country:
@staticmethod
def dispCountryInfo(obj):
print("--------------------------------------------------
--")
obj.capital()
obj.lang()
obj.type()
print("--------------------------------------------------
--")
#main program
uo=USA()
ind=India()
Country.dispCountryInfo(uo)
Country.dispCountryInfo(ind)
#polyex10.py
class India:
def capital(self): # original method
print("Delhi is the capital of India")
def lang(self): # original method
print("Hindi / Mixed Lang Indian can speack")
def type(self): # original method
print("India is a developping.... Country")
class USA:
def capital(self):
print("WashingTon is the capital of USA")
def lang(self):
print("English Lang, Americans can speack")
def type(self):
print("USA is a developped Country")
class Country:
@staticmethod
def dispCountryInfo(obj):
print("--------------------------------------------------
--")
obj.capital()
obj.lang()
obj.type()
print("--------------------------------------------------
--")
#main program
uo=USA()
ind=India()
for kvobj in (ind,uo):
Country.dispCountryInfo(kvobj)
===============================================
Data Encapsualtion and Data Abstraction
===============================================
Data Encapsualtion:
-----------------------------
=>The process hiding the confidential information( Data members /
Methods) from external Programmers / Users is called Data
Encapsualtion
=>Data Encapsulation can be implemented (like private in Java) in
python for hinding the data members and methods.
=>the members can be hidden from external programmers by following
the syntax
def __methodname(self,.....):
------------------------
------------------------
=>The __data member name (private data member) and __method
name(..) (private method) can be accessed in the context of same
class but not possible to access in the context of other classes.
Example: account.py
-------------------------------
Data Abstraction:
-------------------------------
=>The process of retrieving essential details without considering
about hidden details is called Data Abstraction.
Example: others.py
#account.py----treated as module
class Account:
def __init__(self):
self.__acno=10
self.cname="Avinash"
self.__bal=3.4
self.__pin=1234
self.bname="SBI"
def __openPinCover(self): # private method
print("Ur pin is={}".format(self.__pin))
#others.py
from account import Account
ao=Account()
print("------------------------------------------------------------
-----")
#print("Account Number=",ao.acno) can't access
print("Account Holder Name=",ao.cname)
#print("Account Balance=",ao.bal) can't access
#print("Account Pin=",ao.pin) can't access
print("Account Branch Name=",ao.bname)
print("------------------------------------------------------------
-----")
#ao.openPinCover() can't access
================================
OOPs--->Constructors in Python
================================
=>The purpose of Constructors in a class of Python is that "To
Initlize the Object " (OR) Constructors are always used for placing
our values in the object without empty
=>Def of Constructor:
--------------------------------
=>A Constructor is one of the special method , which is
automatically / implicitly called by PVM during object creation
whose role is to place our own values in the object without empty.
---------------------------------------------------
Syntax for defining Constructor:
---------------------------------------------------
def __init__(self, list of formal params if any):
------------------------------------------------
------------------------------------------------
Block of statemnts--Initlization
------------------------------------------------
------------------------------------------------
#defaulconsex1.py
class Test:
def __init__(self):
self.a=10
self.b=20
t1=Test()
print("Content of t1=", t1.__dict__)
t2=Test()
print("Content of t2=", t2.__dict__)
t3=Test()
print("Content of t3=", t3.__dict__)
#emp.py
class Employee:
def getempvalues(self):
self.eno=int(input("Enter Emp Number:"))
self.ename=input("Enter Emp Name:")
self.dsg=input("Enter Emp Designation:")
def dispempvalues(self):
print("Emp Number: {}".format(self.eno))
print("Emp Name: {}".format(self.ename))
print("Emp Designation: {}".format(self.dsg))
#main program
eo1=Employee() # when we create an object, it must initlized by
calling one special method implicitly by PVM--that special method
is called Constructor
print("content of eo1=", eo1.__dict__)
#emp1.py
class Employee:
@classmethod
def __init__(self, a,b,c):
print("--------------------------------------")
self.eno=int(input("Enter Emp Number:"))
self.ename=input("Enter Emp Name:")
self.dsg=input("Enter Emp Designation:")
print("--------------------------------------")
def dispempvalues(self):
print("--------------------------------------------------
-")
print("Emp Number: {}".format(self.eno))
print("Emp Name: {}".format(self.ename))
print("Emp Designation: {}".format(self.dsg))
print("--------------------------------------------------
-")
#main program
eo1=Employee()
eo2=Employee()
eo3=Employee()
#paramconsex1.py
class Test:
def __init__(self, a,b):
self.a=a
self.b=b
t1=Test(10,20)
print("Content of t1=", t1.__dict__)
t2=Test(100,200)
print("Content of t2=", t2.__dict__)
t3=Test(1000,2000)
print("Content of t3=", t3.__dict__)
#sample.py
class Sample:
def __init__(self, a=100, b=200):
print("-------------------------------------------")
self.a=a
self.b=b
print("Val of a :{}".format(self.a))
print("Val of b :{}".format(self.b))
print("-------------------------------------------")
#main program
print("so1 values")
so1=Sample() # default constructor
print("so2 values")
so2=Sample(1,2) # Parameterized constructor
print("so3 values")
so3=Sample(10) # Parameterized constructor
print("so4 values")
so4=Sample(b=55,a=65) # Parameterized constructor
print("so5 values")
so5=Sample(b=555) # Parameterized constructor
================================================================
Garbage Collection--gc module
and
Destructors in Python
================================================================
=>A destructor is a special method identified as __del__(self),
which automatically / implicitly called by Garbage Collector .
=>Garbage Collector is in-built program, which is automatically
calling destructor provided when the referenced object becomes un-
referenced bcoz of two operations.
1) del objname
or
2) objname=None
PROGRAMS
#destex1.py
import time
class Sample:
def __init__(self):
print("Object Initliztion---Constructor:")
def __del__(self):
print("Memory Space pointed by object removed--Garbage
Collector")
#main program
s1=Sample()
print("object created and initlized");
time.sleep(10)
s1=None
print("End of application")
#destex2.py
import time
class Sample:
def __init__(self):
print("Object Initliztion---Constructor:")
def __del__(self):
print("Memory Space pointed by object removed--Garbage
Collector")
#main program
s1=Sample()
print("object created and initlized");
time.sleep(10)
print("End of application")
#destex3.py
import time
class Sample:
def __init__(self):
print("Object Initliztion---Constructor:")
def __del__(self):
print("Memory Space pointed by object removed--Garbage
Collector")
#main program
s1=Sample()
print("object created and initlized");
s2=s1
s3=s2
print("Object s3 is removed")
s3=None
time.sleep(10)
print("Object s2 is removed")
s2=None
time.sleep(10)
print("Object s1 memory space is going be removed")
s1=None
time.sleep(10)
print("End of Application")
#destex4.py
import time
class Sample:
def __init__(self):
print("Object Initliztion---Constructor:")
def __del__(self):
print("Memory Space pointed by object removed--Garbage
Collector")
#main program
s1=Sample()
print("object created and initlized");
s2=s1
s3=s2
print("Object s3 is removed")
time.sleep(10)
print("Object s2 is removed")
time.sleep(10)
print("Object s1 memory space is going be removed")
time.sleep(10)
print("End of Application")
#destex5.py
import time
class Sample:
def __init__(self):
print("Object Initliztion---Constructor:")
def __del__(self):
print("Memory Space pointed by object removed--Garbage
Collector")
#main program
lst=[ Sample(),Sample(),Sample() ]
print("we created 3 sample objects and placed in lst")
time.sleep(10)
del lst
time.sleep(10)
print("end of application")
#destex6.py
import time
class Sample:
def __init__(self):
print("Object Initliztion---Constructor:")
def __del__(self):
print("Memory Space pointed by object removed--Garbage
Collector")
#main program
s1=Sample()
s2=Sample()
s3=Sample()
print("we created 3 sample objects and placed in lst")
time.sleep(10)
print("object s1--memory space")
del s1 # gc is calling __del__(self)
time.sleep(10)
print("object s2--memory space")
del s2 # gc is calling __del__(self)
time.sleep(10)
print("object s3--memory space")
del s3 # gc is calling __del__(self)
time.sleep(10)
print("end of application")
#destex7.py
import time,sys
class Sample:
def __init__(self):
print("Object Initliztion---Constructor:")
def __del__(self):
print("Memory Space pointed by object removed--Garbage
Collector")
#main program
s1=Sample()
s2=s1
s3=s2
print("Refs of s1=", sys.getrefcount(s1)) #4
print("end of application")
=====================================
Garbage Collection--gc module
=====================================
=>We know that garbage Collector is python in-built program, which
is running by default in background our python application for
collecting / removing Un-Used memory space and improves the
performnace of Python Based applications.
=>To deal with garbage Collection Facility , we use a pre-defned
module called "gc"
=>The module gc contains the following functions.
a) gc.disable()------>used for stopping the exection of
garbage collector
b) gc.enable()------>used to start the exection of garbage
collector
c) gc.isenabled()--> It returns True provided garbage
collector program is running
It returns False provided garbage
collector program is not running
-----------------
Example:
-----------------
#gcdemo.py
-------------------
import gc
print("By default Garbage Collector Program is running ..")
#gc module----- isenabled()--->True(running) Flase (not
running)
print("is Garbage Colletcor Running by default=", gc.isenabled()) #
True
#gc module----- disable()--->Garbage Collector program stops
running
gc.disable()
print("is Garbage Colletcor Running afer disable()=",
gc.isenabled()) # False
#gc module----- enable()--->Garbage Collector program starts
running
gc.enable()
print("is Garbage Colletcor Running afer enable()=",
gc.isenabled()) # True
-------------------------------------------------------------------
-----------------------------------
#gcdemo.py
import gc
print("By default Garbage Collector Program is running ..")
#gc module----- isenabled()--->True(running) Flase (not
running)
print("is Garbage Colletcor Running by default=", gc.isenabled()) #
True
#gc module----- disable()--->Garbage Collector program stops
running
gc.disable()
print("is Garbage Colletcor Running afer disable()=",
gc.isenabled()) # False
#gc module----- enable()--->Garbage Collector program starts
running
gc.enable()
print("is Garbage Colletcor Running afer enable()=",
gc.isenabled()) # True
==========================================
Network Programming In Python
==========================================
=>The purpose of Network Programming is that "To share the data /
info across the network".
=>Def of network:
-------------------------
=>"Collection of interconnected computers connected each other"
-------------------------------------------------------------------
Steps for developing Server Side Application
-------------------------------------------------------------------
-
1) write the server side program
2) Every server side program be available in a machine(DNS--
>localhost or IP Adress->127.0.0.1) and it
must run at unique Port number
3) The Client Side Program must send a request to the server side.
4) The Client Side Program must receive the response from Server
Side Program and display.
host=socketobj.gethostname()
-------------------------------------------------------------------
-------------------------------
3) connect(dns,port):
----------------------------------------------
=>This function is used for obtaning connection from server side
program by passing dns and port in the tuple by client side
program.
Syntax: varname1,varname2=socket.accept()
varname1 represents connection object
varname2 represents addr of client at server side
Example: kvrcon, kvradd=socketobj.accept()
-------------------------------------------------------------------
--------------
6) send():-
-----------------
=>This function is used for sending the data from client side to
server side program and from server side program to client side
program with encode()
syntax: socketobj.send(strdata.encode())
Example:-socketobj.send("Hello Rossum".encode())
-------------------------------------------------------------------
----------
7) recv()---> [ 1024 2048 4096......] :
=>This function is used for recevinging the data from client side
to server side program and from server side program to client side
program with decode() by specifing size of data by mensioning
either 1024 or 2048 or 4096...etc
syntax: varname=socketobj.recv(1024).decode()
varname is an object, which is holding server data or
client
-------------------------------------------------------------------
-------
Program
#client1.py
import socket
s=socket.socket()
s.connect(("localhost",8989) )
print("---------------------------------------------------")
print("Client Side Program connected to server side program");
print("---------------------------------------------------")
cdata=input("Enter a Message:")
s.send(cdata.encode())
print("---------------------------------------------------")
sdata=s.recv(1024).decode()
print("Data from Server at Client side={}".format(sdata))
print("---------------------------------------------------")
#server1.py
import socket
s=socket.socket()
s.bind( ("localhost",8989) )
s.listen(4)
print("------------------------------------------------------------
---")
print("Server Side Program is ready to accept client Request...");
print("------------------------------------------------------------
---")
while(True):
con,addr=s.accept()
print("Type of con=",type(con))
print("Type of addr=",type(addr))
print("Server program connected to client at:
{}".format(addr))
cdata=con.recv(1024).decode()
print("Data from Client at Server side={}".format(cdata))
con.send("Hi, This is KVR from server Side".encode())
#client2.py----> This program accept a number from kbd at client,
send to server and get its square.
import socket
s=socket.socket()
s.connect(("localhost",9999) )
print("---------------------------------------------------")
print("Client Side Program connected to server side program");
print("------------------------------------------------------")
val=input("\nEnter a number:")
s.send(val.encode())
sdata=s.recv(1024).decode()
print("------------------------------------------------------")
print("Square of {} at Client Side:{}".format(val,sdata))
print("------------------------------------------------------")
=======================================
Storing the data in numpy programming
=======================================
=>In numpy programming, to store the data, we must create an object
of ndarray class.
a)array():
------------
=>It is used for creating an object of ndarray by passsing an
object which is containing multiple values (OR) any function
returns an of array of elements.
Syntax:-
-----------
varname=np.array(object, dtype)
>>>a=np.array(10)
>>> a
array(10)
>>> type(a)-----------<class 'numpy.ndarray'>
>>> a.ndim---0
--------------------------------------
>>> l1=[10,20,30,40]
>>> a=np.array(l1)
>>> a-----------array([10, 20, 30, 40])
>>> a.ndim--------------1
---------------------------------------------------------------
>>> l1=[[10,20,30],[30,40,50],[60,70,80]]
>>> a=np.array(l1)
>>> a
array([[10, 20, 30],
[30, 40, 50],
[60, 70, 80]])
>>> a.ndim--------------2
>>> print(type(a))-----------<class 'numpy.ndarray'>
-------------------------------------------------------------------
--------
>>> def fun():
... l1=[[10,20],[30,40]]
... return l1
...
>>> a=np.array(fun())
>>> type(a)
<class 'numpy.ndarray'>
>>> a
array([[10, 20],
[30, 40]])
>>> a.ndim---------2
========================================================
special examples:
----------------------------
>>> a=np.array([10,20,30.2])
>>> a------------>array([10. , 20. , 30.2])
>>> a.dtype---------->dtype('float64')
>>> a=np.array([10,20,40,True])
>>> a.dtype----------dtype('int32')
>>> a------------array([10, 20, 40, 1])
>>> a=np.array([10,20,40,True,2.3])
>>> a----------array([10. , 20. , 40. , 1. , 2.3])
>>> a.dtype------------dtype('float64')
-------------------------------------------------------------------
-----------------------
>> a=np.array([10,20,40,True])
>>> a.dtype
dtype('int32')
>>> a------------array([10, 20, 40, 1])
>>> a=np.array([10,20,40,True,2.3])
>>> a-----------------array([10. , 20. , 40. , 1. , 2.3])
>>> a.dtype---------------dtype('float64')
>>> a=np.array([10,20,40,True,2.3,0], dtype='bool')
>>> a-----------array([ True, True, True, True, True, False])
>>> a.dtype-----------dtype('bool')
>>> a=np.array([10,20,30,'kvr'])
>>> a---array(['10', '20', '30', 'kvr'], dtype='<U11')
>>> a=np.array(['kvr','pyt','jav'])
>>> a----array(['kvr', 'pyt', 'jav'], dtype='<U3')
>>> a=np.array(['kr','pt','jav'])
>>> a-------array(['kr', 'pt', 'jav'], dtype='<U3')
>>> a=np.array(['kr','pt','jv'])
>>> a------------array(['kr', 'pt', 'jv'], dtype='<U2')
>>> a=np.array([10,20,2+3j])
>>> a------array([10.+0.j, 20.+0.j, 2.+3.j])
>>> a=np.array([10,20,2+3j], dtype='int')-->TypeError: can't
convert complex to int
>>> a=np.array([10,20,2+3j], dtype='complex')
>>> a-----------array([10.+0.j, 20.+0.j, 2.+3.j])
>>> a=np.array([10,20,2+3j], dtype='str')
>>> a------------array(['10', '20', '(2+3j)'], dtype='<U6')
>>> a.dtype----------dtype('<U6')
>>> a=np.array([10,20,2+3j], dtype='float')----TypeError: can't
convert complex to float
>>> a=np.array([10,'KVR',12.34,True,2+4j])
>>> a-----array(['10', 'KVR', '12.34', 'True', '(2+4j)'],
dtype='<U64')
>>> a=np.array([10,'KVR',12.34,True,2+4j],dtype='object')
>>> a----------array([10, 'KVR', 12.34, True, (2+4j)],
dtype=object)
>>> a.dtype-------dtype('O')
-------------------------------------------------------------------
--------------------------------------------------
2)arange():
---------------------
=>arange() is used generating seqence of numerical values in the
form 1-Dimensional array only.[ if we want to view then in matrix
format, we must use reshape())
Examples:
------------------
import numpy as np
>>> a=np.array([10,20,30,40])
>>> a
array([10, 20, 30, 40])
>>> a.ndim
1
>>> a=np.array([ [10,20],[30,40]])
>>> a.ndim
2
>>> a
array([[10, 20],
[30, 40]])
>>> a=np.arange(10)
>>> type(a)
<class 'numpy.ndarray'>
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a=np.arange(10, dtype='float')
>>> a
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
>>> a=np.arange(10)
>>> type(a)
<class 'numpy.ndarray'>
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.ndim
1
>>> a.shape
(10,)
>>> a.size
10
>>> a.reshape(5,2)
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.reshape(2,5)
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> a.reshape(10,1)
array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
>>> a.reshape(1,10)
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
a=np.arange(10,20)
>>> a
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> a.size
10
>>> a.reshape(2,5)
array([[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
a=np.arange(10,20,3)
>>> a
array([10, 13, 16, 19])
>>> a.reshape(2,2)
array([[10, 13],
[16, 19]])
-------------------------------------------------------------------
-------------------------------------------
3) linspace():
-----------------------
=>This function is used for generating equally spaced numbers will
be generated.
(OR)
=> This function returns exactly spaced numbers over a specified
interval
=>this function returns the values in the form float
=>the default value for linspace is 50.
Syntax:
varname=np.linspace(start,stop, lin_num)
Example:-
----------------
a=np.linspace(1,10, 5)
>>> a
array([ 1. , 3.25, 5.5 , 7.75, 10. ])
>>> a=np.linspace(1,50, 10)
>>> a
array([ 1. , 6.44444444, 11.88888889, 17.33333333,
22.77777778,
28.22222222, 33.66666667, 39.11111111, 44.55555556, 50.
])
-------------------------------------------------------------------
-------------------------------
4) zeros():
-------------
=>This function is used for creating ndarray matrix with zeros
depends on type of shape we specify.
=>This function fills the value '0' (zero)
Example:
-------------------------
>>> a=np.zeros(10)
>>> a.ndim
1
>>> a.shape
(10,)
>>> a.size
10
>>> a
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> a.reshape(5,2)
array([[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.]])
>>> a.reshape(2,5)
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
>>> a.reshape(3,3)--------->-ValueError: cannot reshape array of
size 10 into shape (3,3)
-------------------------------------------------------------------
-----------------------------------------------------
a=np.zeros((3,3))
>>> a
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
>>> a=np.zeros((3,3), dtype='int')
>>> a
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros((4,3), dtype='int')
>>> a
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
-------------------------------------------------------------------
--------------------------------------------------------
5) ones():
---------------
>This function is used for for creating ndarray matrix with ones
depends on type of shape we specify.
=>This function fills the value '1' (one )
Examples:
-----------------
a=np.ones(6)
>>> type(a)
<class 'numpy.ndarray'>
>>> a
array([1., 1., 1., 1., 1., 1.])
>>> a=np.ones(6,dtype='int')
>>> a
array([1, 1, 1, 1, 1, 1])
>>> a.reshape(2,3)
array([[1, 1, 1],
[1, 1, 1]])
>>> a.reshape(3,2)
array([[1, 1],
[1, 1],
[1, 1]])
-------------------------------------------------------------------
------
a=np.ones((3,3),dtype='int')
>>> a
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
>>> a=np.ones((3,4),dtype='int')
>>> a
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> a=np.ones((2,6),dtype='int')
>>> a
array([[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]])
-------------------------------------------------------------------
----------------------------
6) full():
------------
The purpose of full() is that to fill the ndarray object with
programmer specified value along with its dtype.
Examples:
------------------
>> a=np.full(5,fill_value=6)
>>> a
array([6, 6, 6, 6, 6])
>>> a=np.full(shape=(5,), fill_value=8)
>>> a
array([8, 8, 8, 8, 8])
>>> a=np.full(fill_value=9,shape=(10,))
>>> a
array([9, 9, 9, 9, 9, 9, 9, 9, 9, 9])
>>> a.reshape(5,2)
array([[9, 9],
[9, 9],
[9, 9],
[9, 9],
[9, 9]])
>>> a.reshape(2,5)
array([[9, 9, 9, 9, 9],
[9, 9, 9, 9, 9]])
>>> a=np.full(4,2)
>>> a
array([2, 2, 2, 2])
>>> a.reshape(2,2)
array([[2, 2],
[2, 2]])
>>> type(a)
<class 'numpy.ndarray'>
-------------------------------------------------------------------
---------------------------------------
>>>a=np.full((3,3),5)
>>> a
array([[5, 5, 5],
[5, 5, 5],
[5, 5, 5]])
>>> a=np.full((3,3),1)
>>> a
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
>>> a=np.full((3,4),0)
>>> a
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
-------------------------------------------------------------------
------------------------------------
7) eye()
----------------------------------------------------------
=>This function is used for generating identity matrix ( ie. 1 in
principle diagonal elements and 0 in other places)
---------------------
Explanation:
---------------------
=>here 'n' represents number of rows
'm' represents number of columns
k represents principle diagonal (k=0)
if k=-1,-2... represents bellow principle diagonal made
as 1
if k=1 2,.....represents above principle diagonal made
as 1
=>If we don't pass 'm' value then by default 'n' value will be
considered as 'm' value.
Examples:
------------------
>>a=np.eye(3)
>>> a
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> a=np.eye(3,dtype='int')
>>> a
array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> a=np.eye(3,2,dtype='int')
>>> a
array([[1, 0],
[0, 1],
[0, 0]])
>>> a=np.eye(3,4,dtype='int')
>>> a
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])
>>> a=np.eye(5,5,dtype='int')
>>> a
array([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]])
>>> a=np.eye(5,5, k=1,dtype='int')
>>> a
array([[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0]])
>>> a=np.eye(5,5, k=-1,dtype='int')
>>> a
array([[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0]])
>>> a=np.eye(5,5, k=-2,dtype='int')
>>> a
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0]])
>>> a=np.eye(5,5, k=-3,dtype='int')
>>> a
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0]])
>>> a=np.eye(5,5, k=1,dtype='int')
>>> a
array([[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0]])
>>> a=np.eye(5,5, k=2,dtype='int')
>>> a
array([[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
-------------------------
8)identity()
-------------------------
=>This function is used for generating identity or unit matix
(always square matrix)
syntax:- np.identity(n,dtype)
=>here 'n' repersents (n,n), i.e n rows and n columns.
Example:
------------------
>>> a1=np.identity(3)
>>> a1
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> a1=np.identity(3, dtype='int')
>>> a1
array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
=============================================================
============================
ndarray
============================
=>In numpy module programming, the data is always stored in the
form of object whose type is 'ndarray'
=>here 'ndarray' is a pre-defined class in numpy module and whose
objects allows to store array of values.
=>an object of ndarray takes less memory space fast in data
analysis.
-------------------------------------------------------------------
------------------------------------------------
Differences between ndarray and tradtional list of python lang
-------------------------------------------------------------------
----------------------------
=>an object of ndarray takes less memory space fast in data
analysis and list object takes more memory space.
=>on the object of ndarray, we can perform Vector operations. where
as on the object of list we can't perform any vector operations.
============================================================
Attrubutes of ndarray :
-----------------------------------
a) ndim---->gives dimesion of an array.
b) shape--->returns shape of an array in the form of tuple ()
c) size------>returns no. of values in the array
d) dtype--->returns data type of ndarray
c) itemsize--->returns the memory space occupied by every element
of an array
-------------------------------------------------------------------
--------------------------------------------------
=============================
1) Numpy Indexing
=============================
=>In indexing Process, we find or obtain a single value from given
array by passing valid existing position otherwise we IndexError
>>> a.ndim---------------1
>>> b.ndim---------------2
---------------------------------
>>> b[0,0]
10
>>> b[1,1]
50
>>> b[2,2]
90
-----------------------------
>>> b[-3][-3]
10
>>> b[-3,-3]
10
-----------------------------
>>> b[-13,-13]----IndexError: index -13 is out of bounds for axis 0
with size 3
>>> b[-3,-13]----IndexError: index -13 is out of bounds for axis 1
with size 3
=================================
Numpy Slicing Operations
=================================
=>The purpose of Numpy Slicing Operations is that to extract some
range values from the given nd array object.
=>We can perform Numpy Slicing Operations on two things. The are
Examples:
-------------------
>>> a=np.array([10,20,30,40,50,60,70])
>>> a
array([10, 20, 30, 40, 50, 60, 70])
>>> a[0:6]
array([10, 20, 30, 40, 50, 60])
>>> a[2:6]
array([30, 40, 50, 60])
>>> a[2:]
array([30, 40, 50, 60, 70])
>>> a[:6]
array([10, 20, 30, 40, 50, 60])
>>> a[:]
array([10, 20, 30, 40, 50, 60, 70])
-------------------------------------------------------------------
------------------------
syntax2:- ndarrayobject[start:stop:step]
-----------
Rules:
-----------
1) For 'start' and 'stop' values , we can pass both Possitive and
Negative Values.
ndarrayobj[rowindex,colindex]
------------------------------------------
Syntax for 2-D array slicing
------------------------------------------
ndarrayobj[rowindex,colindex]
ndarrayobj[begin:end:step, begin:end:step ]
----------------------- -------------------
--
slice1 slice2
=>here slice1 represents Rows
=>here slice2 represents Columns
Examples:
-----------------
a[0:1,0:3]
array([[10, 20, 30]])
>>> a[0:1,:]
array([[10, 20, 30]])
>>> a[0::2,:]
array([[10, 20, 30],
[70, 80, 90]])
>>> a[0:3:2,:]
array([[10, 20, 30],
[70, 80, 90]])
>>> a[1:2, : ]
array([[40, 50, 60]])
>>> a[1:2, 0:2 ]
array([[40, 50]])
>>> a[1:2, :2 ]
array([[40, 50]])
>>> a[ :, 2:]
array([[30],
[60],
[90]])
>>> a[1:3,0:3]
array([[40, 50, 60],
[70, 80, 90]])
>>> a[1:3, :]
array([[40, 50, 60],
[70, 80, 90]])
>>> a[1:, :]
array([[40, 50, 60],
[70, 80, 90]])
>>> a[0:2,0:2]
array([[10, 20],
[40, 50]])
>>> a[:2,:2]
array([[10, 20],
[40, 50]])
>>> a[0:2,1: ]
array([[20, 30],
[50, 60]])
>>> a[0:2,1:3]
array([[20, 30],
[50, 60]])
>>> a[0:2,1:]
array([[20, 30],
[50, 60]])
>>> a[:,1:2]
array([[20],
[50],
[80]])
>>> a[:3,1:2]
array([[20],
[50],
[80]])
>>> a[:3,1:2]
array([[20],
[50],
[80]])
>>> a[:3:2,1:2]
array([[20],
[80]])
>>> a[:3:2,0:1]
array([[10],
[70]])
>>> a[::2,0:1]
array([[10],
[70]])
>>> a[::2,1: ]
array([[20, 30],
[80, 90]])
>>> a[0:3:2,1:3 ]
array([[20, 30],
[80, 90]])
>>> a[: ,1:]
array([[20, 30],
[50, 60],
[80, 90]])
>>> a[::2, ::2]
array([[10, 30],
[70, 90]])
>>> a[0:3:2, 0:3:2]
array([[10, 30],
[70, 90]])
===================================================================
====
===================================================
Numpy Advanced Indexing and Slicing
===================================================
=>If we want access multiple elements which are not in order /
sequence (random elements or arbitrary elements) then we must
advanced indexing.
Examples:
------------------
a=np.array([[10,20,30],[40,50,60],[70,80,90]])
>>> a
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
>>> a[[0,2],[0,2]]
array([10, 90])
>>> a[[0,1,2],[0,1,2]]
array([10, 50, 90])
>>> a[ [0,1,2],[2,1,0]]
array([30, 50, 70])
>>> a[[1,2,2],[2,1,2]]
array([60, 80, 90])
-------------------------------------------------------------------
------------------------
Numpy Advanced Indexing and Slicing on 1D--Array
-------------------------------------------------------------------
------------
Syntax:- ndarryobj[ k ]
Examples:
-----------------
>>> a=np.array([100,200,300,400,500,600])
>>> print(a)-------------[100 200 300 400 500 600]
Example:
--------------
>>> print(a)
[100 200 300 400 500 600]
--------------
Way-1
--------------
>>> lst=[0,5]
>>> a[lst]
array([100, 600])
>>> a[ [0,5] ]
array([100, 600])
--------------------------
Way-2
--------------------------
>>> a[[True,False,False,False,False,True]]
array([100, 600])
>>> a[[True,False,False,True,False,True]]
array([100, 400, 600])
===================================================
3-D Arrays in Numpy
===================================================
=>We know that 1-D array Contains Some Sequence of elements in 1-
Direction / row
=>Example:- >>>a=np.array([10,20,30,40]
>>>print(a)---->array([10,20,30,40]---- 1-D Array
=>We know that 2-D array Contains data in the form of Rows and cols
=>2-D array contains combination of 1-D arrays.
Examples:
-------------------
>>> a=np.array([ [10,20,30],[40,50,60],[70,80,90]])
>>> a
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
>>> a.ndim--------------2
-------------------------------------------------------------------
---
=>3-D array contains combination of 2-D arrays with rows and
columns.
Examples:
----------------
>>>
a=np.array([[[10,20,30],[40,50,60],[70,80,90]],[[1,2,3],[4,5,6],[7,
8,9]]])
>>> a.ndim
3
>>> a.shape
(2, 3, 3)
>>> a
array([[[10, 20, 30],
[40, 50, 60],
[70, 80, 90]],
[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]]])
>>>
a=np.array([[[1,2,3,4],[5,6,7,8],[9,10,11,12]],[[13,14,15,16],[17,1
8,19,20],[21,22,23,24]] ] )
>>> a
array([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],
Examples:-
------------------
>>> a[ : , : , 0:1]
array([[[ 1],
[ 5],
[ 9]],
[[13],
[17],
[21]]])
>>> a[0:2, 0:3, :1]
array([[[ 1],
[ 5],
[ 9]],
[[13],
[17],
[21]]])
>>> a[:,0:2,1:3]
-------------------------------------------------------------------
-----------------
Advanced Indexing on 3-Darrays:
------------------------------------------------
Syntax:-
---------------
Example:
>>> a[[0,0,0],[1,0,1],[1,2,3]]
array([6, 3, 8])
>>> a[[0,1,1],[0,0,2],[0,1,3]]
array([ 1, 14, 24])
>>> a[ [0,0,0,1,1,1],[0,1,2,0,1,2],[2,1,0,2,1,0] ]
array([ 3, 6, 9, 15, 18, 21])
===================================================================
======================================================
Numpy--BroadCasting /Arithmetic Operations
======================================================
=>To perform Arithmetic Operations on numpy arrays, we use the
following functions.
1) add()
2) subtract()
3) multiply()
4) divide()
Syntax:-
------------
np.add(array1,array2)
np.subtract(array1,array2)
np.multiply(array1,array2)
np.divide(array1,array2)
=>Instead of using these functions, we cal also use all arithmetic
Operators of python.
Examples:
===================
>>> import numpy as np
>>> a=np.array([[10,20],[30,40]])
>>> b=np.array([[1,2],[3,4]])
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> print(a+b)
[[11 22]
[33 44]]
>>> print(a-b)
[[ 9 18]
[27 36]]
>>> print(a*b)
[[ 10 40]
[ 90 160]]
>>> print(b-a)
[[ -9 -18]
[-27 -36]]
>>> print(a/b)
[[10. 10.]
[10. 10.]]
>>> print(a//b)
[[10 10]
[10 10]]
>>> print(a%b)
[[0 0]
[0 0]]
>>> print(a**b)
[[ 10 400]
[ 27000 2560000]]
>>> np.add(a,b)
array([[11, 22],
[33, 44]])
>>> np.subtract(a,b)
array([[ 9, 18],
[27, 36]])
>>> np.multiply(a,b)
array([[ 10, 40],
[ 90, 160]])
>>> np.divide(a,b)
array([[10., 10.],
[10., 10.]])
================================================================
Examples : Arithmetic Operations with Different Dimensions
(BroadCasting)
>>> a=np.array([[10,20,30],[40,50,60]])
>>> a
array([[10, 20, 30],
[40, 50, 60]])
>>> b=np.array([2,5,6])
>>> b
array([2, 5, 6])
>>> a.ndim
2
>>> b.ndim
1
>>> print(a+b)
[[12 25 36]
[42 55 66]]
>>> print(a-b)
[[ 8 15 24]
[38 45 54]]
>>> print(a*b)
[[ 20 100 180]
[ 80 250 360]]
>>> print(a/b)
[[ 5. 4. 5.]
[20. 10. 10.]]
>>> print(a//b)
[[ 5 4 5]
[20 10 10]]
>>> print(a%b)
[[0 0 0]
[0 0 0]]
------------------------------------------------------------------
------------------------------------------------------------
>>> np.add(a,b)
array([[12, 25, 36],
[42, 55, 66]])
>>> np.subtract(a,b)
array([[ 8, 15, 24],
[38, 45, 54]])
>>> np.multiply(a,b)
array([[ 20, 100, 180],
[ 80, 250, 360]])
>>> np.divide(a,b)
array([[ 5., 4., 5.],
[20., 10., 10.]])
=================================================================
Numpy--Statical Functions
======================================================
=The most essential statical functions are
1) amax
2) amin
3)mean
4) median
5) variance
6) standard deviation
1) amax() and amin():
---------------------------------
=>These functions are used for finding max and min from given
array.
Syntax:-
np.amax(array)
np.amin(array)
np.mean(array, axis=0)
np.mean(array, axis=1)
Examples:
>>> b=np.array([[2,6],[4,8]])
>>> np.mean(b)
5.0
>>> np.mean(b,axis=0)
array([3., 7.])
>>> np.mean(b,axis=1)
array([4., 6.])
-------------------------------------------------------------------
------------------
3) median()
---------------------
=>This is used for finding median of the given array
Syntax:- np.median(array)
np.median(array, axis=0)
np.median(array, axis=1)
Examples:
>>> b=np.array([[2,6],[4,8]])
>>> np.median(b)
5.0
>>> np.median(b,axis=0)
array([3., 7.])
>>> np.median(b,axis=1)
array([4., 6.])
-------------------------------------------------------------------
--------
5) variance:
--------------------
=>used for finding variance of an array
Syntax:- np.var(array)
np.var(array, axis=0)
np.var(array, axis=1)
Examples:
-----------------
>>> b=np.array([[2,6],[4,8]])
>>> np.var(b)
5.0
>>> np.var(b,axis=0)
array([1., 1.])
>>> np.var(b,axis=1)
array([4., 4.])
----------------------------------------------------------
6) standard deviation
----------------------------------
=>used for finding standard deviation of an array
Syntax:- np.std(array)
np.std(array, axis=0)
np.std(array, axis=1)
Examples:
------------------------
>>> b=np.array([[2,6],[4,8]])
>>> np.std(b)
2.23606797749979
>>> np.std(b,axis=0)
array([1., 1.])
>>> np.std(b,axis=1)
array([2., 2.])
===================================================================
=
===================================
Introduction to PANDAS
===================================
=>PANDAS is an open Source Python Library(C+PYTHON lang)
=>PANDAS provides High Performnce for doing Data Analysis. In
otherwords PANDAS is one of the Data Analysis tool.
=>The word PANDAS is derived a word "PANel DAta
=>The PANDAS Module / Library developed by WES McKinney in the year
2008
=>Syntax:-
---------------
varname=pandas.Series(data, index,dtype)
Explanation:-
-------------------
=>here varname is an object of <class, 'pandas.core.series.Series'>
=>Data represents ndarray,list,constants
=>index represents rows . In otherwords Index value must be Unique
and they must be equal to number of values. By default index starts
from 0 to n-1. Programatically we can assign our own index names.
=>dtype represents data type (int32,int64, float32,float64...etc)
-------------------------------------------------------------------
----------------------------------------------
=>We have two types of Series. They are
a) empty series
b) non-empty series
a) empty series:
-----------------------------
=>An empty series does not contain any values.
Syntax / example: s=pd.Series()
print(s)-------------Series([], dtype:
float64)
-------------------------------------------------------------------
-----------------------
b)b) non-empty series:
---------------------------------
=>An non-empty series contains many values.
Syntax s=pd.Series(data)
===================================================================
Example: create a series for 10 20 30 40
--------------
>>s=pd.Series([10,20,30,40])
>>> print(s)
0 10
1 20
2 30
3 40
dtype: int64
-------------------------------------------------------------------
---
>>> s=pd.Series([10,20,30,40],dtype='float')
>>> print(s)
0 10.0
1 20.0
2 30.0
3 40.0
dtype: float64
-------------------------------------------------------------------
----
create a series object w.r.t nd array object.
-------------------------------------------------------------------
-----
>>> a=np.array([100,200,300,400])
>>> a
array([100, 200, 300, 400])
>>> s=pd.Series(a)
>>> print(s)
0 100
1 200
2 300
3 400
dtype: int32
-------------------------------------------------------------------
-------------
create a series object by using list object
--------------------------------------------------
>>> lst=[10,"KVR",23.45,True]
>>> s=pd.Series(lst)
>>> print(s)
0 10
1 KVR
2 23.45
3 True
dtype: object
>>> s=pd.Series([10,"KVR",23.45,True],dtype='object')
>>> print(s)
0 10
1 KVR
2 23.45
3 True
dtype: object
-------------------------------------------------------------------
------------------
The above examples, uses default index . ie. 0 t0 n-1 values
==============================================================
Creating a Series object with Programmer-defined Index
-------------------------------------------------------------------
-------------------------------------------
Examples:
---------------------------
>>>
s=pd.Series(["Ramu","Karan","DD","Rossum","Brucelee"],[100,101,102,
103,104])
>>> print(s)
100 Ramu
101 Karan
102 DD
103 Rossum
104 Brucelee
dtype: object
>>>
s=pd.Series(data=["Ramu","Karan","DD","Rossum","Brucelee"],index=[1
00,101,102,103,104])
>>> print(s)
100 Ramu
101 Karan
102 DD
103 Rossum
104 Brucelee
dtype: object
-------------------------------------------------------------------
--------------------------------------
>>> s=pd.Series(["Rama
Krishna","Raja","Rani"],["Father","Son","Daughter"])
>>> print(s)
Father Rama Krishna
Son Raja
Daughter Rani
dtype: object
===============================================================
=>Creating a Series from dict:
===============================================================
=>dict object organizes the data in the form of (key,value)
=>If we use dict object in a series() then keys of dict object can
be taken as Indices automatically and corresponding values of dict
can be takes data of the Series()
Example:
-----------------
>>> d1={100:"Rossum",101:"Gosling",200:"Ritche"}
>>> print(d1)
{100: 'Rossum', 101: 'Gosling', 200: 'Ritche'}
>>> s=pd.Series(d1)
>>> print(s)
100 Rossum
101 Gosling
200 Ritche
dtype: object
Example:
-----------------
>>> s=pd.Series(d1,[150,250,100,200])
>>> print(s)
150 NaN
250 NaN
100 Rossum
200 Ritche
dtype: object
-------------------------------------------------------------------
-------------------------------
>>> s=pd.Series(10)
>>> print(s)
0 10
dtype: int64
-------------------------------------------------------------------
------------------------------
>>> s=pd.Series(10,["Apple","Mango","Kiwi"])
>>> print(s)
Apple 10
Mango 10
Kiwi 10
dtype: int64
=======================================
Accessing the data from Series
=======================================
=>To access the data from Series object, we have two approaches.
They are
a) By using Position / Index
b) By using Label
----------------------------------------------------------------
a) By using Position / Index:
-------------------------------------------
Syntax:-
seriesobj[Index]
seriesobj[begin:end]
seriesobj[begin:end:step]
Examples:
---------------------
>>> s=pd.Series([1,2,3,4,5],['a','b','c','d','e'])
>>> print(s)
a 1
b 2
c 3
d 4
e 5
dtype: int64
>>> print(s[3])
4
>>> s=pd.Series([1,2,3,4,5],['a','b','c','d','e'])
>>> print(s)
a 1
b 2
c 3
d 4
e 5
dtype: int64
>>> print(s[0:3])
a 1
b 2
c 3
dtype: int64
>>> print(s[0:3:2])
a 1
c 3
dtype: int64
>>> print(s[::2])
a 1
c 3
e 5
dtype: int64
-------------------------------------------------------------------
------------------------------
2) By using Label:
---------------------------------
=>A series is a like a fiexed size dict object, in that we can set
and get values by index label.
Syntax:-
seriesobj['labelname'] ----------->getting the
value
Examples:
------------------
>>> s=pd.Series([1,2,3,4,5],['a','b','c','d','e'])
>>> s
a 1
b 2
c 3
d 4
e 5
dtype: int64
>>> print(s['a'])
1
>>> s['a']=100
>>> s
a 100
b 2
c 3
d 4
e 5
dtype: int64
>>> print(s['b'])
2
>>> print(s[['b','c','e']])
b 2
c 3
e 5
dtype: int64
========================================
DataFrame in PANDAS
========================================
=>A DataFrame is one of the Two dimensional Labelled Data Structure to
organize the data in the form rows and columns.
=>In Otherwords, DataFrame stores the data in the from Rows and columns.
Features of DataFrame:
----------------------------------
1) The column names of DataFrame can be different or same data type (int,
str,float..etc)
2) The size of DataFrame is mutable
3) DataFrame contains two axis(Row and Column)
Explanation:
-------------------
1) here varname reprsents an object of <class
'pandas.core.frame.DataFrame'>
2) DataFrame() is a function used for preparing Two-dimension Labelled
Data Structure.
3) data represents list ,dict,series,CSV file and ndarray
d) index represents row labels. By default row labels starts from 0 to
n-1. Programtically we can give our own row label names
e) columns represents Column Labels. By default column labels starts from
0 to n-1.Programtically we can give our own column label names
f) dtype represents data type of column names.
======================================================================
Example1: creating an empty data frame
------------------
>>>import pandas as pd
>>>df=pd.DataFrame()
>>> print(df)
Empty DataFrame
Columns: []
Index: []
--------------------------------------------------------------------------
----------------------------------
Example2: creating an non-empty data frame with list
------------------
>>>lst=[10,20,30,40,50]
>>>df=pd.DataFrame(lst)
>>>print(df)
0<-----Column
0 10
1 20
2 30
3 40
4 50
>>> df=pd.DataFrame(["apple","kiwi","mango","Guava"])
>>> print(df)
0
0 apple
1 kiwi
2 mango
3 Guava
>>> df=pd.DataFrame(d)
>>> print(df)
==================================================================
>>> studs={"Names":["Divya","Kushrga","Sharada","Sravanthi"],
... "sub1":["PYTHON","Java","Data Sc","AI"],
... "sub2":["Oracle","MYSQL","SQLITE3","DB2"]}
>>> print(studs)
{'Names': ['Divya', 'Kushrga', 'Sharada', 'Sravanthi'], 'sub1': ['PYTHON',
'Java', 'Data Sc', 'AI'], 'sub2': ["Oracle","MYSQL","SQLITE3","DB2"]}
>>> type(studs)
<class 'dict'>
>>> df=pd.DataFrame(studs,index=[100,101,102,103])
>>> print(df)
>>> print(df)
Names sub1 sub2
100 Divya PYTHON Oracle
101 Kushrga Java MYSQL
102 Sharada Data Sc SQLITE3
103 Sravanthi AI DB2
--------------------------------------------------------------------------
----------------------------------
crkt={"player names:" : pd.Series([........]),
"ages:" :pd.Series([.....]),
"rating" :pd.Series([.......]) }
df=pd.DataFrame(crkt)
----------------
Examples:
----------------
d ={'Player
Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack','Lee',
'David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3
.65])}
>>> df=pd.DataFrame(d)
>>> print(df)
Player Name Age Rating
0 Tom 25 4.23
1 James 26 3.24
2 Ricky 25 3.98
3 Vin 23 2.56
4 Steve 30 3.20
5 Smith 29 4.60
6 Jack 23 3.80
7 Lee 34 3.78
8 David 40 2.98
9 Gasper 30 4.80
10 Betina 51 4.10
11 Andres 46 3.65
--------------------------------------------------------------------------
--------------------------------------
>>> cart = {'Product': ['Mobile', 'AC', 'Laptop', 'TV', 'Football'],
... 'Type': ['Electronic', 'HomeAppliances', 'Electronic',
... 'HomeAppliances', 'Sports'],
... 'Price': [10000, 35000, 50000, 30000, 799]
... }
>>> type(cart)
<class 'dict'>
>>> df=pd.DataFrame(cart)
>>> print(df)
Product Type Price
0 Mobile Electronic 10000
1 AC HomeAppliances 35000
2 Laptop Electronic 50000
3 TV HomeAppliances 30000
4 Football Sports 799
--------------------------------------------------------------------------
-------------------------------
=>To select the data from DataFrame object we use
dataframeobject['column name']
>>> print(df['Product'])
0 Mobile
1 AC
2 Laptop
3 TV
4 Football
Name: Product, dtype: object
>>> print(df['Type'])
0 Electronic
1 HomeAppliances
2 Electronic
3 HomeAppliances
4 Sports
>>> print(df['Price'])
0 10000
1 35000
2 50000
3 30000
4 799
Name: Price, dtype: int64
--------------------------------------------------------------------------
--------------------
Querying the data from DataFrame object with loc()
--------------------------------------------------------------------------
--------------------
Syntax:- varname=dataframeobj.loc[dataframeobj['columnname'] cond
stmt]
--------------------------------------------------------------------------
--------------------
Examples:
--------------------------------------------------------------------------
-------------------
>>> data=df.loc[df['Price']>500]
>>> print(data)
Product Type Price
0 Mobile Electronic 10000
1 AC HomeAppliances 35000
2 Laptop Electronic 50000
3 TV HomeAppliances 30000
4 Football Sports 799
>>> data=df.loc[df['Price']<1000]
>>> print(data)
Product Type Price
4 Football Sports 799
>>> data=df.loc[df['Type']=='Electronic']
>>> print(data)
Product Type Price
0 Mobile Electronic 10000
2 Laptop Electronic 50000
Opening(Reading /writting) csv without pandas
1)READING
#readcsvdata.py
#in csv modulle reader()---> syntax:
result=csv.reader(filepointer)
import csv
with open("stud.csv") as csvrp:
records=csv.reader(csvrp)
for rec in records:
print(rec)
2)WRITTING
import csv
rec=[63, "viswa",66.66]
with open("G:\\KVR-PYTHON-4PM\\PANDAS\\stud.csv","a") as csvwp:
wpen=csv.writer(csvwp)
wpen.writerow(rec)
print("\nData written to the CSV File")
#pandascsv.py
import pandas as pd
recs=pd.read_csv("G:\\KVR-PYTHON-4PM\\PANDAS\\stud.csv")
print("The Data Available :\n",recs)