Python Ratan CompleteMaterial
Python Ratan CompleteMaterial
Ratan
Index page
1. python Introduction. 4-31
First application
Different ways to run the code
Different ways to format the data
Escape sequence characters
Keywords in python.
2. data types
String : str
int : int
float : float
Boolean : bool
3. python Operator. 32-39
Arithmetic operators
Relational operators
Bitwise operators
Logical operators
Assignment operators
Identity operators
Membership operators
4. Flow control statements. 40-51
If, If-else , elif
for , while
break, continue
5. python variables. 52-56
Local variables
Global variables
Non local variables
Global keyword
1|P ag e
Python Material Mr. Ratan
2|P ag e
Python Material Mr. Ratan
3|P ag e
Python Material Mr. Ratan
History of Python
Python is a fairly old language created by Guido Van Rossum. The design began in the late 1980s
and was first released in February 1991.
4|P ag e
Python Material Mr. Ratan
Python Day-1
1. other languages more about the coding less about analysis (when compare to python).
python less about coding more about the analysis.
Note: python is simple but need analysis.
To check the popularity of python programming language use below command.
http://pypl.github.io/PYPL.html
Editors
Edit plus
notepad++
subline text
vs editor
Note books
Jupyter
Tools
Anaconda
5|P ag e
Python Material Mr. Ratan
python:
we can develop internet application(client-server)
platform independent language
python : function based : we can declare the functions we can write the code
Object based : deals with classes & objects
script based : directly write code
1. directly write the code
num1 = 10
num2 = 20
result = num1 + num2
print(result)
2. write the code with funtions
def wish():
print("Good Morning")
wish()
Note: Programming languages give instruction to computers then computer will do some action.
without programming languages computer unable to do any task.
6|P ag e
Python Material Mr. Ratan
python Day-2
And changing 2.x to 3.x means checking every line of code do the modification which is not
recommended and not possible.
5. Different versions
python initial version : python 1.0
First appeared : 1990
Python 3.0, released in 2008,
The Python 2 language, i.e. Python 2.7.x, was officially discontinued on 1 January 2020
Stable release 3.8.2 / 24 February 2020
7|P ag e
Python Material Mr. Ratan
8|P ag e
Python Material Mr. Ratan
In other languages: byte short int long float double char Boolean(Type declaration mandatory)
int eid=111;
String ename="ratan";
float esal=100000.34;
9|P ag e
Python Material Mr. Ratan
Once we develop the application by using any one operating system(windows) that application runs
on in all operating system is called platform independency.
ex : python
10 | P a g e
Python Material Mr. Ratan
Features of python:
Easy to Use
o It is a programmer friendly; it contains syntaxes just like English commands.
o Uses an elegant syntax, making the programs you write easier to read.
High Level Language
o Python is a clear and powerful object-oriented programming language, comparable
to Perl, Ruby, Scheme, or Java.
Expressive Language
o The code is easily understandable.
Interpreted
o The execution done in line by line format.
Platform Independent
o We can run this python code in all operating systems.
Open Source
o Python is free of cost, source code also available.
Object-Oriented language
o Python supports object-oriented programming with classes and multiple inheritance
Huge Standard Library
o Code can be grouped into modules and packages.
GUI Programming
o Graphical user interfaces can be developed using Python.
Integrated
o It can be easily integrated with languages like C, C++, JAVA etc.
Extensible
o Is easily extended by adding new modules implemented in a compiled language such
as C or C++.
11 | P a g e
Python Material Mr. Ratan
12 | P a g e
Python Material Mr. Ratan
13 | P a g e
Python Material Mr. Ratan
14 | P a g e
Python Material Mr. Ratan
Just click on python.exe file w e will get command prompt shown below start the programming.
15 | P a g e
Python Material Mr. Ratan
Approach 4: write the application by using editplus, run the application by using command prompt.
Step 1: Write the application in editor (notepad,editplus…etc) run from the command prompt.
Write the application in editor then save the application .py extension.
Approach-6 : We can develop the application by using IDE like PyCharm (jet brains).
16 | P a g e
Python Material Mr. Ratan
E:\python12pm>python first.py
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
17 | P a g e
Python Material Mr. Ratan
num1 = 2.7
num2 = 4.4
num3 = 3.2
res=num1+num2+num3
print(res)
num1,num2,num3 = 2.7,4.4,3.2
res=num1+num2+num3
print(res)
eid,ename,esal = 111,"ratan",10000.45
print(eid)
print(ename)
print(esal)
ex-4: take three int values: print the addition: but taking same values: 10 10 10
num1,num2,num3=10,10,10
res=num1+num2+num3
print(res)
num1=num2=num3=10
res=num1+num2+num3
print(res)
18 | P a g e
Python Material Mr. Ratan
other languages:
for
{
for
{
for
{
if()
{
}
}
}
}
python code:
for x in rane():
sfs
dfgdfg
for x in range:
sfskdf
sdfdsfdsf
if (con):
sfsdf
sdfdsf
sfsddf
for x in range()
sdfsdf
sddfsdfdsf
dsfsdfsdf
Note : other languages we have the brasses, but in python no brasses everything is alignment. So, give
the spaces properly.
19 | P a g e
Python Material Mr. Ratan
ex 6:
#swapping the variables
x,y = 100,200
x,y = y,x
print(x,y)
# deleting var
val = 10
print(val)
del val
print(val) NameError: name 'val' is not defined
ex 7:
#reassiging variables
num = 10
print(num)
num = 100
print(num)
id() is
int is immutable we can not so the modifications
The Garbage collector will collect the data : this is automatic memory management.
immutable means we can ot change the data so we can share the common data.
ex-8:
Note: in python no default values concept once we declare the variables must assign the data.
But some cases if we do not have the data initially assign the data with None later initialize your values.
case 1: Invalid
val
print(val)
case 2: initially we can assign None later we can assign the data.
val = None
print(val)
val = "ratan"
print(val)
Assignment :
1. what is the sizes & ranges of the data types.
Ans:
import sys
val1,val2,val3,val4 = 10,10.5,"",True
print(sys.getsizeof(val1))
print(sys.getsizeof(val2))
print(sys.getsizeof(val3))
print(sys.getsizeof(val4))
20 | P a g e
Python Material Mr. Ratan
Python Comments:
Comments are used to write description about application logics to understand the logics easily.
The main objective comments the code maintenance will become easy.
The comments are non-executable code.
1. Single line comments : write the description in single line & it starts with #
Syntax: # statement
2. Multiline comments:
write the description in more than one line starts with “”” ends with : “”””(triple quotes)
in python while writing the comments we can write double quote or single quote (“) or (‘)
x = 35455443535
print(type(x))
x = 4353453453453453534536546546464565464564564545
print(type(x))
$python main.py
<type 'int'>
<type 'long'>
$python main.py
<class 'int'>
<class 'int'>
21 | P a g e
Python Material Mr. Ratan
print(eid,ename,esal)
print("Emp id=",eid)
print("Emp name=",ename)
print("Emp sal=",esal)
eid,ename,esal = 111,"ratan",10000.45
print("Emp id=%d Emp name=%s Emp sal=%f"%(eid,ename,esal))
eid,ename,esal = 111,"ratan",10000.45
print(f"Emp id={eid} \nEmp name={ename} \nEmp sal={esal}")
22 | P a g e
Python Material Mr. Ratan
eid,ename,esal = 111,"ratan",10000.45
print(eid,"***",ename,"***",esal)
print(eid,ename,esal,sep=" ")
print(eid,ename,esal,sep="***")
print(eid,ename,esal,sep="&&&")
print(eid,ename,esal,sep="$$$")
E:\python12pm>python first.py
Enter a num1: 10 10.5 ratan
Enter a num2: 20 20.6 anu
1020 10.520.6 ratananu
E:\python12pm>python first.py
Enter a num1:10
Enter a num2:20
30
E:\python12pm>python first.py
Enter a num1:ratan
ValueError: invalid literal for int() with base 10: 'ratan'
23 | P a g e
Python Material Mr. Ratan
print(10+20)
print(10.6+20.2)
print(True+True)
print("ratan"+"anu")
print(10+10.5)
print(10+10.5+True)
print(10+False+False)
Errors :
IndentationError : if the alignment is not correct
NameError : i am trying to get the data it is not available.
ValueError : if the type conversion is not possible we will get ValueError.
TypeError : if we are tying to combine different type of data.
Assignment-1: what is the difference between %f & %g while printing float data.
%g : before or after decimal it will take only 6 digits
%f : before or after decimal it will take only 16 or 17 digits
val1 = 3.345345
print("value=%g"%(val1))
val2 = 434654654653.34343434
print("value=%f"%(val2))
Assignment-2 :
Take the name & three marks[maths,science,social] from end user print the message in below
format.
output : hi ratan your total marks 230 and youe percentage is 89.4%
24 | P a g e
Python Material Mr. Ratan
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for',
'from', 'global','if', 'import', 'in','is', 'lambda', 'not', 'or', 'pass', 'print','raise', 'return', 'try',
'while','with', 'yield']
In python 2.7 prints is a keyword to print the data, so parenthesis not required
print "Ratan World"
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is','lambda', 'nonlocal', 'not', 'or', 'pass',
'raise', 'return', 'try', 'while', 'with', 'yield']
In python 3.x print is not a keyword it is a function used to print the data so parenthesis mandatory.
print ("Ratan World")
25 | P a g e
Python Material Mr. Ratan
E:\>python first.py
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', 'iskeyword', 'kwlist', 'main']
The functions starts with two underscores & ends with two underscores is called: Magic function
before magic functions are called: classes
after the magic functions are called: function, variables.
E:\>python first.py
['ABC', 'ABCMeta', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', '_abc_init', '_abc_instancecheck', '_abc_register', '_abc_subclasscheck',
'_get_dump', '_reset_caches', '_reset_registry', 'abstractclassmethod', 'abstractmethod',
'abstractproperty', 'abstractstaticmethod', 'get_cache_token']
The functions starts with two underscores & ends with two underscores is called : Magic function
before magic functions are called : classes
after the magic functions are called : function, variables.
26 | P a g e
Python Material Mr. Ratan
Identifiers in python:
Any name in python like function-name, class-name, variable-name…etc is called
identifier. The identifier must obey fallowing rules.
The identifier contains a-z , A-Z, 0-9, _ but should not start with numeric’s & does
not allows special symbols.
class MyClass123: valid
class 123MyClass: invalid
class MyClass_123: valid
class _MyClass: valid
Is it possible to use predefined class-name & data types names as a identifier but not
recommended. (here ABC is predefined abstract class)
class ABC:
def m1(self):
print("possile")
ABC().m1()
27 | P a g e
Python Material Mr. Ratan
Binary form (Base-2): The allowed digits are: 0 & 1, value should be prefixed with 0b or 0B
b1 = 0b1010 output:
print(b1) E:\>python first.py
b2 = 0B1111 10
print(b2) 15
Octal Form(Base-8): The allowed digits are : 0 to 7 Literal value should be prefixed with 0o or 0O.
d1 = 0o123 output:
print(d1) E:\>python first.py
d2 = 0O111 83
print(d2) 73
Decimal form(base-10): It is the default number system in Python The allowed digits are: 0 to 9
val = 123
print(val)
Hexadecimal System: check the above octal diagram to get the calculations. Just replace 8 with 16.
Hexadecimal is base 16 number system[0-9 a-f]. prefixed with 0x or 0X.
d1 = 0x123 output:
print(d1) E:\>python first.py
d2 = 0X111 291
print(d2) 273
d3 = 0X1af 431
print(d3)
28 | P a g e
Python Material Mr. Ratan
ex:
a,b,c,d = 0b11,0o11,11,0x11 output:
print(a,b,c,d) E:\>python first.py
i,j,k,l = 0b101,0o101,101,0x101 3 9 11 17
print(i,j,k,l) 5 65 101 257
ex: code values in python: a = 97 A = 65 1 = 49. To check the code value use ord() function
print(ord('a'))
print(ord('b'))
print(ord('A'))
print(ord('B'))
print(ord('1'))
print(ord('2'))
ex: To get the character based on the value use chr()
print(chr(100))
print(chr(68))
print(chr(52))
29 | P a g e
Python Material Mr. Ratan
ex-2 : in python 2.7:Taking data from end-user by using raw_input() it takes data only in String format.
We entered 10 to raw_input : it will take string format.
We entered 12.32 to raw_input : it will take string format.
We entered “ratan” to raw_input : it will takes string format data.
30 | P a g e
Python Material Mr. Ratan
ex: Taking data from user by using raw_input() in the form of String then converting after taking data .
num1 = raw_input("Enter first Number :")
num2 = raw_input("Enter Second Number :")
add= float(num1)+int(num2)
print "addition=",add
output :
E:\>python first.py E:\>python first.py
Enter first Number :10 Enter first Number :20.3
Enter Second Number :20 Enter Second Number :10
addition= 30.0 addition= 30.3
E:\>python first.py
Enter first Number: ratan
Enter Second Number :10
ValueError: could not convert string to float: ratta
31 | P a g e
Python Material Mr. Ratan
Python operators
x,y= 15,4
print(x+y)
print(x-y)
print(x*y)
print(x/y) # division by default gives float value: 3.75
print(x%y)
print(x//y) # floor division it will give int value: 3
print(x**y) # power value
print(2**3)
32 | P a g e
Python Material Mr. Ratan
33 | P a g e
Python Material Mr. Ratan
print(3&7) print(15&15)
0011 1111
0111 1111
0011 1111
print(9&6) print(0&0)
1001 0000
0110 0000
0000 0000
print(3|7) print(15|15)
0011 1111
0111 1111
0111 1111
print(9|6) print(0|0)
1001 0000
0101 0000
1111 0000
34 | P a g e
Python Material Mr. Ratan
cond1 & cond2 : it will check the both conditions then only it will give result.
cond1 and cond2 : Here the second condition execution depends on first condition
if the first condition is true then only second condition executed.
if the first condition is false then second condition not executed.
case 1: in below example it will check both conditions here second condition will give TypeError.
if (10>20) & ("anu"+10=="anu"):
print("Good morning")
else:
print("Good Night")
case 2: below example first condition is false so second condition not executed. We will get output.
if (10>20) and ("anu"+10=="anu"):
print("Good morning")
else:
print("Good Night")
observations:
& : for the conditions parenthesis required
if (username=="ratan") & (password=="anu"):
35 | P a g e
Python Material Mr. Ratan
cond1 | cond2 : it will check the two conditions then only it will give result.
cond1 or cond2 : Here the second condition execution depends on first condition
if the first condition is false then only second condition executed.
if the first condition is true then second condition not executed.
case 1: in below example it will check both conditions so second condition gives TypeError.
if (10<20) | (10+"ratan"=="ratan"):
print("Good morning")
else:
print("Good Evening")
case 2: below example first condition is true Then second condition not executed
in above example we will get the output because the second condition is not executing.
if 10<20 or 10+"ratan"=="ratan":
print("Good morning")
else:
print("Good Evening")
Note: and : all the conditions are true then only true.
or : at least one condition is true it return true.
Ans-1 : ratan
Ans-2 : ratan
36 | P a g e
Python Material Mr. Ratan
Assignment operator :
Assignment operators:
normal assignment : =
Augmented Assignment : *=, += ,-= ,/= , %=
# Augmented assignment
val += 10 # val = val + 10
val -= 4 # val = val -4
val /= 2 # val = val / 2
val %= 2 # val = val %2
print(val)
Membership operators:
in: "in" operator return true if a character or the entire substring is present in the
specified string, otherwise false.
not in: "not in" operator return true if a character or entire substring does not exist in
the specified string, otherwise false.
37 | P a g e
Python Material Mr. Ratan
Identity operators
d1 = [10,20,30]
d2 = [40,50,60]
d3 = d1 # d3 pointing to d1
print(id(d1))
print(id(d2))
print(id(d3))
print(id(d4))
#memory comparison: is, is not
print(d1 is d2)
print(d1 is d3)
print(d1 is not d2)
print(d1 is not d3)
38 | P a g e
Python Material Mr. Ratan
ex-1: Assignment.
Take the username & password from enduser
check username=="ratan" password=="anu": Login Success or Fail
ex-2: Assignment
eid , ename , esal ,company : takes the data from end user
either esal>10000 or comapny=="tcs" : then it returns true otherwise false.
39 | P a g e
Python Material Mr. Ratan
if statement: Takes only one option. (if the condition is then only it will execute)
if(condition):
statement(s)
statement (s)
ex:
x,y = 62,22
if (x > y):
print("Hi students Good Morning")
Syntax: if(condition):
statement(s)
else:
statement(s)
case 1: Normal condition.
if 10>20:
print("Good Morning")
print("Hi Students")
else:
print("Good Evening")
print("HI ratan sir")
40 | P a g e
Python Material Mr. Ratan
case 3: In python Boolean constants start with uppercase character. (True, False)
if True:
print("true body")
else:
print("false body")
case 4: If we pass the condition other than true or false it will take as a True.
if "ratan":
print("Good morning")
else:
print("Good Evening")
Assignments
1. Take the year from end-user check leap year or not.
2. Take the two numbers from end user print the bigger number.
3. Take the number from end user print that is even or odd.
4. Take the number from end user check it is positive or negative.
if it is positive : print it is even or odd
if it is negative : print it is even or odd
for this example, use nested if-else.
sample output : enter a num : 4
this is positive & even
enter a num : -3
this is negative & odd
41 | P a g e
Python Material Mr. Ratan
Assignments
2 : Take the number from end user print that is even or odd
num = int(input("enter a number:"))
if num%2==0:
print("number is even")
else:
print("number is odd")
3: Take the two numbers from end user print the bigger number.
# check the biggest of two numbers
num1 = int(input("enter first number:"))
num2 = int(input("enter second number:"))
if(num1>num2):
print("num1 is Bigger")
print("feeling important")
else:
print("num2 is Biffer")
print("feeling very important")
42 | P a g e
Python Material Mr. Ratan
elif statement :
The keyword ‘elif’ is short for ‘else if’
An elif sequence is a substitute for the switch or case statements found in other languages
Syntax:
if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)
case 1: a=200
if a==10:
print("ratan")
elif a==20:
print("anu")
elif a==30:
print("naresh")
else:
print("sravya")
43 | P a g e
Python Material Mr. Ratan
for loop :
Loops are used to execute same data repeatedly.
Loops are used to print the data n number of times based on conation.
If you do need to iterate over a sequence of numbers, use the built-in function range().
range() function :
case 1:
for x in range(10):
print("hi ratan sir...",x)
for x in range(2,7):
print("hi students...",x)
for x in range(2,8,2):
print("hi anu madam....",x)
case 2:
#printing the even values from 1-20
for x in range(1,21):
if x%2==0:
print(x)
44 | P a g e
Python Material Mr. Ratan
for x in range(10):
print(x)
for x in range(10):
print(x,end=" ")
Case 6:
#the loop is repeated with every character
for x in "ratan":
print(x)
45 | P a g e
Python Material Mr. Ratan
Assignments
4. take the name from end user print the addition of all code values.
name = input("Enter your name :")
sum = 0
for x in name:
sum += ord(x)
print("Sum of all code values:",sum)
46 | P a g e
Python Material Mr. Ratan
range(low_value,high_value)
range(2,9)
increament is automatically done by +1
range(low_value,high_value,inc_value)
range(2,7,2)
here increament is done by +2
range(high_value,low_value,dec_value)
range(7,2,-3)
Note : in range() the increament automatically done by +1 but decreament we have to do.
for x in range(2,8,2):
print("Good Morning...",x)
for x in range(7,2,-2):
print("Good Evening...",x)
for x in range(-10,-5,3):
print("ratanit:",x)
for x in range(-5,-10,-2):
print("ratanit:",x)
47 | P a g e
Python Material Mr. Ratan
Along with the for loop possible to take the else block. The else executed when for loop
terminated normally.
for i in range(1, 5):
print(i)
else:
print('The for loop is over')
case 1: if the exception raised in for loop else block not executed.
for x in range(10):
print("ratan world",x)
print(10/0)
else:
print("else block")
case 2: In loop when we use break statement the else block not executed.
for x in range(10):
print("ratan sir",x)
if(x==4):
break
else:
print("else block")
case 3: when we use os._exit(0) the virtual machine shutdown, the else block not executed.
import os
for x in range(6):
print("ratanit:",x)
os._exit(0)
else:
print("else block")
48 | P a g e
Python Material Mr. Ratan
While loop:
while <expression>:
Body
Case 1: printing the data 10 times using for & while loop.
#for loop printing 10-times.
for x in range(10):
print("Good morning")
#while loop printing 10 times.
i=0
while i<10:
print("Good morning")
i += 1
case 2: Assignment
guss = 25
while True:
userguss = int(input("Enter guss value:"))
if userguss==guss:
print("Congrations.......gift")
break
elif userguss>guss:
print("Your value is greater than guss value")
else:
print("Your value is less than guss value")
Note : if u know how many times to repeat use for loop.
if u don't know how many times to repeat use while loop.
Case 3: Assignment
Take the eid,ename,esal from end user print the data using all formats.
after printing give the message do you want one more record (yes/no)
yes : again take the data print the data no : stop the loop
Ans:
while True:
eid = int(input("Enter emp id:"))
ename = input("enter emp name:")
esal = float(input("Enter emp sal:"))
print(f"Emp id={eid} Emp name={ename} Emp sal={esal}")
print("Emp id={0} Emp name={1} Emp sal={2}".format(eid,ename,esal))
print("Emp id=%d Emp name=%s Emp sal=%g"%(eid,ename,esal))
option = input("Do you want one more record(yes/no)")
if option == "no":
break
elif option == "yes":
continue
else:
print("your option is invalid")
break
49 | P a g e
Python Material Mr. Ratan
case 1: if the exception raised in while loop else block not executed.
while True:
print(10/0)
else:
print("while loop terminated normally...")
case 2: In loop when we use break statement the else block not executed.
a=0
while(a<10):
a=a+1
if(a==3):
break
print("RATANIT:",a)
else:
print("else block")
case 3: when we use os._exit(0) the virtual machine shutdown, the else block not executed.
import os
while(True):
print("RATANIT:")
os._exit(0)
else:
print("else block")
50 | P a g e
Python Material Mr. Ratan
Pass statement:
Pass is an empty statement in python.
The pass statement does nothing. It can be used when a statement is required syntactically
but the program requires no action.
If you want declare the function without implementation, but you want provide the
implementation in future use pass statement.
o Declaring function without implementation use pass.
o Declaring if without statements use pass.
o Declaring class without body use pass......etc
while True:
pass
class MyEmptyClass:
pass
def disp1():
pass
if 34>23:
pass
51 | P a g e
Python Material Mr. Ratan
Variables are used to store the data, by using that data we will achieve project requirement.
A variable is nothing but a reserved memory location to store values.
Every variable must have some type i.e.,
o Int, float Boolean
o String
o List
o Tuple
o Dictionary…. etc.
Functions in Python:
function used to write the block of python code.
Functions help break our program into smaller and modular chunks.
Declare the function using def keyword.
The code is usually well organized, easy to maintain, and developer-friendly.
A function can have different types of arguments & return value.
main objective of function is reusing the code.(by calling the function wherever we want)
52 | P a g e
Python Material Mr. Ratan
ex-1: First function without arguments & second function with argument.
def sayHello():
print("HI Good morning")
print("How are you")
def wish(name):
print("Good Evening...",name)
#function calling
sayHello()
wish("ratan")
def wish():
name = "ratan"
print("Good morning...",name)
def add(num1,num2):
print(num1 +num2)
#function call
wish()
add(10,20)
def wish2():
print("Good Evening....",name)
#function calling
wish1()
wish2()
53 | P a g e
Python Material Mr. Ratan
def wish():
happyBirthday('ratan')
happyBirthday('anu')
wish()
#function call
call student_info
call teacher_info
54 | P a g e
Python Material Mr. Ratan
ex-1:
case 1: It is possible to declare the global variable inside the function by using global keyword.
def wish():
global name
name = 'ratan'
print(name)
#function calling
wish()
print(name)
#access func
wish()
print(name)
case 3: Inside the function to represent or change the global variables: use global keyword
name = "sravya"
def wish():
global name
name = 'ratan' # it is global data changing
print(name)
#function calling
wish()
print(name)
55 | P a g e
Python Material Mr. Ratan
#function calling
print ('global : ',a)
f()
print ('global : ',a)
g()
print ('global : ',a)
h()
print ('global : ',a)
56 | P a g e
Python Material Mr. Ratan
#function call
res1 = func1()
print("Return value of func1:",res1)
res2 = func2()
print("Return value of func2:",res2)
a,b,c,d = func2()
print("Return value of func2:",a,b,c,d)
x,y,*z = func2()
print("Return value of func2:",x,y,z)
res3 = func3()
print("Return value of func3:",res3)
res4 = func4()
print("Return value of func4:",res4)
Note:
func1 : The function can return any type of data.
func2 : The Function can return multiple values.
func3 : The default return value of the function is None.
func4 : when we declare empty return by default it returns None.
Holding the return value is optional but it is recommended.
57 | P a g e
Python Material Mr. Ratan
print(disp())
ex 3:
case 1:
inside the function only one return statement allowed.
if we declared multiple return statements after first return the data will be ignored.
def wish():
print("hi sir Good Morning")
return 10
print("hi sir Good Evening")
return 20
return 30
#function calling
res = wish()
print(res)
case 2: here we are writing return in if-else statement but only one return will be executed.
def wish():
if 10>20:
return 10
else:
return 20
#function calling
res = wish()
print(res)
ex 5: Assignment: write the output of the below example.
a_var,b_var,e_var,d_var = 10,15,25,100
def my_func(a_var):
print("in a_func a_var =", a_var)
b_var = 100 + a_var
d_var = 2 * a_var
print(b_var, d_var, e_var)
return b_var + 10
c_var = my_func(b_var)
print(a_var, b_var, c_var, d_var)
58 | P a g e
Python Material Mr. Ratan
def hello():
print('Hello!')
def print_welcome(name):
print('Welcome,', name)
def positive_input(prompt):
number = float(input(prompt))
while number <= 0:
print('Must be a positive number')
number = float(input(prompt))
return number
E:\>python first.py
Your Name: ratan
Hello!
Welcome, ratan
To find the area of a rectangle, enter the width and height below.
Width: 5
Height: 4
Width = 5.0 Height = 4.0 so Area = 20.0
59 | P a g e
Python Material Mr. Ratan
Function arguments:
Every function can take the arguments & we can pass the arguments in four different ways.
i. default arguments
ii. required arguments.
iii. keyword arguments.
iv. variable arguments
ex-1 : default arguments : if we are not assigning any data by default it will take default values.
def emp_details(eid=111,ename="ratan",esal=10000.45):
print(f"Emp id={eid} \nEmp name={ename} \nEmp sal={esal}")
emp_details()
emp_details(222)
emp_details(333,"anu")
emp_details(444,"sravya",30000.45)
ex 2: required arguments: if the function expecting arguments must pass the values.
def emp_details(eid,ename,esal):
print(f"Emp id={eid} \nEmp name={ename} \nEmp sal={esal}")
emp_details(111,"ratan",10000.45)
emp_details(111)
emp_details(222,"anu")
emp_details(333,"sravya",20000.45)
in above example eid is required argument & ename, esal are default arguments.
Note : in function declaration once the default argument is started next all arguments must be
default arguments.
def add(num1,num2,num3=10): valid
def add(num1,num2=5,num3=10): valid
def add(num1=3,num2=5,num3=20): valid
60 | P a g e
Python Material Mr. Ratan
ex-4: If the function excepting arguments means we can pass any type of data.
Case1 : while calling the function we can pass the different types of data.
def add(mum1,num2):
print(num1 + num2)
add(10,20)
add(10.5,20.4)
add("ratan","anu")
add(10,10.5)
add("ratan",10)
def addition(x,y):
print x+y
emp_details(eid=111,ename="ratan",esal=10000.45)
emp_details(ename="ratan",eid=111,esal=10000.45)
The keywords are mentioned during the function call along with their corresponding
values. These keywords are mapped with the function arguments so the function can easily
identify the corresponding values even if the order is not maintained during the function call.
Note: In function call once the keyword argument is started next all arguments must be keyword
arguments.
emp_details(111,ename="ratan",esal=10000.45) : valid
emp_details(111,"ratan",esal=10000.45) : valid
emp_details(111,ename="ratan",10000.45) : invalid
emp_details(eid=111,"ratan",10000.45) : invalid
61 | P a g e
Python Material Mr. Ratan
ex-6 : variable arguments: can take 0 or more values & any type of value.
case 1:
def disp(*var):
print(var)
for x in var:
print(x)
#fnction call
disp()
disp(10)
disp(10,20)
disp(10,10.4,"ratan")
#fnction call
disp(10,20)
disp(10.6,10.5)
disp(10,10.5,True)
disp(10,"ratan")TypeError: unsupported operand type(s) for +: 'int' and 'str'
case 3: along with the variable arguments it is possible to take normal arguments.
def disp(val1,*var):
print(val,"-----",var)
#fnction call
disp(10,10.5,True)
disp(10,20,30)
disp("ratan")
case 4: if the normal argument is last argument then pass the data using keyword type.
def disp(*var,val):
print(var,"-----",val)
#fnction call
disp(10,10.5,val=True)
disp(10,20,val=30)
disp(val="ratan")
62 | P a g e
Python Material Mr. Ratan
print(sum(kwarg.values()))
#fnction call
disp(10,20,30,a=10,b=20,c=30)
63 | P a g e
Python Material Mr. Ratan
ex 3: Inner function variable & outer function variable: just check the output.
def outer():
name = "ratan"
def inner():
name = "sravya"
print(name)
64 | P a g e
Python Material Mr. Ratan
ex 4: nonlocal keyword
inside the inner function to represent (or change) outer function variable use
nonlocal keyword.
def outer():
name = "ratan"
def inner():
nonlocal name
name = "sravya"
print(name)
print(name)
inner2()
inner1()
print(name)
#function call
outer()
65 | P a g e
Python Material Mr. Ratan
outer()
print(s)
print(x)
inner()
print(x)
outer()
print(y)
66 | P a g e
Python Material Mr. Ratan
ex-9:
case 1: valid & recommended
def my_func():
print("hi students")
print("sat exam")
my_func()
my_func()
def my_func():
"""
Author : Ratan
team size : 10
vendor : nareshit
"""
pass
print(my_func.__doc__)
67 | P a g e
Python Material Mr. Ratan
print(float(10.4))
print(float(10))
print(float(False))
print(float("10.4"))
#print(float("10")) valueError
#print(float("ratan")) ValueError:
# for the bool if we pass other than true false we will get True
print(bool(0))
print(bool(1))
print(bool(True))
print(bool(False))
print(bool("True"))
print(bool("False"))
print(bool(10))
print(bool(10.5))
print(bool("ratan"))
print(str("ratan"))
print(str(10)+str(10))
print(str(10.5)+str(10.3))
print(str(True)+str(False))
print(int(float(str(bool("ratan")))))
print(str(float(int(bool("ratan")))))
print(int(bool(str(float(10)))))
68 | P a g e
Python Material Mr. Ratan
variable PEP8:
#not recommended
x = "addanki ratan"
i,j = x.split()
print(i,j)
# Recommended
name = 'addanki ratan'
first_name, last_name = name.split()
print(last_name, first_name)
https://www.jetbrains.com/pycharm/download/
69 | P a g e
Python Material Mr. Ratan
Functions PEP8:
# Not recommended
def db(x):
return x * 2
y = db(2)
print(y)
# Recommended
def multiply_by_two(num):
return num * 2
result = multiply_by_two(20)
print(result)
keyword pep:
After keyword only one space allowed if we will give more than one space will get
PEP8:multipe spaces after keyword.
def my_func1():
class MyClass:
all keywords names shoud be lower case.
Comments PEP-8:
a. Limit the line length of comments and docstrings to 72 characters.
b. Use complete sentences, starting with a capital letter.
c. Make sure to update comments if you change your code.
d. after # give one white space
colan(:) PEP-8
after colan one whitespace required.
d1 = {111: "Good", 222: "anu"}
print(d1)
70 | P a g e
Python Material Mr. Ratan
import PEP8:
# Valid Not Recommended
import time,keyword # PEP8 : multiple imports on one line
camelCase: stats with upper & inner words start with upper.
line space:
line data break it is recommended to take 79 characters.
“Attend the classes Regularly then you will get the clarity on subject”
71 | P a g e
Python Material Mr. Ratan
72 | P a g e
Python Material Mr. Ratan
Numbers
Int / float/complex : type
Describes the numeric value & decimal value
These are immutable modifications are not allowed.
Boolean
bool : type
represent True/False values.
0 =False & 1 =True
Logical operators and or not return value is Boolean
Strings
str : type
Represent group of characters
Declared with in single or double or triple quotes
It is immutable modifications are not allowed.
Lists
list : type
group of heterogeneous objects in sequence.
This is mutable modifications are allowed
Declared with in the square brackets [ ]
Tuples
tuple : type
group of heterogeneous objects in sequence
this is immutable modifications are not allowed.
Declared within the parenthesis ( )
Sets
set : type
group of heterogeneous objects in unordered
this is mutable modifications are allowed
declared within brasses { }
Dictionaries
dict : type
it stores the data in key value pairs format.
Keys must be unique & value
It is mutable modifications are allowed.
Declared within the curly brasses {key:value}
73 | P a g e
Python Material Mr. Ratan
74 | P a g e
Python Material Mr. Ratan
str:
string is to take sequence of characters represented in the quotation marks.
we can declare the string in in double or single or triple quotes.
string support both positive indexing & negative indexing.
string immutable data so modifications are not allowed.
The type of the string data is: str & to check the type of the data use type () function.
ex 1: string declarations: we can declare the string in in double or single or triple quotes.
str1 = "ratan"
print(str1)
str2 = 'ratan'
print(str2)
str3 = """ratan"""
print(str3)
ex 2: possible to take the string data using single & double or triple quotes.
If the string is starts & ends with double quotes then middle of the string possible to take the
single quotes.
If the string is starts & ends with single quotes then middle of the string possible to take the
double quotes.
If the string is starts & ends with triple quotes then middle of the string possible to take the
single & double quotes.
75 | P a g e
Python Material Mr. Ratan
76 | P a g e
Python Material Mr. Ratan
name = "nareshit"
#0123456
print(name[0])
print(name[2:4])
print(name[:4])
print(name[2:])
print(name[:])
print(name[2:4:2])
print(name[:4:2])
print(name[2::2])
print(name[::2])
print(name[4:2:-2])
print(name[:2:-2])
print(name[4::-2])
print(name[::-2])
print(name[::-1])
#in slicing the data available it will print otherwise it will ignore without error
print(msg[2:12:2])
print(msg[9:14:2])
Note: In slicing the data not available just it will ignore the data.
But when we print the single value, if the data not available we will get IndexError.
77 | P a g e
Python Material Mr. Ratan
print(name[0])
print(name[-1])
print(name[-7:-2])
print(name[:-2])
print(name[-7:])
print(name[:])
print(name[-7:-2:2])
print(name[:-2:2])
print(name[-7::2])
print(name[-2:-7:-3])
print(name[:-7:-3])
print(name[-2::-3])
print(name[::-3])
print(name[2:-2])
print(name[-3:3:-1])
print(name[2:-2:2])
for x in name:
if x=='a':
break
print(x,end="")
print()
for x in name:
if x=='a':
continue
print(x,end="")
78 | P a g e
Python Material Mr. Ratan
Ex-10: Concatenation: combining two different string then result is stored in new String.
Replication: same data replicating(duplicate) multiple times.
s1 = "ratan"
s2 = "anu"
res = s1 + s2
print(res)
Ex-12: Membership operators In, not in: To check data is available or not returns Boolean value.
o "in" operator return true if a character or the entire substring is present in the specified
string, otherwise false.
o "not in" operator return true if a character or entire substring does not exist in the specified
string, otherwise false.
msg = "hi ratan sir"
print("ratan" in msg)
print("anu" in msg)
print("ratan" not in msg)
print("anu" not in msg)
msg = "ratan"
print("r" in msg)
print("z" in msg)
print("r" not in msg)
print("z" not in msg)
print("ratan" in "ratanit")
print("anu" in "ratanit")
print("ratan" not in "ratanit")
print("anu" not in "ratanit")
79 | P a g e
Python Material Mr. Ratan
print(len(msg))
print(len(msg.strip()))
name = "@@@ratan###"
print(name.lstrip("@"))
print(name.rstrip("#"))
print(name.rstrip("#").lstrip("@"))
rfind() & rindex() : it returns the last occurrence index of the string.
name = "ratanitat"
print(name.index('a'))
print(name.rindex('a'))
#print(name.index('z')) ValueError: substring not found
print(name.find('a'))
print(name.rfind('a'))
print(name.find('z')) #-1
80 | P a g e
Python Material Mr. Ratan
msg = "ratanit";
print (msg.startswith("ta",2))
print (msg.startswith("an",3,8))
print (msg.endswith("it",3))
print (msg.endswith("an",2,4))
name = "ratanitaa"
print(name.count('a'))
print(name.count('t'))
print(name.count('a',3))
print(name.count('a',3,6))
81 | P a g e
Python Material Mr. Ratan
name = "ratan124"
print(min(name))
print(max(name))
82 | P a g e
Python Material Mr. Ratan
Assignment-2 : Count number of ratan occurrences in given string without using count function.
s="ratan anu ratan durga ratan"
words = s.split()
count=0
for i in words:
if(i=="ratan"):
count=count+1
print(count)
IndexError: str = "hi sir" print(str[10]) # IndexError: string index out of range
TypeError: print (10+”ratan”) # TypeError: unsupported operand type(s) for +: 'int' and 'str'
83 | P a g e
Python Material Mr. Ratan
Introduction:
List is a data type, used to store the group of elements (homogeneous & heterogeneous).
Declare the list data using square brackets [ ] every element separated by comma.
<list_name> = [value1,value2,value3,...,valuen]
84 | P a g e
Python Material Mr. Ratan
l3 = list(range(1,11))
print(l3)
l4 = list(range(1,10,3))
print(l4)
l5 = list()
print(l5)
a. when we convert string to list format every character will becomes element of the list.
b. it is not possible to convert single element to list format, if we are trying to convert, we will
get TypeError.
85 | P a g e
Python Material Mr. Ratan
data = [10,20,30,40,50]
# 0 1 2 3 4
print(data[0])
print(data[2])
print(data[2:4])
print(data[1:])
print(data[:3])
print(data[:])
print(data[1:4:2])
print(data[1::2])
print(data[:4:2])
print(data[::2])
print(data[4:2:-2])
print(data[:2:-3])
print(data[1::-2])
print(data[::-1])
print(data[::-2])
print(data[1:10:2])
print(data[9]) IndexError: list index out of range
86 | P a g e
Python Material Mr. Ratan
print(data[0])
print(data[-1])
print(data[-5:-2])
print(data[-5:])
print(data[:-2])
print(data[:])
print(data[-5:-2:2])
print(data[-5::2])
print(data[:-2:2])
print(data[::2])
print(data[-1:-4:-2])
print(data[:-4:-2])
print(data[-2::-2])
print(data[::-2])
print(data[2:-2])
print(data[1:-1:2])
print(data[-1:2:-2])
data = [10,10.5,'ratan']
a,b,c= data
print(a,b,c)
data = [10,20,30,40,50]
a,b,*c = data
print(a,b,c) #10 20 [30, 40, 50]
numbers = [10,20,30]
x,y = numbers # ValueError: too many values to unpack (expected 2)
print(x,y)
87 | P a g e
Python Material Mr. Ratan
data = [10,20,30,40]
for x in data:
print(x)
for x in range(data[2]):
print(x)
#TypeError: 'int' object is not iterable
for x in data[2]:
print(x)
88 | P a g e
Python Material Mr. Ratan
names = ['ratan','anu','sravya','naresh']
print('anu' in names) output
print('radha' in names) E:\>python first.py
print('anu' not in names) True
print('radha' not in names) False
False
data = [10,20.5,[1,2],"ratan"] True
print([1,2] in data) True
print(20.5 in data) True
print("ratan" not in data) False
print([1,2] not in data) False
89 | P a g e
Python Material Mr. Ratan
d1 = [10,20,30]
d2 = [40,50,60]
d3 = d1
d4 = [10,20,30]
Output :
print(d1 is d4) E:\>python first.py
print(d1==d4) False
True
# printing memory address 2370982531592
print(id(d1)) 2370982532104
print(id(d2)) 2370982531592
print(id(d3)) 2370984194184
print(id(d4)) False
True
#memory comparison is , is not True
print(d1 is d2) False
print(d1 is d3) False
print(d1 is not d2) True
print(d1 is not d3) True
False
# data comparision
print(d1==d2)
print(d1==d4)
print(d1!=d2)
print(d1!=d4)
E:\>python first.py
[10, 20, 30, 40, 50, 60]
[10, 20, 30, 10, 20, 30, 40, 50, 60, 40, 50, 60]
90 | P a g e
Python Material Mr. Ratan
numbers = [10,4,5,2,20]
numbers.sort()
print(numbers)
numbers = [10,4,5,2,20]
numbers.sort(reverse=True)
print(numbers)
numbers = [10,4,5,2,20]
print(sorted(numbers))
numbers = [10,4,5,2,20]
print(sorted(numbers,reverse=True))
numbers = [1,4,5,2,30]
print(min(numbers))
print(max(numbers))
names = ['ratan','anu','sravya']
print(min(names))
print(max(names))
data = [10,10.5,True]
print(min(data))
print(max(data))
91 | P a g e
Python Material Mr. Ratan
names1 = ["ratan","ramu"]
names2 = ["ratan","ramesh"]
print(names1>names2)
print(names1<names2)
d1 = [10,"ratan"]
d2 = ["ratan",10]
print(d1>d2)
print(d1<d2) TypeError:
Note: To apply the relational operators the data must be homogenous otherwise will get TyepError.
92 | P a g e
Python Material Mr. Ratan
animal[1:3]=["cat","rat","dog"]
print(animal)
animal[1:3]="Puppy"
print(animal)
animal[2]=10
print(animal)
animal[2:4]=100 # here slicing is present but we assigned only one element.
print(animal) TypeError: can only assign an iterable
93 | P a g e
Python Material Mr. Ratan
When we need to remove an item from a list, we’ll use the list.remove(x) method which
removes the first occurrence item in a list whose value is equivalent to x.
If you pass an item in for x in list.remove() that does not exist in the list, you’ll receive the
following error: list.remove(x): x not in list
We can use the list.pop([i]) method to return the item at the given index position from the
list and then remove that item.
The square brackets around the i for index tell us that this parameter is optional, so if we
don’t specify an index (as in fish.pop()), the last element will be returned and removed.
The del statement can also be used to remove slices from a list or clear the entire list
By using clear() function we can clear the all the elements of the list.
#pop() removes the data based on index : if no index removes last by default
names = ["ratan","anu","sravya","radha"]
names.pop(2)
names.pop()
print(names)
94 | P a g e
Python Material Mr. Ratan
numbers = [10,20,30,40,10,10]
print(len(numbers))
print(numbers.count(10))
print(numbers.index(30))
print(numbers.index(10))
print(numbers.index(10,2))
fruit=["apple","orange","grapes","orange"]
fruit.reverse()
print(fruit)
95 | P a g e
Python Material Mr. Ratan
Multidimensional Lists:
ex:
l = [["ratan"] * 2] * 3
print(l)
print(l[0])
print(l[0][0])
print(l[0][1])
l[0].append("durga")
print(l)
lists = [[]] * 3
print(lists)
lists[0].append("durga")
print(lists)
The reason is that replicating a list with * doesn’t create copies, it only creates references to the
existing objects. The *3 creates a list containing 3 references to the same list of length two. Changes to
one row will effect in all rows, which is almost certainly not what you want.
ex:
ex:
a = ["ratan"]*3
for x in range(3):
a[x] = ["ratan"]*2
print(a)
w, h = 2, 3
l = [["ratan"] * w for i in range(h)]
print(l)
96 | P a g e
Python Material Mr. Ratan
# In tuple only one element it must separate with comma otherwise it is <class 'int'>
t4 = (10)
print(type(t4))
# empty tuple
t6 = ()
print(t6)
97 | P a g e
Python Material Mr. Ratan
t3 = tuple(range(1,11))
print(t3)
t4 = tuple(range(1,10,4))
print(t4)
t5 = tuple()
print(t5)
for x in fruits[2:5]:
print(x)
# this for loop having one element only but string format
for x in fruits[3]:
print(x)
98 | P a g e
Python Material Mr. Ratan
data = (10,20,30,40,50)
#0 1 2 3 4
print(data[0])
print(data[2:4])
print(data[2:])
print(data[:4])
print(data[:])
print(data[1:4:2])
print(data[1::2])
print(data[:4:2])
print(data[::2])
print(data[4:2:-2])
print(data[:2:-2])
print(data[4::-2])
print(data[::-2])
print(data[::-1])
print(data[2:10:2])
99 | P a g e
Python Material Mr. Ratan
data = (10,20,30,40,50)
# -5 -4 -3 -2 -1
print(data[0])
print(data[-1])
print(data[-4:-2])
print(data[:-2])
print(data[-4:])
print(data[:])
print(data[-5:-1:2])
print(data[-5::2])
print(data[:-1:2])
print(data[::2])
print(data[-2:-5:-2])
print(data[:-5:-2])
print(data[-2::-2])
print(data[::-2])
print(data[1:-2])
print(data[1:-2:2])
print(data[-2:2:-2])
t2 = (10,20,30,40,50)
x,y,*z = t2 # * : will store the data in list format
print(x,y,z)
print(type(x),type(y),type(z))
t3 = (1,2,4)
i,j = t3 #ValueError: too many values to unpack (expected 2)
100 | P a g e
Python Material Mr. Ratan
ex 8: Nested tuple
# 0 1
t = ((10,20) , (30,40))
#0 1 0 1
print(t[0])
print(t[1])
print(t[1][1])
print(t[0][1])
print(t[1][0])
# To use this for loop the sub tuple length must be same
for x, y in t:
print(y)
t3 = (10,20.7,False)
print(max(t3))
print(min(t3))
t4 = (10,"ratan",10.5)
print(max(t4))
print(min(t4))
TypeError: '>' not supported between instances of 'str' and 'int'
Note: To find mini & max the data must be homogenous if data is heterogenous we will get TypeError.
101 | P a g e
Python Material Mr. Ratan
Note:
in immutable data if the data is same the ref-variables are pointing to same memory because we
cannot do any modifications.
in mutable data, if the data is same or difference, the ref-var is pointing to different memory
because they can do modification later.
ex 13 : relational operators.
t1 = (1,2,4,3)
t2 = (1,2,3,4)
print(t1<t2)
print(t1>t2)
t1 = ("anu","ratan","anu")
t2 = ("anu","ratan","chandu")
print(t1>t2)
print(t1<t2)
t1 = (10,10.5,"ratan")
t2 = (10,20,"anu")
print(t1>t2)
print(t1<t2)
t1 = (10,10,"ratan")
t2 = (10,"ratan","anu")
print(t1>t2)
print(t1<t2)
TypeError: '>' not supported between instances of 'int' and 'str'
Note: To apply the relational operators the data must be homogenous.
102 | P a g e
Python Material Mr. Ratan
print(data.index(30))
print(t.index(10,2,4))
print(t.count(10))
103 | P a g e
Python Material Mr. Ratan
ex-1:
# set of integers
my_set = {1, 2, 3}
print(my_set)
print(type(my_set))
104 | P a g e
Python Material Mr. Ratan
s2 = set([10,20,30,10])
print(s2)
s3 = set(range(4))
print(s3)
s4 = set(range(2,9,3))
print(s4)
s5 = set((2,9,2,10,3))
print(s5)
s2 = {1,2,3,"anu",4,5,"ratan",7,8}
x,y,*z = s2
print(z)
s3 = {10,20,30}
i,j = s3 ValueError: too many values to unpack (expected 2)
105 | P a g e
Python Material Mr. Ratan
s1 = {10,20,30}
s1.add(2)
s1.add((1,2,3))
print(s1)
print(len(s1))
s2 = {10,20,30}
s2.update((1,2,3))
s2.update([11,22])
print(s2)
print(len(s2))
s1 = {10,20,30}
s2 = {11,22,33}
s1.update(s2)
print(s1)
Note : we can add one set to another set using update()
concat & replication is not allowed by set because set is duplicates are not allowed.
s1 = {10,20,30}
s2 = {10,20,30}
print(id(s1))
print(id(s2))
print(s1 is s2)
print(s1 is not s2)
print(s1==s2)
print(s1!=s2)
print(10 in s1)
print(100 in s1)
print(10 not in s1)
print(100 not in s1)
106 | P a g e
Python Material Mr. Ratan
ex 7 :Adding group of values into set using single line of for loop.
x = {i for i in range(10,20)}
print(x)
my_set = {"ratan","anu","sravya"}
my_set.remove("ratan")
#my_set.remove("radha") KeyError: 'radha'
print(my_set)
my_set = {"ratan","anu","sravya","radha"}
print(my_set) #{'radha', 'ratan', 'sravya', 'anu'}
print(my_set.pop()) # removes radha
print(my_set.pop()) # removes ratan
print(my_set) #{'sravya', 'anu'}
print(my_set is copy_set)
print(my_set is not copy_set)
print(my_set == copy_set)
print(my_set != copy_set)
107 | P a g e
Python Material Mr. Ratan
s2 = {10.4,20,True,3,2}
print(min(s2))
print(max(s2))
s3 = {10,20.5,"ratan"}
print(min(s3))
print(max(s3))
TypeError: '<' not supported between instances of 'int' and 'str'
a = set("ratan")
b = set("ratansoft")
print(a-b) # preset in s1 not in s2
print(a & b) # all common elements
print(a | b) # all unique elements
print(a^b) # without common elements
108 | P a g e
Python Material Mr. Ratan
ex 1: dict declarations.
phone = {"ratan":9090909,"anu":8080808,"sravya":707070}
print(phone)
d2 = {111:"ratan",111:"anu",222:"sravya"}
print(d2)
d3 = {}
print(d3)
print(type(d3))
d1 = {}
d1[111] = "ratan"
d1[222] = "anu"
print(d1)
phone = {"ratan":9090909,"anu":8080808}
phone['ratan'] = 9999999
print(phone)
data = {}
data[(1,2,3)] = [1,2,3]
data["ratan"] = (10,20)
print(data[(1,2,3)][-1])
data[(1,2,3)].append(100)
print(data)
109 | P a g e
Python Material Mr. Ratan
t1 = (1,2,3)
t2 = ("aaa","bbb","ccc")
d2 = dict(zip(t1,t2))
print(d2)
# empty dictionary
x = dict()
print(x)
res = dict(zip(range(1,6),range(10,60,10)))
print(res)
friends = {'tom':'111-222-333','jerry':'666-33-111'}
print(friends)
print(friends['tom'])
print(friends['jerry'])
print(friends.get("ratan")) #none
print(friends.get("tom"))
print(friends.get('jerry'))
print(friends['ratan']) #KeyError: 'ratan'
110 | P a g e
Python Material Mr. Ratan
phone = {"ratan":9090909,"anu":8080808,"sravya":707070}
print(phone.keys())
print(phone.values())
print(phone.items())
print(list(phone.keys()))
print(list(phone.values()))
print(list(phone.items()))
print(tuple(phone.keys()))
print(tuple(phone.values()))
print(tuple(phone.items()))
print(set(phone.keys()))
print(set(phone.values()))
print(set(phone.items()))
ans:
d1 = {11:"aaa",22:'bb',33:'cc'}
d2 = {1:"ratan",2:'sravya',3:'anu'}
res = dict(zip(d1.keys(),d2.values()))
print(res)
111 | P a g e
Python Material Mr. Ratan
ex-7:
To print the id of the dictionary use id() function, it print memory address.
To check the memory address use is & is not operator.
o If two references are pointing to same memory returns true otherwise false.
== operator will check the data in dictionary (key based) not memory address.
o If the data same returns true otherwise false.
To check the data is available or not use in & not in operators. If the data present in dictionary
return true otherwise returns false.
d1 = {1:"ratan",2:"anu"}
d2 = {3:"aaa",4:"bbb"}
d3=d1
d4={1:"ratan",2:"anu"}
print(id(d1))
print(id(d2))
print(id(d3))
print(d1 is d2)
print(d1 is d3)
print(d1 is not d2)
print(d1 is not d3)
print(d1==d2)
print(d1==d4)
print(d1!=d2)
print(d1!=d4)
print(1 in d1)
print("ratan" in d1)
print(1 not in d1)
print("ratan" not in d1)
112 | P a g e
Python Material Mr. Ratan
#Updating data
mydict = {"ratan":28,"anu":25,"durga":30}
mydict["ratan"]=35
print(mydict)
Note : dict data type concat & replication not allowed because it does not allowed duplicates.
but it is possible to substitute one dict data into another dict using **.
phonebook ={ "ratan":938477,"anu":93837,"sravya":909090}
phonebook.pop("anu")
#phonebook.pop("naresh") KeyError: 'naresh'
print(phonebook)
phonebook ={ "ratan":93847,"anu":938372,"sravya":909090}
phonebook.popitem()
print(phonebook)
phonebook ={ "ratan":938477,"anu":938372,"sravya":90090}
phonebook.clear()
print(phonebook)
113 | P a g e
Python Material Mr. Ratan
res = dict.fromkeys(range(1,6),"naresh")
print(res)
E:\>python first.py
{1: 'ratan', 23: 'ratan', 31: 'ratan', 40: 'ratan'}
{1: 'naresh', 2: 'naresh', 3: 'naresh', 4: 'naresh', 5: 'naresh'}
d2 = {"ratan":1,"anu":2,"sravya":3}
print(min(d2))
print(max(d2))
d3 = {1:"ratan","anu":2,10.5:"naresh"}
print(min(d3))
print(max(d3))
TypeError:'<'not supported between instances of 'str' and 'int'
114 | P a g e
Python Material Mr. Ratan
print(str(d2[2][2])[-1])
print(d2[1][22][1:2][1])
d3 = {1:[1,2,3,4],2:{11:"ratan",22:"anu"}}
del d3[1][1]
del d3[2][22]
print(d3)
d1 = {1:{11:"ratan",22:"anu"},2:[10,20,30]}
del d1[1][22]
d1[2].remove(20)
print(d1)
d2 = {1:{111:[1,2,3],222:"anu"},2:[1,2,[10,20,30]]}
del d2[1][111][-1]
d2[2][2].remove(20)
print(d2)
d1 = {1:{11:"ratan",22:{"aa":12,"bb":23}},2:[10,20,30]}
del d1[1][22]['bb']
del d1[2][:2]
print(d1)
d2 = {1:{11:"ratan",22:"anu"},2:[10,20,30]}
print(d2[1][22])
print(d2[2][1])
115 | P a g e
Python Material Mr. Ratan
Ex-1 : any() returns Boolean values, if any one condition is True then it returns True.
print(any([2>8,4>2,1>2]))
print(any((True,False,True))) E:\>python first.py
True
print(any({1,2,3,4})) True
print(any({False,False,False})) True
False
print(any({0 : "Apple", 1 : "Orange"})) True
print(any({111 : "Apple", 222 : "Orange"})) True
print(any({2>3 : "Apple", 1>3 : "Orange"})) False
E:\>python first.py
Enter a expresson:10+20*5
110
Enter three numbers:(10,20,30)
60
Enter three numbers:[1,2,3]
6
Enter three numbers:{4,5,6}
15
Enter three numbers:{1:"aaa",2:"bbb",3:”ccc”}
6
116 | P a g e
Python Material Mr. Ratan
print("a".join("bd"))
print("ratan".join("abc"))
print("a".join(['a','b','c','d']))
print("ratan".join(('1','2','3')))
print("apple".join({"ratan","anu"}))
#print("a".join([10,20,30])) TypeError:
E:\>python first.py
bad
aratanbratanc
aabacad
1ratan2ratan3
anuappleratan
117 | P a g e
Python Material Mr. Ratan
118 | P a g e
Python Material Mr. Ratan
ex 2:
#Filter the data starts with r & len should be <=4
data = ["ratan","raju","rani","narestit","anu"]
print(list(filter(lambda x:len(x)<=4 and x.startswith("r"),data)))
119 | P a g e
Python Material Mr. Ratan
Maper: The map function is used to apply a particular operation to every element in a sequence.
map (map_logics , input_data)
ex-1:
# Adding +2 marks for all elements
marks = [34,56,34,23,67,33]
print(list(map(lambda x:x+2,marks)))
print(list(map(max,"ratan")))
print(list(map(min,"anu"))) E:\>python first.py
['r', 'a', 't', 'a', 'n']
print(list(map(min,["ratan","anu"]))) ['a', 'n', 'u']
print(list(map(max,("anu","sravya")))) ['a', 'a']
['u', 'y']
print(list(map(len,["ratan","anu"]))) [5, 3]
print(list(map(len,("anu","sravya")))) [3, 6]
[3, 7, 11]
print(list(map(sum,[[1,2],[3,4],[5,6]])))
120 | P a g e
Python Material Mr. Ratan
l1 = [1,2,3]
l2 = [5,6,7]
res = list(map(lambda x,y:x*y,l1,l2))
print(res)
E:\>python first.py
[111, 222, 333]
[5, 12, 21]
ex 5: Assignment
l1 = [[1,2],[1,2,3],[1,2,3,4]]
l2 = [[10,20],[10,20,30],[10,20,30,40]]
addition of all l1 sublist data
min of all l2 data
need the multiplication of first result & second result.
Answer:
l1 = [[1,2],[1,2,3],[1,2,3,4]]
l2 = [[10,20],[10,20,30],[10,20,30,40]]
res1 = list(map(sum,l1))
res2 = list(map(min,l2))
print(list(map(lambda x,y:x*y,res1,res2)))
E:\>python first.py
[30, 60, 100]
121 | P a g e
Python Material Mr. Ratan
reduce:
reduce will perform competition on all elements it returns only one element as result.
The reduce will take always 2 inputs to perform the operations.
reduce is a function present in functools module so import the module using import stmt.
Ex-1:
from functools import reduce
l1 = [1,2,3,4]
print(reduce(lambda x,y:x*y,l1))
l1 = [1,2,3,4]
print(reduce(lambda x,y:x**y,l1))
names = ["ratan","anu","sravya"]
res = reduce(lambda x,y:x+y,names)
print(len(res))
ex-2: Assignment
#problem statement #Answer
Take the list of 1-20 elements from functools import reduce
filter the even values data = list(range(1,21))
every value add +3 even = list(filter(lambda x:x%2==0,data))
then print the addition of all elements mapres = list(map(lambda x:x+3,even))
print(reduce(lambda x,y:x+y,mapres))
ex-3: Assignment
#problem statement #Answer
Take the list of 12 elements: 202020212222 from functools import reduce
filter only twos data = list("202020212222")
every element power of 3 fil_res = list(filter(lambda x:x=='2',data))
print the add of all elements res = list(map(lambda x:int(x)**3,fil_res))
print(reduce(lambda x,y:x+y, res))
***Feeling important****
Do practical’s**************Thank you************Refer your Friends
122 | P a g e
Python Material Mr. Ratan
Exception handling
Syntax error are nothing but normal mistakes done by developer while writing the code.
An exception is an error that happens during the execution of a program.
123 | P a g e
Python Material Mr. Ratan
124 | P a g e
Python Material Mr. Ratan
The try block contains exceptional code it may raise an exception or may not.
If the exception raised in try block the matched except block will be executed.
ex-1
# Application without try-except block
print("Hello")
print(10/0)
print("rest of the app……")
output :
Hello
ZeroDivisionError: division by zero
Disadvantages:
o Program terminated abnormally.
o Rest of the application not executed.
output :
5
rest of the Application
Advantages:
o Rest of the application executed.
o Program terminated normally.
ex-2:
If the except block is not matched so program terminated abnormally.
In below example try block raise ZeroDivisionError but except block not matched(TypeError)
try:
print(10/0)
except TypeError as a:
print("Exception raised:",a)
print("Rest of the App")
125 | P a g e
Python Material Mr. Ratan
ex-3: If no exception occurs in try block then code under except clause will be skipped.
try:
print("ratanit")
except ArithmeticError as a:
print("Exception raised:",a)
ex 6: if the exception raised in try block it will check the except blocks.
if the exception raised in except block: abnormal termination
try:
print(10/0)
except ZeroDivisionError:
print(10+"ratan")
print("rest of the app")
error :
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
ex 7: once the exception raised in try: the remaining code of the try not executed.
try:
print(10/0)
print("ratan")
print("anu")
except ZeroDivisionError:
print(10/2)
print("rest of the app")
E:\>python first.py
5.0
rest of the app
126 | P a g e
Python Material Mr. Ratan
case 3: when we have multiple except blocks the except blocks order is child to parent.
try:
n = int(input("enter a number:"))
print(10/n)
print(10+"ratan")
except ZeroDivisionError as e:
print("ratanit...",e)
except Exception as a:
print("nareshit.....",a)
print("rest of the app")
case 4: when we have multiple except blocks the except block order is child to parent, if we declare order
is parent to child, in this case the parent can handle all the exceptions, the child will be ignored.
try:
n = int(input("enter a number:"))
print(10/n)
print(10+"ratan")
except Exception as a:
print("nareshit.....",a)
except ZeroDivisionError as e:
print("ratanit...",e)
print("rest of the app")
127 | P a g e
Python Material Mr. Ratan
case 1: The else block will be executed when there is no exception in try block.
try:
n = int(input("enter a num:"))
print(10/n)
except BaseException as a:
print("exception msg=",a)
else:
print("no exception in try")
print("Rest of the app")
enter a num:5
enter a num:0
enter a num:ratan
try:
n = int(input("enter a num:"))
print(10/n)
print(10+"ratan")
except TypeError as e:
print("ratanit")
except:
print("nareshit")
print("Rest of the app")
128 | P a g e
Python Material Mr. Ratan
Category-4
Below all cases can handle multiple exceptions
except BaseException as a:
except Exception as a:
except:
except (ZeroDivisionError,ValueError) as a:
except (IndexError,KeyError,TypeError) as a:
ex: one except block can handle multiple exceptions exception using comma separator.
try:
n = int(input("enter a num:"))
print(10/n)
except (ZeroDivisionError,ValueError) as a:
print("exception msg=",a)
else:
print("no exception in try")
print("Rest of the app")
enter a num:5
enter a num:0
enter a num:ratan
#function call
my_func()
129 | P a g e
Python Material Mr. Ratan
Case 1: try:
print("outer try block")
n = int(input("enter a number"))
print(10/n)
try:
print("inner try")
print("anu"+"ratan")
except TypeError:
print("ratanit.com")
else:
print("inner no exception")
except ArithmeticError:
print(10/5)
else:
print("outer no excepiton")
finally:
print("finally block")
case 2:
try:
n = int(input("enter a number:"))
print("outer try block")
try:
print("Inner try block")
print(10/n)
except NameError:
print("Inner except block")
finally:
print("Inner finally block")
except ZeroDivisionError:
print("outer except block")
else:
print("else block execute")
finally:
print("outer finally block")
print("Rest of the Application")
130 | P a g e
Python Material Mr. Ratan
Finally block:
finally block executed always in both normal & abnormal termination of application.
finally, block is always executed irrespective of try-except blocks.
finally blocks is used to release the resource like (database closeing,file closeing) in both normal
cases and abnormal cases.
try:
<exceptional code>
except <ExceptionType1>:
<handler1>
else:
<process_else>
finally:
<process_finally>
131 | P a g e
Python Material Mr. Ratan
case 1: The control is not entered in try block so finally block is not executed.
print(10/0)
try:
print("try block")
finally:
print("finally block")
case 2: when we use os._exit(0) virtual machine is shutdown so finally block is not executed.
import os
try:
print("try block")
os._exit(0)
finally:
print("finally block")
Interview Questions:
Case 1: If the try,except , finally block contains exceptions : it display all three exception.
try:
print(10/0)
except ArithmeticError as e:
print("ratan"+10)
finally:
s="ratan"
print(s[10])
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
During handling of the above exception, another exception occurred:
IndexError: list index out of range
Case 2: If the try,except , finally block contains return statement : it display finally block return
def disp():
try:
return 10
except:
return 20
finally:
return 30
print(disp())
132 | P a g e
Python Material Mr. Ratan
only try :
only except :
only else :
only finally :
try-except :
try-except-else :
try-except-except-else :
try-except -finally :
try-except -else - finally :
try-finally :
try-finally-except :
try-except-finally-else :
try-except-else-finally :
try-except -except-finally :
try-except-except-else-finally :
try-try-except-except-else-finally :
try-except-except-else-else-finally :
try-except-except-else-finally-finally :
133 | P a g e
Python Material Mr. Ratan
st-1
st-2
try:
st-3
st-4
try:
st-5
st-6
except:
st-7
st-8
except:
st-9
st-10
try:
st-11
st-12
except:
st-13
st-14
else:
st-15
st-16
finally:
st-17
st-18
st-19
st-20
Write the output of below all cases
case 1: No exception in above example.
Case 2: Exception raised in st-2
Case 3: exception raised in st-3 the except block is matched.
Case 4: exception raised in st-4 the except block is not matched.
Case 5: exception raised in st-5 the except block is matched.
Case 6:exception raised in st-6 the inner except block is not matched but outer except block is matched .
Case 7 : Exception raised in st-5 the except block is matched while executing except block
exception raised in st-7 the inner except block executed while executing inner except
block exception raised in st-9 , the inner except block executed while executing inner
except exception raised in st-11.
Case 8 : Exception raised in st-6 the except block is matched while executing except block
exception raised in st-8 the inner except block executed while executing inner except
block exception raised in st-10 , the inner except block executed while executing inner
except exception raised in st-12.
Case 9 : exception raised in st-13
Case 10 : exception raised in st-15
Case 11 : exception raised in st-18
134 | P a g e
Python Material Mr. Ratan
raise keyword:
By using raise keyword we can raise predefined exceptions & user defined exceptions.
By using raise keyword it is not recommended to raise predefined exceptions because predefined
exceptions contains some fixed meaning(don’t disturb the meaning).
raise ArithmeticError("name is not good")
By using raise keyword, it is recommended to raise user defined exceptions.
raise InvalidAgeError("age is not good")
135 | P a g e
Python Material Mr. Ratan
Assignment:
Create exception : TooYoungError : without description
136 | P a g e
Python Material Mr. Ratan
File is a named location on disk to store related information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk).
Python support read & write operations on the file using predefined functions. But does not require
any predefined modules.
Text file:
Text files are contains simple text(character data).
Ex: .html , .c , .cpp , .java ….etc
Binary files:
Binary files contain binary data which is only readable by computer.
Ex : video files ,audio files , ,jpg file ,pdf files ….etc
Note: To read the data from file then file is mandatory but to write the data file is optional.
137 | P a g e
Python Material Mr. Ratan
The open function takes two arguments, the name of the file and the mode of operation.
f = open (filename, mode)
step 2: Read, Write, Append the data: The default mode of the file is: Read
Writing to a File : write() method is used to write a string into a file.
Reading from a File : read() method is used to read data from the File.
Append operations : used to append the data to existing file.
File modes :
r : read
w : write
a : append
By default the file is open in read mode.
138 | P a g e
Python Material Mr. Ratan
f = open("sample.txt",'w')
f.write"hi ratan sir \n welcome to ratanit")
f.close()
print("operations are completed.....")
f = open("sample.txt")
data = f.read()
print(data)
f.close()
print("Operations are successfull.....")
f = open("sample.txt",'a')
f.write("\n Good Morning")
f.close()
print("Operations are successfull")
f = open("sample.txt",'r')
print(f)
print(f.name)
print(f.mode)
print(f.closed)
f.close()
print(f.closed)
139 | P a g e
Python Material Mr. Ratan
f = open("sample.txt",'r')
res = f.read(5) # after reading 5-cahrs the control is 5th characters
print(res)
print(f.tell())
f.seek(0) #moving the control to starting location
res = f.read(4)
print(res)
print(f.tell())
f.close()
ex 6: Assignment.
Assume like abc.txt : contians 3-lines of code
from abc.txt read the first 3-chars write to : a.txt
from abc.txt read the first 6-chars write to : b.txt
from abc.txt read the first 2-8-chars write to : c.txt
Ans: f = open("abc.txt",'r')
f1= open("a.txt","w")
f1.write(f.read(3))
f.seek(0)
f2= open("b.txt","w")
f2.write(f.read(6))
f.seek(2)
f3= open("c.txt","w")
f3.write(f.read(8))
f.close()
f1.close()
f2.close()
f3.close()
print("operations are completed")
140 | P a g e
Python Material Mr. Ratan
f = open("sample.txt",'r')
res = f.read(5)
print(res)
f.seek(0)
res = f.readline()
print(res)
f.seek(0)
res = f.readlines()
print(res)
f.close()
E:\>python first.py
hi st
hi students
['hi students \n', 'how are you\n', 'Good Evening\n', 'sunday no class...']
Note : readlines() function read the data line by line format and it return list format so we can
use slicing to the get the specific lines.
ex 8:
assume like abc.txt contains 4-lines of code
from abc.txt read the first line write to : a.txt
from abc.txt read the first two lines write to : b.txt
from abc.txt read the first 3-lines write to : c.txt
141 | P a g e
Python Material Mr. Ratan
f1 = open("sample.txt",'r')
f2 = open("ratan.txt",'w')
for x in f1:
f2.write(x)
f1.close()
f2.close()
print("operations are completed....")
f = open("sample.txt",'r+')
print(f.read())
f.write("\nHi stuents.....")
f.close()
f = open("sample.txt",'w+')
f.write("Hi stuents.....")
f.seek(0)
print(f.read())
f.close()
in above example after writing the data the control is pointing at last but to read the
data from starting move the cursor first location using seek.
142 | P a g e
Python Material Mr. Ratan
Here after appending the data the control is poining at last but to read the data move
the cursor first location using seek.
in above example
All operations are success then file is closed.
If any operation fails the program terminated abnormally in this case file is not closed.
To overcome above problem to close the file in both normal & abnormal cases use finally block.
#Solution:
try:
f = open("sample.txt","w")
f.write("hi sir how are you")
print(10/0)
except Exception as e:
print("Exception info....",e)
finally:
f.close()
print("File is closed")
In above example we are closing the file using finally block. The finally block is executed
both normal & abnormal cases so the file is closed in both normal cases & abnormal cases.
143 | P a g e
Python Material Mr. Ratan
ex-18: Assignment.
create the directory ratan
under the directory create the file abc.txt & write the data to file
after writing the data read the data from file & print it on console.
Ans:
import os
os.mkdir("ratan")
os.chdir("ratan")
f = open("abc.txt","w+")
f.write("Good Morning...")
f.seek(0)
print(f.read())
f.close())
144 | P a g e
Python Material Mr. Ratan
ex-19: Assignment
write “hi ratan sir” message 10 times to file.
after write read only “ratan” from the file.
Ans:
f = open("abc.txt",'w+')
for x in range(10):
f.write("hi ratan sir\n")
f.seek(0)
for x in f:
print(x.split()[1])
f.close()
ex-20:
create the file abc.txt write the data: 10 20 30 40 50
read the data from abc.txt i need the sum of all numbers. #read & sum in single.
f = open("abc.txt",'w+')
for x in range(0,51,10):
f.write(str(x)+"\n")
f.seek(0)
print(sum(list(map(lambda x:int(x.split("\n")[0]),f.readlines()))))
f.close()
145 | P a g e
Python Material Mr. Ratan
Assertion
Assertion is used to debug the application.
Assert statements are a convenient way to insert debugging assertions into a program.
Note: the assert msg will be printed when the condition is fail.
When we will get AssertionError decide in application we are putting some condition but it is fail.
ex-1 :
name = input("Enter u r name:")
# success means nathing happen
assert name=="ratan","something is wrong"
print("your name is working good.....")
E:\>python first.py
Enter u r name:ratan
your name is working good.....
E:\>python first.py
Enter u r name:anu
AssertionError: something is wrong
ex 2:
company = input("enter company name:")
sal = int(input("enter sal:"))
house = input("enter house : (yes/no):")
assert company=="tcs" and sal>80000 and house=="yes","sorry try for other girl"
ex 3:
name = input("enter comp name:")
sal = int(input("enter sal:"))
house = input("enter house name:")
146 | P a g e
Python Material Mr. Ratan
E:\>python first.py
Enter a status code:200
Application working fine
E:\>python first.py
Enter a status code:202
AssertionError: we got fail response code
ex 5: data = [2,4,6,25,56,8,65]
for x in data:
assert x<20,"the values is rejected"
print(x)
ex-6:
def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
assert 0 <= price <= product['price'],"give proper info"
return price
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
E:\>python first.py
Average of mark2: 78.0
AssertionError: List is empty.
147 | P a g e
Python Material Mr. Ratan
Oracle versions:
oracle 9i
oracle 10g
oracle 11g
oracle 12c
oracle 18c
in google type :
oracle 11g express edition free download
https://www.oracle.com/database/technologies/xe-prior-releases.html
# Oracle queries:
create table emp(eid number,ename varchar2(30),esal number);
desc emp;
148 | P a g e
Python Material Mr. Ratan
The oracle database connection required one module cx_Oracle so install the module using pip command
pip install cx_Oracle
cs = conn.cursor()
cs.close()
conn.close()
print("Connection closed successfully....")
149 | P a g e
Python Material Mr. Ratan
ex 4 :
#reading all columns data
res = cs.execute("select * from emp")
for x in res:
print(x)
cs.close()
ex 5:
Take eid ename esal from end user. insert the data into emp table.
After that do u want one more record : yes/no
if yes : again take the data from end user insert into data base
if no : stop the execution.
Ans:
import cx_Oracle
conn = cx_Oracle.connect("system","ratan")
cs = conn.cursor()
while True:
eid = int(input("etner Emp id:"))
ename = input("Enter emp name:")
esal = float(input("enter Emp sal:"))
cs.execute(f"insert into emp values({eid},'{ename}',{esal})")
conn.commit()
option = input("data inserted do you want one more(yes/no)")
if option=="no":
break
cs.close()
conn.close()
print("Connection closed successfully.....")
150 | P a g e
Python Material Mr. Ratan
ex 6:
create product table : pd pname pcost
insert three product records into product table.
print the product data
update the data pcost>100 +5
print the product data
drop the product table
Ans:
import cx_Oracle
conn = cx_Oracle.connect("system","ratan")
cs = conn.cursor()
cs.execute("create table product(id number,name varchar2(30),cost number)")
print("table created successfully.....")
cs.close()
conn.close()
print("Conneciton closed successfully....")
151 | P a g e
Python Material Mr. Ratan
cs = conn.cursor()
cs.close()
conn.close()
print("connection closed successfully....")
#Application Flow:
In above example 3-times we are sending request & 3-times we are getting response.
If the application contains more data then network calls are increased its effects on performance.
In above example we are inserting the data one by one record using for loop this is simple execution
in this case we are sending req to database 3-times.
if the number of values is increased the number of network calls will be increased it effects on
performance.
cs = conn.cursor()
cs.close()
conn.close()
print("connection closed successfully....")
152 | P a g e
Python Material Mr. Ratan
ex-8: inserting 100 records into emp table using simple execution & batch execution.
import cx_Oracle
import random
import names
conn = cx_Oracle.connect("system","ratan")
cs = conn.cursor()
#simple execution inserting 100 records into emp table.
for x in range(200):
cs.execute(f"insert into emp values({x},'{names.get_first_name()}',{random.uniform(5,9)})")
cs.executemany(query,details)
conn.commit()
cs.close()
conn.close()
print("Connection closed successfully.......")
in above example,
a. if the application terminated normally then connection is closed.
b. when exception raised program terminated abnormally, connection is not closed.
so, you must close the connection both normal cases & abnormal cases so use finally block.
the finally block is executed both normal cases & abnormal cases.
import cx_Oracle
try:
conn = cx_Oracle.connect("system","ratan")
print("Connection created successfully...")
print(10/0)
except:
print("Excpetion raised...")
finally:
conn.close()
print("Connection closed successfully...")
The finally block is executed both normal cases & abnormal cases the connection will be closed.
153 | P a g e
Python Material Mr. Ratan
import cx_Oracle
try:
conn = cx_Oracle.connect("system","ratan")
print("Connection created successfully...")
cs = conn.cursor()
cs.execute("insert into emp values(111,'ratan',10000.45)")
cs.execute("insert into emp values(222,'anu',20000.45)")
cs.execute("insert into emp values(333,'sravya',30000.45)")
cs.execute("update emp set esal=esal+100 where esal>15000")
conn.commit()
print("Transction success......")
except:
conn.rollback()
print("Transction fail......")
finally:
cs.close()
conn.close()
print(“database connection closed”)
154 | P a g e
Python Material Mr. Ratan
MySQL Database
155 | P a g e
Python Material Mr. Ratan
import mysql.connector
con =
mysql.connector.connect(host="localhost",user="root",password="root",database="ratan")
print("Connection creation successfull")
cs = con.cursor()
print("cursor created successfully...")
cs.close()
con.close()
print("Connection closed.........")
observation : if the emp table is already available we will get error message.
E:\>python first.py
Connection successfull
operations are fail.... 1050 (42S01): Table 'emp' already exists
observation: if the username or password wrong, we will get error message
E:\>python first.py
operations are fail. 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
observation : if the query is wrong we will get error message.
E:\>python first.py
Connection successfull
operations are fail.... 1064 (42000): You have an error in your SQL syntax;
cs = con.cursor()
print("cursor created successfully...")
cs.close()
con.close()
print("Connection closed.........")
156 | P a g e
Python Material Mr. Ratan
157 | P a g e
Python Material Mr. Ratan
postgres Database
ex-1:
import psycopg2
try:
conn = psycopg2.connect(user="postgres",password ="ratan",host = "localhost", port
="5432",database="postgres")
cs = conn.cursor()
while True:
eid = int(input("enter employee id::"))
ename = input("enter employee name::")
esal = int(input("enter employee salary::"))
address = input("enter employee name::")
cs.execute(f"insert into Emp_table values({eid},'{ename}',{esal},'{address}')")
request = input("IF YOU WANT TO ADD NEW ROW\nPLEASE ENTER OPTIONS::(yes/no)or(y/n)")
conn.commit()
if request == 'yes' or request == 'y':
continue
elif request == 'no' or request == 'n':
print("YOUR WORK IS COMPLETED..")
break
else:
print("SORRY YOU SELECTED WRONG OPTION")
break
conn.commit()
cs.execute("select *from emp_table")
res =cs.fetchall()
for x in res:
print(x)
except Exception as e:
print("exception",e)
finally:
cs.close()
conn.close()
158 | P a g e
Python Material Mr. Ratan
ex-2 :
import psycopg2
try:
conn = psycopg2.connect(user="postgres",password ="ratan",host ="localhost" , port
="5432",database="postgres")
cs = conn.cursor()
cs.execute("create table Login_table(user_name text ,password text)")
cs.execute("insert into Login_table values('raja','dillraja')")
cs.execute("insert into Login_table values('dillraja','raja')")
conn.commit()
cs.execute("select *from Login_table")
print(cs.fetchone())
except Exception as e:
print(e)
finally:
cs.close()
conn.close()
ex-3:
import psycopg2
conn = psycopg2.connect(user ="postgres",password = "ratan",host = "localhost",port ="5432",database
= "postgres")
cs = conn.cursor()
username = ['raja','ramu','pawan']
password = ['aaa','bbb','ccc']
res = list(zip(username , password))
for x in res:
cs.execute(f"insert into Login_table values('{x[0]}','{x[1]}')")
conn.commit()
cs.execute("select *from Login_table")
print(cs.fetchall())
cs.close()
conn.close()
ex 4:
import psycopg2
conn = psycopg2.connect(user ="postgres",password = "Raja1234",host ="127.0.0.1", port =
"5432",database ="postgres" )
cs = conn.cursor()
cs.execute("delete from Login_table where user_name ='raja'")
159 | P a g e
Python Material Mr. Ratan
except Exception as e:
print(e)
finally:
conn.commit()
cs.close()
conn.close()
res =Registration()
res.registration()
160 | P a g e
Python Material Mr. Ratan
ex-6:
import psycopg2
conn = psycopg2.connect(user = "postgres",password ="Raja1234",host="127.0.0.1", port
="5432",database = "postgres")
conn.autocommit = True
cs = conn.cursor()
cs.execute('CREATE DATABASE Ramu')
print('operations are succuss')
cs.close()
conn.close()
ex-7:
import psycopg2
conn = psycopg2.connect(user = "postgres",password ="Raja1234",host="127.0.0.1", port
="5432",database = "postgres")
cs = conn.cursor()
cs.execute("create table student_table(sid integer ,sname text , smarks integer)")
sid,sname,smarks =[1,2,3,4,5],['raja','ramu','pawankalyan','karnakar','kashi'],[45,78,76,46,57]
res = list(zip(sid,sname,smarks))
for x in res:
cs.execute(f"insert into student_table values({x[0]},'{x[1]}',{x[2]})")
conn.commit()
cs.execute("select * from student_table")
results = cs.fetchall()
for x in results:
print(x)
cs.close()
conn.close()
print("operations are succuss")
161 | P a g e
Python Material Mr. Ratan
Regular Expression
Introduction:
The term "regular expression", sometimes also called regex or regexp for string pattern
matching.
In python the regular expression is available in re module.
To check the predefined functions in re module use dir()
import re
print(dir(re))
A raw string is a string literal (prefixed with an r) in which the normal escaping rules have been
suspended so that everything is a literal.
Raw string can prefix with `r' or `R’.
For example, the string literal r"\n" consists of two characters: a backslash and a lowercase `n'.
#normal string
print ('this\nexample')
print('this\twebsite')
print('C:\\Program Files')
#raw String
print (r'this\nexample')
print(r'this\twebsite')
print(r'C:\\Program Files')
162 | P a g e
Python Material Mr. Ratan
import re
result = re.match(r'ratan', 'ratan sir good')
print (result)
print (result.group(0))
print (result.start())
print (result.end())
E:\>python first.py
<_sre.SRE_Match object; span=(0, 5), match='ratan'>
ratan
0
5
None
ex 2: If the whole string matches this regular expression, return a corresponding match object.
Return None if the string does not match the pattern.
import re
result = re.match(r'ratan', 'ratan sir')
print (result)
E:\>python first.py
<re.Match object; span=(0, 5), match='ratan'>
None
<re.Match object; span=(0, 5), match='ratan'>
163 | P a g e
Python Material Mr. Ratan
ex-3: re.search(pattern,input)
pattern : The data that we want find.
input : The available data
This method finds match entire string. If the match is not available it returns None.
The search will return only first occurrence.
import re
result = re.search(r'ratan', 'hi ratan sir good ratan sir is great')
print (result)
print (result.start())
print (result.end())
print(result.span())
print (result.group(0))
ex 4: findall(pattren,input)
search() function will returns only first occurrence but findall() returns all
occurrences in the form of list.
if the data is not available it returns empty list.
import re
result = re.findall(r'ratan', 'hi ratan sir ratan good')
print (result)
164 | P a g e
Python Material Mr. Ratan
ex 5: compile(string)
compile the pattern only once later we can use that pattern multiple times.
create the object of your pattern then use that object multiple times.
import re
#application code without compile() function
result1 = re.findall(r'ratan', 'hi ratan sir ratan sir good')
print (result1)
result2 = re.findall(r'ratan', 'hi good ratan sir')
print (result2)
result3 = re.findall(r'ratan', 'hi ratan sir ratan sir great')
print (result3)
165 | P a g e
Python Material Mr. Ratan
ex 7: split() functions
import re
result = re.split(" ","hi ratan sir")
print(result)
result = re.split("ratan","hi ratan sir")
print(result)
result = re.split(" ","hi ratan sir python is good",maxsplit=2)
print(result)
E:\>python first.py
['hi', 'ratan', 'sir']
['hi ', ' sir']
['hi', 'ratan', 'sir python is good']
ex 8: finditer()
findall() : it return the data in elements format
finditer : it return the data in object format
import re
s = "hi i like beer and beer is good"
ex-9:
msg = "hi ratan sir python is Good"
take the input pattren from enduser to search :
enter pattren : ratan : search successfull
enter pattren : naresh : search not successfull
Ans:
import re
msg = "hi ratan sir python is Good"
pattern = input("input pattern:")
data = re.search(pattern,msg)
if data:
print("search successful")
else:
print("search not successful")
166 | P a g e
Python Material Mr. Ratan
[abc] Only a, b, or c
[a-z] Characters a to z
[a-e] characters a to e
[^abc] Not a, b, nor c
[0-9] Numbers 0 to 9
import re
s = "rat mat bat cat ratan naresh"
x = re.findall("[rmbc]at",s)
print(x)
y = re.findall("[a-f]at",s)
print(y)
z = re.findall("[^a-f]at",s)
print(z)
i = re.findall("[a-z]at",s)
print(i)
j = re.findall("[A-Z]at",s)
print(j)
E:\>python first.py
['ratan', 'ratan', 'can', 'an']
['ran', 'rrran']
['ran', 'tan', 'an', ' an']
167 | P a g e
Python Material Mr. Ratan
result2 = re.findall("[hc]+at",input)
print(result2)
result3 = re.findall("[hc]?at",input)
print(result3)
import re
x = re.findall("\d{2}","1 hi 23 ratan 156 sirr 2456")
print(x)
y = re.findall("\d{2,}","1 hi 23 ratan 156 sirr 2456")
print(y)
z = re.findall("\d{1,3}","1 hi 23 ratan 156 sirr 2456")
print(z)
num = "12345"
print("Matches : ",len(re.findall("\d",num)))
print("Matches : ",len(re.findall("\D",num)))
168 | P a g e
Python Material Mr. Ratan
169 | P a g e
Python Material Mr. Ratan
res = dict(zip(names,age))
print(res)
170 | P a g e
Python Material Mr. Ratan
171 | P a g e
Python Material Mr. Ratan
2. static method
self not required but it required @staticmethod qualifier.
Access the static method using class-name.
3. cls method
First argument must be cls.
Access the class method using object name & class-name.
@staticmethod
def wish():
print("Good morning")
@staticmethod
def mul(num1,num2):
print(num1*num2)
#Data Access
op = Operations()
op.add(10,20)
Operations.mul(3,4)
172 | P a g e
Python Material Mr. Ratan
c. Based on single class it is possible to create multiple objects but every object occupies memory.
ex-3: for single class possible to create multiple objects every object occupies memory.
class MyClass:
def disp(self,name):
print("Good Morning....",name)
c2 = MyClass()
c2.disp("Anu")
class MyClass:
def wish(self):
print("Good evening...")
173 | P a g e
Python Material Mr. Ratan
print(id(c1))
print(id(c2))
print(id(c3))
print(id(c4))
#memory comp
print(c1 is c2)
print(c3 is c4)
print(c1 is not c2)
print(c3 is not c4)
ex 6:
__init__: constructor executed when we create the object.
__str__:
it will be executed when we print the object
it will return only string data.
if we return other than stirng data we will get TypeError
__del__ : destructor
it will be executed when we destroy the object.
destroy the object using del keyword.
class MyClass:
def __init__(self):
print("this is constructor")
def __str__(self):
return "ratan"
def __del__(self):
print("object destroyed")
c = MyClass()
print(c)
del c
observation :
def __str__(self):
return 10
TypeError: __str__ returned non-string (type int)
174 | P a g e
Python Material Mr. Ratan
ex 7 : Methods Accessing
class MyClass:
def disp(self):
print("hi students")
@staticmethod
def wish():
print("Good Morning")
def data_access(self):
self.disp()
MyClass.wish()
c = MyClass()
c.data_access()
175 | P a g e
Python Material Mr. Ratan
def disp(self):
print(f"Emp id={self.eid} Emp name={self.ename} Emp sal= {self.esal}
Emp comp={self.comp} Emp addr={self.addr}")
e1 = Emp(111,"ratan",10000.45,"tcs","hyd")
e1.disp()
e2 = Emp(222,"anu",20000.45,"tcs","hyd")
e2.disp()
Instance variables every object memory allocated. so company, addr is duplicated for all objects.
to overcome above problem, use class variables.
class variable for all objects single memory created. it means for all object one copy of company,
address is created.
def disp(self):
print(f"Emp id={self.eid} Emp name={self.ename} Emp sal= {self.esal} Emp
comp={Emp.comp} Emp addr={Emp.addr}")
e1 = Emp(111,"ratan",10000.45)
e1.disp()
e2 = Emp(222,"anu",20000.45)
e2.disp()
Note: instance variables every object separate memory created whereas static variables
irrespective of object creation, for all objects single copy created.
176 | P a g e
Python Material Mr. Ratan
ex: Assignment
class Customer :
name pname pcost pquantity storename addr sgst
instance : status()
calculate the bill
bill>200 : print Good Cust
print all the details
bill<200 : print very good customer
print all the details
__str__ : to return the data
Ans :
class Customer:
storename,addr,sgst = "D-mart","hyderabad",3
def __init__(self,name,pname,pcost,pquantity):
self.name = name
self.pname = pname
self.pcost = pcost
self.pquantity = pquantity
def status(self):
b = self.pcost*self.pquantity+Customer.sgst
if b>200:
print("Good Customer")
print(self.__str__())
else:
print("very Good customer")
print(self.__str__())
def __str__(self):
return f"{self.name} {self.pname} {self.pcost} {self.pquantity}
{Customer.storename} {Customer.addr} {Customer.sgst}"
c1 = Customer("ratan","pen",30,5)
c1.status()
c2 = Customer("anu","pencil",40,8)
c2.status()
177 | P a g e
Python Material Mr. Ratan
class MyClass:
name = "ratan" # calss variable
def disp(self):
print(MyClass.name)
print(self.name)
c = MyClass()
c.disp()
print(MyClass.name)
print(c.name)
class MyClass:
def __init__(self):
self.num = 10 # instance variable
def disp(self):
print(self.num)
c = MyClass()
c.disp()
print(c.num)
178 | P a g e
Python Material Mr. Ratan
def __init__(self):
print("constructor")
self.num = 100
def __str__(self):
return "ratanit.com"
def __del__(self):
print("object destoryed....")
c = MyClass()
print(MyClass.a)
print(c.num)
c.m1()
MyClass.wish("ratan")
print(c)
del c
E:\>python first.py
constructor
10
100
m1 Method
Good morning.... ratan
ratanit.com
object destoryed....
179 | P a g e
Python Material Mr. Ratan
class Student:
colg,univer,addr = "swaran","JNTUK","godava"
def __init__(self,id,name,marks):
self.id = id
self.name = name
self.marks = marks
def __str__(self):
return f"{self.id} {self.name} {self.marks} {Student.colg} {Student.univer}
{Student.addr}"
s1 = Student(111,"ratan",98)
print(s1)
s2 = Student(222,"anu",97)
print(s2)
in above example we print the object it calls __str__ it returns the emp data.
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def __str__(self):
return "Name : {0} Salary: {1}".format(self.name,self.salary)
emp2.displayCount()
180 | P a g e
Python Material Mr. Ratan
s = Student(111,"sai",23)
print(getattr(s,"id"))
print(getattr(s,"name"))
print(getattr(s,"age"))
setattr(s,"age",26)
print(getattr(s,"age"))
print(hasattr(s,"id"))
print(hasattr(s,"marks"))
ex:
class Customer:
def __init__(self,name,bal=0.0):
self.name=name
self.bal=bal
def deposit(self,amount):
self.bal=self.bal+amount
def withdraw(self,amount):
if amount>self.bal:
raise RuntimeError("withdraw amount is more than balance")
else:
self.bal=self.bal-amount
def remaining(self):
return self.bal;
c = Customer("ratan",10000)
damt = int(input("enter amount to deposit"))
c.deposit(damt)
print(c.remaining())
181 | P a g e
Python Material Mr. Ratan
def disp(self):
print("hi students")
@staticmethod
def wish():
print("Good Morning")
def __str__():
return "nareshit"
c = MyClass("ratan","addanki")
print(c.__dict__) # to get the instance variable
print(MyClass.__dict__) # to get the complete class data in the form of dict
print(MyClass.__doc__) # to get the doc string of class
print(MyClass.__name__) # to get the name of the class
print(MyClass.__module__) # to get the module of the class
E:\>python first.py
{'fname': 'ratan', 'lname': 'addanki'}
{'__module__': '__main__', '__doc__': '\n\tinstance & static methods \n\tprinting
messages\n\t', 'num': 10, '__init__': <function MyClass.__init__ at 0x00000285822A5CA8>,
'disp': <function MyClass.disp at 0x00000285822A5D38>, 'wish': <staticmethod object at
0x00000285822B2308>, '__str__': <function MyClass.__str__ at 0x00000285822A5E58>,
'__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__'
of 'MyClass' objects>}
MyClass
__main__
182 | P a g e
Python Material Mr. Ratan
def disp(self):
print(f"{MyClass.num1} {MyClass.num2} {MyClass.num3} {self.fname} {self.lname}")
c = MyClass("ratan","addanki")
print(dir(c)) # it prints complete data both instance & static
print(dir(MyClass)) # it prints only static data
E:\>python first.py
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '__weakref__', 'disp', 'fname', 'lname', 'mum3', 'num1', 'num2']
{'__module__': '__main__', 'num1': 10, 'num2': 20, 'mum3': 30, '__init__': <function MyClass.__init__ at
0x000002B58A995B88>, 'disp': <function MyClass.disp at 0x000002B58A995C18>, '__dict__': <attribute
'__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
'__doc__': None}
183 | P a g e
Python Material Mr. Ratan
c = MyClass("ratan","addanki")
print("Instance variables.....")
for attribute, value in c.__dict__.items():
print(attribute, '=', value)
print("Static variables.....")
for attribute, value in MyClass.__dict__.items():
if attribute[:2]!="__":
print(attribute, '=', value)
E:\>python first.py
Instance variables.....
fname = ratan
lname = addanki
Static variables.....
num1 = 10
num2 = 20
mum3 = 30
184 | P a g e
Python Material Mr. Ratan
OOPS: Inheritance
Classic class declaration not inheriting form any class. In python 2.7
class MyClass: # Don't inherit from anything.
While new-style classes inherit from either object or some other class. In python 3.x
class MyClass(object): # Inherit from object, new-style class.
2. object creation
Possible to create the object of both parent & child classes.
But it is recommended to create the object of child class because using child reference we can
access both parent & child properties.
a = A()
a.func1 a.func2
b = B()
b.func1 b.func2 b.func3 b.func4
c = C()
c.func1 b.func2 b.func3 b.func4 b.func5 c.func6
185 | P a g e
Python Material Mr. Ratan
4. To check the type of the object use : isinstance() it returns Boolean value
class A:
pass
class B(A):
pass
class C(B):
pass
a = A()
b = B()
c = C()
print(isinstance(a,object))
print(isinstance(b,object))
print(isinstance(c,object))
print(isinstance(b,A))
print(isinstance(c,A))
print(isinstance(c,B))
print(isinstance(a,C))
print(isinstance(b,C))
186 | P a g e
Python Material Mr. Ratan
5. Type of inheritance.
class A: A
pass |
class B(A): B
pass
2. multi-level:
class A: A
pass |
class B(A): B
pass |
class C(B): C
pass
class A:
pass
class B: A B
pass \/
class C(A,B): C
pass
187 | P a g e
Python Material Mr. Ratan
ex-1: using child class object we can access both parent & child data.
class Parent:
def m1(self):
print("Parent class m1")
class Child(Parent):
def m2(self):
print("Child class m2")
p = Parent()
p.m1()
c = Child()
c.m1()
c.m2()
c = Child()
c.add(1000,2000)
class Child(Parent):
num1,num2 = 100,200
def add(self,num1,num2):
print(num1+num2)
print(self.num1+self.num2)
print(super().num1+super().num2)
c = Child()
c.add(1000,2000)
188 | P a g e
Python Material Mr. Ratan
case 1 : child class & parent class having different method names.
class Parent:
def m2(self):
print("Parent class m1")
class Child(Parent):
def m1(self):
print("Child class m1")
def data_access(self):
self.m1()
self.m2()
c = Child()
c.data_access()
case 2: child class & parent class having same method names.
class Parent:
def m1(self):
print("Parent class m1")
class Child(Parent):
def m1(self):
print("Child class m1")
def data_access(self):
self.m1()
super().m1()
c = Child()
c.data_access()
189 | P a g e
Python Material Mr. Ratan
c = C()
case 2: call the super class constructor using class-name: first argument must be self
class A:
def __init__(self):
print("A class constructor")
class B(A):
def __init__(self):
A.__init__(self)
print("B class constructor")
class C(B):
def __init__(self):
B.__init__(self)
print("C class constructor")
c = C()
Note:
we can call the super class constructors in two ways
1. using super() keyword : direct call
super().__init__()
2. using class name : the first argument must be self
Parent.__init__(self)
190 | P a g e
Python Material Mr. Ratan
ex-1:
case 1: two classes without relation.
class Person:
def __init__(self,first_name,last_name,email):
self.first_name = first_name
self.last_name = last_name
self.email = email
def __str__(self):
return f"Fist name:{self.first_name} Last Name:{self.last_name} Person email:{self.email}"
class Emp:
def __init__(self,first_name,last_name,email,eid,esal):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.eid = eid
self.esal = esal
def __str__(self):
return f"{self.first_name} {self.last_name} {self.email} {self.eid} {self.esal}"
p = Person("addanki","ratan","ratna5256@gmail.com")
print(p)
e = Emp("anu","dasari","anu@gmail.com",123,10000.45)
print(e)
class Emp(Person):
def __init__(self,first_name,last_name,email,eid,esal):
#super().__init__(first_name,last_name,email)
Person.__init__(self,first_name,last_name,email)
self.eid = eid
self.esal = esal
def __str__(self):
return f"{super().__str__()} {self.eid} {self.esal}"
p = Person("ratan","addanki","ratan@gmail.com")
print(p)
e = Emp("anu","dasari","anu@gmail.com",222,100000.45)
print(e)
191 | P a g e
Python Material Mr. Ratan
ex-2: Assignment.
write the example
case 1 : without relation
case 2 : with relation
class Student:
first_name,last_name,school_name:
__str__ : to return the data
class Teacher(Student):
first_name,last_name,school_name,subject,pay:
__str__ : to return the data
class Teacher(Student):
def __init__(self,first_name,last_name,school_name,subject,pay):
super().__init__(first_name,last_name,school_name)
self.subject = subject
self.pay = pay
def __str__(self):
return f'{super().__str__()} {self.subject} {self.pay}'
192 | P a g e
Python Material Mr. Ratan
#addr.py
class Address:
def __init__(self,dno,street,state):
self.dno = dno
self.street = street
self.state = state
#movies.py
class MovieTypes:
def __init__(self,tmov,bmov):
self.tmov = tmov
self.bmov = bmov
#hero.py
from addr import Address
from movies import MovieTypes
class Hero:
def __init__(self,name,age,height,addr,mtypes):
self.name = name
self.age = age
self.height = height
self.addr = addr
self.mtypes = mtypes
def __str__(self):
return f"{self.name} {self.age} {self.height} " \
f"\n{self.addr.dno} {self.addr.street} {self.addr.state}" \
f"\n {self.mtypes.tmov} {self.mtypes.bmov} "
193 | P a g e
Python Material Mr. Ratan
ex -4:
#family.py
class Parent:
def __init__(self,fname,mname):
self.fname=fname
self.mname=mname
#progess.py
class Marks:
def __init__(self,m1,m2,m3):
self.m1=m1
self.m2=m2
self.m3=m3
#location.py
class Address:
def __init__(self,street,state,pin,country):
self.street=street
self.state=state
self.pin=pin
self.country=country
#student.py
from family import Parent
from progess import Marks
from location import Address
class Student:
def __init__(self,sid,sname,schoolname,parents,marks,addr):
self.sid=sid
self.sname=sname
self.schoolname=schoolname
self.parents=parents
self.marks=marks
self.addr=addr
def __str__(self):
return f"student id={self.sid} Student Name={self.sname} School Name={self.schoolname}"\
f"\n Father Name={self.parents.fname} Mother Name={self.parents.mname}"\
f"\n Student Mrk1={self.marks.m1} Student Mrk2={self.marks.m2}
Student Mrk3={self.marks.m3}"\
f"\n Street No={self.addr.street} State Name={self.addr.state} Pin
No={self.addr.pin} Country Name={self.addr.country}"
194 | P a g e
Python Material Mr. Ratan
OOPS: polymorphism
class Parent:
def properties(self):
print("money + land + gold +cars...")
def mrg(self):
print("very black girl....")
class Child(Parent):
def mrg(self):
print("kajal......")
#data access
c = Child()
c.properties()
c.mrg()
195 | P a g e
Python Material Mr. Ratan
ex-2:
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
polymorphic functions:
The function can take different types of input data it will give proper result.
Depends on client input we are executing specific data.
Here different clients can pass different type of input data.
ex 3: assignment
class unicorn:
speed()
milage()
class CBZ:
speed()
milage()
client can pass either unicorn obj or cbz obj access the data.
196 | P a g e
Python Material Mr. Ratan
add(10)
add(10,20)
add(10,20,30)
print(type(10))
print(type(10.5))
print(type("ratan"))
print(type([10,20,30]))
print(sum([10,20,30]))
print(sum((1,2,3)))
print(min("ratan"))
print(min([10,20,30]))
print(min((1,2,4)))
print(max("ratan"))
print(max([10,20,30]))
print(max((1,2,4)))
197 | P a g e
Python Material Mr. Ratan
ex:
case 1: Here every class contains constructor.
class TextDoc:
def __init__(self,name):
self.name = name
def show(self):
print("this is text doc impl...",self.name)
class PdfDoc:
def __init__(self, name):
self.name = name
def show(self):
print("this is PDF doc impl...", self.name)
class WordDoc:
def __init__(self, name):
self.name = name
def show(self):
print("this is word doc impl...", self.name)
case 2: Here declaring the constructor in one class that constructor used in multiple classes.
class TextDoc:
def __init__(self,name):
self.name = name
def show(self):
print("this is text doc impl...",self.name)
class PdfDoc(TextDoc):
def show(self):
print("this is PDF doc impl...", self.name)
class WordDoc(TextDoc):
def show(self):
print("this is word doc impl...", self.name)
objects = [TextDoc("sample.txt"),PdfDoc("sample.pdf"),WordDoc("sample.word")]
for x in objects:
data_access(x)
198 | P a g e
Python Material Mr. Ratan
Normal methods:
Normal methods contain method declaration & implementation.
def disp(self):
print("Good Morning")
Abstract methods:
The abstract method contains only method declaration but not implementation.
To represent your method is a abstract use @abstractmethod.
@abstractmethod
def disp(self):
pass
Abstract class:
The abstract classes are used to declare the functionalities of project. The abstract class contains
one or more abstract methods.
To make your class is abstract class, your class must extends ABC class. And ABC is a class
present in abc module so import the abc module using import statement.
project level:
step 1: Declare the functionalities : using abstract classes
step 2: Later write the implementation : using business classes
199 | P a g e
Python Material Mr. Ratan
a. If the abstract class contains abstract method write the implementations in child classes.
b. One abstract class contains multiple implementations classes.
c. for the abstract classes object creations are not possible.
ex 2:
from abc import ABC,abstractmethod
class Bike(ABC):
@abstractmethod
def speep(self):
pass
@abstractmethod
def milage(self):
pass
class unicorn(Bike):
def speep(self):
print("unicorn speed 150kmph.....")
def milage(self):
print("unicorn milage 50kmpl")
class cbz(Bike):
def speep(self):
print("cbz speed 200kmph.....")
def milage(self):
print("cbz milage 40kmpl")
#Data Access
u = unicorn()
u.speep()
u.milage()
c = cbz()
c.speep()
c.milage()
200 | P a g e
Python Material Mr. Ratan
class Dev1(MyClass):
def add(self,num1,num2):
print(num1+num2)
class Dev2(Dev1):
def mul(self,num1,num2):
print(num1*num2)
#m = MyClass() TypeError: Can't instantiate abstract class MyClass with abstract methods add, mul
# d = Dev1() TypeError: Can't instantiate abstract class Dev1 with abstract methods mul
d = Dev2()
d.add(10,20)
d.mul(4,5)
MyClass is an abstract class contains 2-abstarct method so object creation not possible.
Dev1 one implementation completed(add) & one abstract method (mul) so object creation not possible.
Dev2 here all implementations are completed so Dev2 is normal class so we can create the object.
ex-4: Assignment
from abc import ABC,abstractmethod
class MyClass(ABC):
@abstractmethod
def login(self,username,password):
pass
@abstractmethod
def wish(self,name):
pass
@abstractmethod
def add(self,num1,num2):
pass
class Dev1(MyClass):
def login(self,username,password):
if username=="ratan" and password=="anu":
return "Login Success"
else:
return "Login Fail"
201 | P a g e
Python Material Mr. Ratan
class Dev2(Dev1):
def wish(self,name):
return f"Good Morning....{name}"
def add(self,num1,num2):
return f"Additionof two nums:{num1+num2}"
d = Dev2()
status = d.login("ratan","anu")
print(status)
print(d.wish("ratan"))
res = d.add(10,20)
print(res)
ex 5:
from abc import ABC,abstractmethod
class Party(ABC):
@abstractmethod
def eat(self):
pass
def comman_eat(self):
print("sweet+ice cream + fruits + water...")
class Veg(Party):
def eat(self):
print("veg biryani,rice and dal panner chapati....etc")
class NonVeg(Party):
def eat(self):
print("chicken , mutton prawns ....etc")
v = Veg()
v.eat()
v.comman_eat()
non = NonVeg()
non.eat()
non.comman_eat()
To give the command functionality to all implementation classes declare that functionality in
abstract class.
In abstract class possible to declare the normal methods & these methods are commonly shared
by all implementation classes.
202 | P a g e
Python Material Mr. Ratan
a = Add(10)
a.disp()
b = Mul(5)
b.disp()
ex:
from abc import ABC,abstractmethod
class Operations:
def __init__(self,num1,num2):
self.num1 = num1
self.num2 = num2
@abstractmethod
def ope(self):
pass
class Addition(Operations):
def ope(self):
print(self.num1 + self.num2)
class Multiplication(Operations):
def ope(self):
print(self.num1 * self.num2)
add = Addition(10,20)
add.ope()
mul = Multiplication(10,20)
mul.ope()
203 | P a g e
Python Material Mr. Ratan
OOPS: Encapsulation
Encapsulation introduction:
The process of binding the data is called encapsulation.
The process of wrapping methods & data as single unit is called encapsulation.
ex :
class is an encapsulation mechanism because class binding methods & variables as a single unit.
module is an encapsulation mechanism because the module is binding classes, variables, functions.
we will achieve encapsulation using private modifiers. the private data can be accessed only with
in the class. it means other clients unable to access the data & modify the data.
The main objective of encapsulation is security.
def set_name(self,name):
self.__name = name
def set_cost(self,cost):
self.__cost = cost
def set_quantity(self,quantity):
self.__quantity = quantity
def get_name(self):
return self.__name
def get_cost(self):
return self.__cost
def get_quantity(self):
return self.__quantity
#financeclient.py
from salesinfo import Sales
s = Sales("pen",10,3)
#initial data
print(f"Pen name:{s.get_name()} Pen cost:{s.get_cost()} Pen quantity:{s.get_quantity()}")
204 | P a g e
Python Material Mr. Ratan
s.set_cost(15)
s.set_quantity(7)
#after modify
print(f"Pen name:{s.get_name()} Pen cost:{s.get_cost()} Pen quantity:{s.get_quantity()}")
a. Every property must contains one pair of setter & getter methods. Depends on the required the
client can access specific setter or getter methods.
b. Sales team contains private data we use only with in the class it means other clients (finance
team) unable to access the data & modify the data. But other clients (finance team) can do the
modifications on private data with the help of setters & get the private data using getter
methods.
c. we can assign the data to properties in two ways,
a. constructors : we have to assign all values.
b. setter methods : setters to set the specific values. (updating the particular values)
205 | P a g e
Python Material Mr. Ratan
As your program gets longer, you may want to split it into several files for easier maintenance. To
support this, Python has a way to put definitions in a file and use them in a script or in an interactive
instance of the interpreter. Such a file is called a module.
Splitting of a big single python program into separate python modules helps us in many ways like;
o It becomes easy to read the code and understand it.
o Maintenance of neatly grouped code is easy.
o Python module makes easy re-usability of frequently used code. We can group frequently
used code into a module. So next time instead of copying the actual code definition into a
program, we can just import the module.
python file is called module. The module names all characters are lower case & should be short
names.
Whenever we are using other module data then import that module using import statement.
Note: it is possible to import the multiple modules in single line of import but it is not recommended.
# valid recommended
import first
import second
206 | P a g e
Python Material Mr. Ratan
207 | P a g e
Python Material Mr. Ratan
#second.py
class Student:
instance method : wish() : Good Morning
static method : disp() : HI ratan sir
#client.py
normal import access the data
print global var
call the add function
call the student data : one instance & static method accessing
from import access the data
print global var
call the add function
call the student data :one instance & static method accessing
Ans:
#first.py #second.py
val1 , val2 = 10, 20 class Student:
def add(num1,num2): def wish(self):
print(num1+num2) print("good morning")
print(val1+val2) @staticmethod
def disp():
print("Hi ratan sir")
#client.py
import first
import second
print(first.val1)
print(first.val2)
first.add(40,10)
f=second.Student()
f.wish()
second.Student.disp()
208 | P a g e
Python Material Mr. Ratan
class Food:
@staticmethod
def disp():
print("idli dosa puri.......")
class Fruits:
def disp(self):
print("mango apple banana.......")
#client.py
import operations
print(dir(operations))
E:\>python client.py
['Food', 'Fruits', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'mul', 'name1', 'name2']
Note: To check the variables, functions, classes present in operations module use dir() function.
The function starts with two underscores & ends with two underscores is called magic function.
Before the magic functions the data is : classes
After magic functions the data is : functions,varaibles
E:\>python client.py
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__',
'__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'disp']
209 | P a g e
Python Material Mr. Ratan
#client.py
#Access the data using complete name of the module
import operations
operations.add(10,20)
operations.mul(3,4)
210 | P a g e
Python Material Mr. Ratan
#operations.py
def add(num1,num2):
print(num1+num2)
def mul(num1,num2):
print(num1*num2)
#opeclient.py
from operations import add,mul #global import
class Myclass:
def my_func1(self):
add(10,20)
mul(3,4)
def my_func2(self):
add(10,20)
mul(3,4)
c = Myclass()
c.my_func1()
c.my_func2()
in above example we are using local import for my_func1 so we can access the operations
module data only in my_func1 but we cannot access the data in other functions like my_func2.
211 | P a g e
Python Material Mr. Ratan
ex-7: Assignment
#first.py
class Emp:
during object creation initialize the data : eid ename esal
print the data using __str__
#second.py
class Student:
during object creation initialize the data : sid sname smarks
print the data using __str__
#client.py
user normal import
use from import to access the data
Ans :
#first.py
class Emp:
def __init__(self, eid, ename):
self.eid = eid
self.ename = ename
def __str__(self):
return f"Emp id :{self.eid} Emp name:{self.ename}"
#second.py
class Student:
def __init__(self, rollno, name):
self.rollno = rollno
self.name = name
def __str__(self):
return f"Emp id :{self.rollno} Emp name:{self.name}"
#client.py
import first
import second
e = first.Emp(111,"ratan")
print(e)
s = second.Student(1,"anu")
print(s)
212 | P a g e
Python Material Mr. Ratan
Packages
ex-1: packages first example.
services
|-->operations.py
|-->message.py
model
|-->first.py
|-->second.py
client
|--> ratan.py
|--> anu.py
services.operations.add(10,20) add(10,20)
services.operations.mul(5,6) mul(4,5)
services.message.wish("ratan") wish("ratan")
model.first.first_disp() first_disp()
model.second.second_disp() second_disp()
213 | P a g e
Python Material Mr. Ratan
client
|-->ratan.py : access the data using normal import
|-->anu.py : access the data using from import
services.laptop.hp.hp_info() hp_info()
services.laptop.dell.dell_info() dell_info()
services.mobile.apple.apple_info() apple_info()
services.mobile.oneplus.oneplus_info() oneplus_info()
services.generalservice.general_info() general_info()
214 | P a g e
Python Material Mr. Ratan
|-->generaloffer.py
class General:
def general_info(): static print the message
loans [main package]
|--> personal.py
class PersonalLoan
def loan_info(): instance method : print("13%")
|-->home.py
class HomeLoan
def loan_info(): static method : print("7%")
215 | P a g e
Python Material Mr. Ratan
Modifiers in python:
a. public modifier
In python our data is by default public
public is for : classes , functions , variables.
public Permission : All packages can access the data.
class MyClass:
num = 10
def disp(self):
pass
b. private modifier
In python to represent private use two underscores : __num = 10
Private is for : variables , functions
Private Permission : only with in the class even child cannot access the parent private data.
class Parent:
__num = 100
def disp(self):
print(self.__num) # Here we can access with in the class
class Child(Parent):
def my_func(self):
print(self.__num) # error : outside of the class
c = Child()
c.disp()
c.my_func()
c. protected modifier
To represent protected use one underscores : _num = 10
Protected is for : variables , functions
what is the Permission of protected & write one example : assignment
216 | P a g e
Python Material Mr. Ratan
Predefined modules
1. names module:
install the names module using pip command
pip install names
case-1:
import names
for x in range(10):
print(names.get_first_name())
for x in range(10):
print(names.get_last_name())
for x in range(10):
print(names.get_full_name())
for x in range(10):
print(f"{names.get_first_name()}.{names.get_last_name()}@gmail.com")
case 2:
import names
print(names.abspath("abc.txt")) #this method returns the complete path of the file
print(names.dirname("G:/pnames/gt/first.py"))
print(names.join('E:/python/','list.py'))
G:\pnames>python first.py
G:\pnames\abc.txt
G:/pnames/gt
E:/python/list.py
217 | P a g e
Python Material Mr. Ratan
2. string module
import string
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.ascii_letters)
print(string.digits)
print(string.ascii_letters+string.digits)
print(type(string.ascii_lowercase))
print(type(string.ascii_letters))
print(type(string.digits))
print(string.octdigits)
print(string.hexdigits)
E:\>python first.py
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
<class 'str'>
<class 'str'>
<class 'str'>
01234567
0123456789abcdefABCDEF
Hi Ratan Sir
218 | P a g e
Python Material Mr. Ratan
3. random module
case 1:
import random
#both functions will give decimal values
print(random.random()) # 0.0 to 1.0
print(random.uniform(2,8)) # specific range
random : it will give the random decimal value between 0.0 to 1.0.
uniform : it will give the decimal value between range.
randint : it will give the random int value between range.
randrange : it will give the random value based on start,end,stepping.
case 2:
import random
import string
print(random.choice(["ratan","anu",10,20]))
print(random.choices(["rat","anu","aaa"],k=2))
print(random.sample(["rat","anu","aaa"],2))
if the input list length is 3 but if we want 8 elements it will give the data.
print(random.choices(["rat","anu","aaa"],k=8))
G:\>python first.py
['anu', 'anu', 'anu', 'rat', 'anu', 'rat', 'anu', 'aaa']
if we pass the number of choices in negative value we will get empty list.
print(random.choices(["rat","anu","aaa"],k=-2))
G:\>python first.py
[]
219 | P a g e
Python Material Mr. Ratan
if the input list length is 3 but if we want 8 elements we will get ValueError.
print(random.sample(["rat","anu","aaa"],k=8))
G:\>python first.py
ValueError: Sample larger than population or is negative
import string
import random
print("".join(random.choices(string.ascii_letters+string.digits,k=5)))
case 5:
mylist = ["apple", "banana","orange"]
random.shuffle(mylist)
print(mylist)
220 | P a g e
Python Material Mr. Ratan
4. math module
import math
print(math.ceil(30.1))
print(math.floor(30.9))
print(math.factorial(4))
print(math.pow(3,4))
print(math.sqrt(4))
print(math.sin(90))
print(math.cos(90))
print(math.pi)
print(math.e)
E:\>python first.py
31
30
24
81.0
2.0
0.8939966636005579
-0.4480736161291701
3.141592653589793
2.718281828459045
20.085536923187668
221 | P a g e
Python Material Mr. Ratan
5. sys module
case 1: Taking command line arguments at runtime. the command line argument separator is space.
import sys
print(sys.argv)
E:\>python first.py 10 20 30 40
['first.py', '10', '20', '30', '40']
ex-2: taking command line arguments at runtime & passing to function arguments.
import sys
def add(a,b):
print(a+b)
def sub(a,b):
print(a-b)
def mul(a,b):
print(a*b)
if __name__ == "__main__":
add(int(sys.argv[1]),int(sys.argv[2]))
sub(int(sys.argv[1]),int(sys.argv[2]))
mul(int(sys.argv[1]),int(sys.argv[2]))
Note :
if we are not declaring __name__ == __main__ in this case execution starts from function calling.
if we are declaring __name__ == __main__ in this case execution starts from main.
E:\>python first.py 3 6
9
-3
18
E:\>python first.py 3 6 5 6 7
222 | P a g e
Python Material Mr. Ratan
9
-3
18
Note: To take the space in command line arguments take that argument in double quotes.
case 5:
import sys
print(sys.base_prefix) #gives the python installation path.
print(sys.builtin_module_names) #gives all predeined modules.
print(sys.executable) #gives path and executable file name for the Python interpreter.
print(sys.is_finalizing())#Return True if the Python interpreter is shutting down,False otherwise.
223 | P a g e
Python Material Mr. Ratan
ex : os module
import os
os.rename("sample.txt","ratan.txt")
os.remove("ratan.txt")
os.mkdir("new")
os.chdir("data")
print(os.getcwd())
os.rmdir("new")
ex 3: statistics module
import statistics
print(statistics.mean([2,5,6,9]))
print(statistics.median([1,2,3,8,9]))
print(statistics.median([1,2,3,7,8,9]))
print(statistics.mode([2,5,3,2,8,3,9,4,2,5,6]))
print(statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5]))
ex: datetime
import datetime
dt = datetime.datetime.now()
print (dt)
today = datetime.date.today()
print(today)
res = datetime.datetime.now().strftime("%H:%M:%S")
print(res)
224 | P a g e
Python Material Mr. Ratan
import time
print("hi sir")
time.sleep(2)
print("hi sir")
print(time.strftime('%a'))
print(time.strftime('%A'))
print(time.strftime('%b'))
print(time.strftime('%B'))
print(time.strftime('%c'))
print(time.strftime('%d'))
print(time.strftime('%H'))
print(time.strftime('%j'))
print(time.strftime('%m'))
print(time.strftime('%M'))
print(time.strftime('%X'))
print(time.strftime('%Z'))
print(time.strftime('%p'))
print(time.strftime('%X%p %a %x %Z '))
225 | P a g e
Python Material Mr. Ratan
for p in itertools.permutations('ABC'):
print(p)
for p in itertools.permutations('ABCD'):
print(p)
for p in itertools.permutations('12'):
print(p)
for p in itertools.permutations('123'):
print(p)
print(list(itertools.combinations([1,2,3],2)))
#But here different type of data we can not combine using + : so use chain() function to print
list_data = [12.3, 2.5, 34.13]
tuple_data = ('cpp', 'Python', 'Java')
set_data = {1,2,3}
for x in chain(list_data,tuple_data,set_data):
print(x)
226 | P a g e
Python Material Mr. Ratan
Ex : zipfile module
case 1: write the files to zip
from zipfile import ZipFile
zf = ZipFile('ratan.zip', mode='w')
zf.write("ramu.txt")
zf.write("anu.txt")
zf.write("abc.txt")
print("Zip file is creates")
case 2: Assignment
from zipfile import ZipFile
zf = ZipFile('ratan.zip', mode = 'r')
res = zf.read("abc.txt")
print(res)
res1 = zf.read("ramu.txt")
print(res1)
227 | P a g e
Python Material Mr. Ratan
Multithreading
228 | P a g e
Python Material Mr. Ratan
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of
the other threads of the process; changes to the parent process does not effect child
processes.
229 | P a g e
Python Material Mr. Ratan
Note : thread, threading modules present in python 2.7 but python 3.x support only threading module.
#Multithreading :
create the multiple threads run the threads parallel.
230 | P a g e
Python Material Mr. Ratan
ex-1:
# importing the threading module
import threading
def print_square(num):
print("Square:",num * num)
def print_cube(num):
print("Cube: ",num * num * num)
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
ex 2: from import : we can access the Thread class directly without using module name.
from threading import Thread
def add(num1,num2):
print("Addition:",num1+num2)
t1 = Thread(target=add,args=(10,20))
t1.start()
231 | P a g e
Python Material Mr. Ratan
ex 3: Main Thread
a. Once the application starts one thread will starts automatically is called main thread.
b. To represent current thread use currentThread()
c. To get the name of the current thread use getName().
import threading
print(threading.currentThread().getName())
t1 = Thread(target=add,args=(10,20))
print(t1) # Initial state
t1.start()
print(t1) # started state
time.sleep(1)
print(t1) # stopped state
E:\>python first.py
<Thread(Thread-1, initial)>
Addition: 30
<Thread(Thread-1, started 6176)>
<Thread(Thread-1, stopped 6176)>
t = threading.Thread(target=disp)
t.start()
t.start() #RuntimeError: threads can only be started once
232 | P a g e
Python Material Mr. Ratan
t2 = threading.Timer(10,disp)
t2.start()
ex 7: ThreadSchedular.
from threading import Thread
def disp1(name):
for x in range(10):
print("Good Morning......",name)
def disp2(name):
for x in range(10):
print("Good Evening......",name)
t1 = Thread(target=disp1,args=("ratan",))
t2 = Thread(target=disp2,args=("anu",))
t1.start()
t2.start()
if the application contains more than one thread then thread execution decided by
ThreadSchedular.
ThreadSchedular is unexpected behavior so multi-threaded example we will get unexpected
output(run to run output will be changed.)
Note : multi-threading is important to design gaming application where multiple objects are
moving at a time.
def sleeper(i):
print(f"thread {i} sleeps for 5 seconds")
time.sleep(5)
print(f"thread {i} woke up")
for i in range(10):
t = Thread(target=sleeper, args=(i,))
t.start()
233 | P a g e
Python Material Mr. Ratan
ex 9: join() :To stop the other threads to complete the execution of current thread use join().
import threading
import time
def print_table1(num):
for x in range(1,11):
print(f"{num} * {x} ={num*x}")
time.sleep(1)
def print_table2(num):
for x in range(1,11):
print(f"{num} * {x} ={num*x}")
time.sleep(1)
t1 = threading.Thread(target=disp,args=("python",))
t1.start()
t2 = threading.Thread(target=disp,args=("Django",))
t2.start()
E:\>python first.py
Hi students python is Good This is.. Thread-1
Hi students Django is Good This is.. Thread-2
case 2: user defined names
import threading
def disp(name):
print(f"Hi students {name} is Good This is..",threading.currentThread().getName())
t1 = threading.Thread(target=disp,args=("python",),name = "worker1")
t1.start()
t2 = threading.Thread(target=disp,args=("Django",),name = "worker2")
t2.start()
E:\>python first.py
Hi students python is Good This is.. worker1
Hi students Django is Good This is.. worker2
234 | P a g e
Python Material Mr. Ratan
ex-11 :
case 1: application without threading
import time
def sqr(n):
for x in n:
time.sleep(1)
x%2
def cube(n):
for x in n:
time.sleep(1)
x%3
n=[1,2,3,4,5,6,7,8]
s=time.time()
sqr(n)
cube(n)
e=time.time()
print(e-s)
def cube(n):
for x in n:
time.sleep(1)
x%3
n=[1,2,3,4,5,6,7,8]
start=time.time()
t1=Thread(target=sqr,args=(n,))
t2=Thread(target=cube,args=(n,))
t1.start()
t2.start()
t1.join()
t2.join()
end=time.time()
print(end-start)
235 | P a g e
Python Material Mr. Ratan
lock = threading.Lock()
t1 = Thread(target=disp,args=("ratan",))
t2 = Thread(target=disp,args=("anu",))
t1.start()
t2.start()
ex-13:
case 1 : application without thread pooling : threads recreated
import threading
import time
def disp():
print(f"running:{threading.currentThread().getName()}")
time.sleep(1)
for x in range(6):
threading.Thread(target=disp).start()
in normal approach every request thread is recreated if number of requests are increased number of
threads are increased it effects on performance
To overcome above problem, use thread pool
thread pool approach contains the pool of threads these same threads are reused by multiple
request.
case 2: application with thread pooling : threads reused
import threading
import time
import concurrent.futures
def disp():
print(f"running:{threading.currentThread().getName()}")
time.sleep(5)
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
for x in range(8):
executor.submit(disp)
236 | P a g e
Python Material Mr. Ratan
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(2)
logging.info("Thread %s: finishing", name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(filename="log.txt",format=format, level=logging.INFO,datefmt="%H:%M:%S")
def worker():
logging.debug('worker Starting {}'.format(threading.currentThread().getName()))
time.sleep(2)
logging.debug('worker Exiting {}'.format(threading.currentThread().getName()))
def my_service():
logging.debug('myservice Starting {}'.format(threading.currentThread().getName()))
time.sleep(3)
logging.debug('myservice Exiting {}'.format(threading.currentThread().getName()))
237 | P a g e
Python Material Mr. Ratan
t = MyThread()
t.start()
import threading
class MyThread(threading.Thread):
pass
t1 = MyThread(name="anu")
t1.start()
print(t1.getName())
t1.setName("ratan")
print(t1.getName())
238 | P a g e
Python Material Mr. Ratan
t2:
Good morning ....Thread-2
Good morning ....Thread-2
Good morning ....Thread-2
t3 :
Good morning ....Thread-3
Good morning ....Thread-3
Good morning ....Thread-3
import threading
import time
class MyThread(threading.Thread):
def run(self):
for x in range(3):
print(f"Good Morning : {threading.currentThread().getName()}")
time.sleep(1)
t1 = MyThread()
t2 = MyThread()
t3 = MyThread()
t1.start()
t1.join()
t2.start()
t2.join()
t3.start()
239 | P a g e
Python Material Mr. Ratan
t1 = MyThread1(name="ratan")
t1.start()
t1.join()
t2 = MyThread2(name="anu")
t2.start()
t2.join()
t3 = MyThread3(name="sravya")
t3.start()
t3.join()
print("Main Thread is completed.....")
240 | P a g e
Python Material Mr. Ratan
t1 = MyThread1(daemon=True)
t1.start()
for x in range(5):
print("main thread")
time.sleep(1)
241 | P a g e
Python Material Mr. Ratan
242 | P a g e
Python Material Mr. Ratan
JSON introduction:
Java Script Object Notation was inspired by a subset of the JavaScript programming language
dealing with object literal syntax.
json is used to store and transfer the data.
while conversion check the data types, because python data types & json data types are different.
243 | P a g e
Python Material Mr. Ratan
Conversion Table:
import json
py_data = {"name":"ratan","hobbies":("cricket","eating"),"id":111,"email":None,"status":True}
json_data = json.dumps(py_data)
print(json_data)
E:\>python first.py
{"name": "ratan", "hobbies": ["cricket", "eating"], "id": 111, "email": null, "status": true}
import json
json_data = '{"name": "ratan", "hobbies": ["cricket", "eating"], "id": 111, "email": null, "status": true}'
py_data = json.loads(json_data)
print(py_data)
E:\>python first.py
{'name': 'ratan', 'hobbies': ['cricket', 'eating'], 'id': 111, 'email': None, 'status': True}
244 | P a g e
Python Material Mr. Ratan
ex-3: After conversion of python to json data we can do the required operations on python data.
import json
x = '{ "name":"ratan", "age":30, "city":"hyderabad"}'
#load the json data
y = json.loads(x)
print(type(y))
#reading the json data
print(y["age"],y['city'],y['name'])
print(y.values())
print(y.keys())
ex-4: Here we are printing json data in proper format: indent & sort keys
import json
py_data = {"name":"ramu",
"age":30,
"married":True,
"divorced":False,
"childrens":('raju','rani'),
"pets":None,
"hobbies":['cricket',"music"]}
json_data = json.dumps(py_data,indent=4,sort_keys=True)
print(json_data)
ex-5: Assignment
json_data = '{"stu_id":"ABC123","status" :true,"marks":[10,79,30],
"teachers":[{"good":["ratan","anu"],"bad":["ramesh","mahesh"]}]}'
convert json to python
a. check the total marks>150 : pass or fail
b. print good teachers : ratan anu
Ans :
import json
json_data =
'{"stu_id":"ABC123","marks":[50,60,30],"teachers":[{"good":["ratan","anu"],"bad":["ramesh","mahesh"]}]}'
py_data = json.loads(json_data)
total_marks = sum(py_data["marks"])
245 | P a g e
Python Material Mr. Ratan
ex 6: Assignment
import json
json_data = '{"emp_name":"ratan","email":"ratan@hotmail.com","status":true,
"profile":[{"title1":"temlead","title2":"sr Developer"}]}'
convert json to python
a. print the email domain name : hotmail
b. print the: teamlead
Ans:
import json
json_data = '{"emp_name":"ratan","email":"ratan.anu@hotmail.com",
"profile":[{"title1":"temlead","title2":"sr Developer"}]}'
py_data = json.loads(json_data)
mail = py_data["email"]
print(mail[mail.index("@")+1:mail.rindex(".")])
print(py_data["profile"][0]['title1'])
ex7: convert python to json data writing the json data to json file
import json
data = {"mobile":9009,"hobbies":('cric','music'),"email":None,"status":True}
f = open("sample.json","w")
f.write(json.dumps(data))
f.close()
print("file operations are completed.....")
246 | P a g e
Python Material Mr. Ratan
Rest APIs
Introduction:
To use an API, you make a request to a remote web server, and retrieve the data you need.
REST API (Representational state transfer) is an API that uses HTTP requests for communication with
web services.
Every Rest API contains url to access that service.
Rest APIs means we are designing a service at serverside it will take the input & produce the output in
different formats such as,
o String
o Xml
o Json
o yaml
To use an API, you make a request to a remote web server, and retrieve the data you need.
But why use an API instead of a static CSV dataset you can download from the web? APIs are useful in the
following cases:
There are many different types of requests. The most commonly used one, a GET request, is used
to retrieve data.
Use GET requests to retrieve resource representation/information only and not to modify it in
any way. As GET requests do not change the state of the resource.
247 | P a g e
Python Material Mr. Ratan
248 | P a g e
Python Material Mr. Ratan
when we send the request to service the service will take the request & process the request and it
will give the response with status code values.
400 – Bad Request. The server cannot process the request because(incorrect request format).
401 – Unauthorized. Occurs when authentication was failed, due to incorrect credentials or even
their absence.
403 – Forbidden. Access to the specified resource is denied.
404 – Not Found. The requested resource was not found on the server.
405 - Method not allowed
To check complete information about http status code use below website.
https://httpstatuses.com/
249 | P a g e
Python Material Mr. Ratan
250 | P a g e
Python Material Mr. Ratan
2. using postman tool : this tool is used to test API : this is API testing tool.
download the postman: https://www.postman.com/downloads/
just install the postman
open the post man
click on +
select the request type[get,post,put...] & type the url
send the request see the response message
import requests
res = requests.get("http://api.open-notify.org/astros.json")
if res.status_code==200:
data = res.json()
print(data)
print(data['message'])
print(data['people'])
else:
print("data is empty....not successfull",res.status_code)
in above example the data coming in the from dict so we no need to convert json to python.
in above example check the response by giving both corrent & incorrent API url.
251 | P a g e
Python Material Mr. Ratan
#producing API :
ex-1: creating get service.
@app.route('/gettest',methods=["GET"])
def hello_string():
return 'Hello World!'
@app.route('/getjson',methods=["GET"])
def hello_json():
return jsonify({"status":"Good Morning"})
@app.route('/test/<int:num>',methods=["GET"])
def hello_mul(num):
return jsonify({"Result":num*10})
http://127.0.0.1:5000/getjson
{"status":"Good Morning"}
http://127.0.0.1:5000/test/10
{"Result":100}
252 | P a g e
Python Material Mr. Ratan
app = Flask(__name__)
@app.route('/test',methods=["POST"])
def post_world():
data = request.get_json()
if data['username']=="ratan" and data['password']=="anu":
return jsonify({"Result":"Login Success"})
else:
return jsonify({"Result":"Login Fail"})
@app.route('/testope',methods=["POST"])
def operations():
data = request.get_json()
add = data['num1'] + data['num2']
mul = data['num1'] * data['num2']
return jsonify({"Addition":add,"Multiplication":mul})
if __name__ == '__main__':
app.run()
http://127.0.0.1:5000/posttest
test the above url using post man by passing json input.
body ----> raw--->select json
{ "username":"ratan",
"password":"anu"
}
http://127.0.0.1:5000/testope
test the above url using post man by passing json input.
body ----> raw--->select json
{ "num1":10,
"num2":20
}
253 | P a g e
Python Material Mr. Ratan
company=="tcs" or esal>100000 :
status:Eligible for mrg
else :
status : not eligible try after some time
254 | P a g e
Python Material Mr. Ratan
Magic Functions
Introduction:
The function which starts with two underscores & ends with two underscores is called magic
function.
Some of the magic functions are automatically executed & some of the magic function we have
to call explicitly.
Magic functions in Python are the special functions which add "magic" to your class.
Note: All magic functions will work for any type of data.
def __str__(self):
return "Good Morning"
def __del__(self):
print("object destoryed.....")
c = MyClass()
print(c)
del c
255 | P a g e
Python Material Mr. Ratan
ex 2: magic functions
import re
print(re.__name__)
print(re.__version__)
print(re.__file__)
import names
print(names.__name__)
print(names.__version__)
print(names.__file__)
E:\>python first.py
re
2.2.1
C:\Users\RATAN\AppData\Local\Programs\Python\Python37\lib\re.py
names
0.3.0
C:\Users\RATAN\AppData\Local\Programs\Python\Python37\lib\site-
packages\names\__init__.py
if __name__=="__main__":
print(MyClass.__dict__)
print(MyClass.__doc__)
print(MyClass.__module__)
print(MyClass.__name__)
256 | P a g e
Python Material Mr. Ratan
E:\>python first.py
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__',
'__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__',
'__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__',
'__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__',
'__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__',
'__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__',
'__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__',
'__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate',
'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
res1 = num.__add__(10)
print(res1)
res2 = num.__mul__(10)
print(res2)
E:\>python first.py
20
20
100
__init__ : we are initializing the data __new__ : it is talking about object creation process internally
class Employee:
def __new__(cls):
print("this is new")
inst = object.__new__(cls)
return inst
def __init__(self):
print("this is Init")
e = Employee()
when we create the object internally __new__ executed it calls parent class new to create our class
object & it return object.
257 | P a g e
Python Material Mr. Ratan
class Word(str):
def __new__(cls,msg):
w = msg.split()[1]
instance = str.__new__(cls,w)
return instance
w = Word("addanki ratan")
print(w)
During object reation we are passing the data at fourth line so object created for only data.
in fourth line if we are not passing the data then object created for entire message.
ex 7: The cls is allows to create only one object is called singleton cls. when we are trying to create
multiple objects it has to return exiting object reference insted of creating new object.
in __new__ first time we are creating object later the if condition is fail so it returns previous object.
class MyClass(object):
obj = None
def __new__(cls):
if not cls.obj:
cls.obj = object.__new__(cls)
return cls.obj
c1 = MyClass()
print(id(c1))
c2 = MyClass()
print(id(c2))
c3 = MyClass()
print(id(c3))
ex 8: Assignments
for my class i want create only 4-four objects
if i am trying to create the fifth object
error message object creations limit excceed for this class.
258 | P a g e
Python Material Mr. Ratan
class Closer:
def __init__(self, obj):
self.obj = obj
def __enter__(self):
print("file started...")
return self.obj
def __exit__(self,*data):
print("file closed...")
self.obj.close()
E:\>python first.py
file started...
Checking the data
file closed...
ex 10: Assignment
__setattr__ : it is called when we set the data
__getattr__ : it is called when we get the data
__delattr__ : it is called when we delete the data
259 | P a g e
Python Material Mr. Ratan
Django
Client:
Who sends the request and who takes the response is called client.
ex: InternetExploral, MozillaFrefox, opera………..etc
Server:
1. server contains project
2. Takes the request from client
3. Identify the requested resource.
4. Process the request.
5. generate response to client.
ex: Djnago server , Flask server ………..etc
260 | P a g e
Python Material Mr. Ratan
create the Django project using IDE will get three folders:
1. location folder : configuration
setting.py
urls.py
261 | P a g e
Python Material Mr. Ratan
def disp(request):
return HttpResponse("This is Django First Application....")
def wish(request):
return HttpResponse(f"Good Morning.......{datetime.now()}")
def status(request):
return HttpResponseRedirect("http://facebook.com")
def htmltstatus(request):
return render(request,"success.html")
262 | P a g e
Python Material Mr. Ratan
ex 2: Login Application.
step 1: The client is sending the req from browser http://10.4.3.10/login
The server has to render the response login.html
step 2: The client enter the username & password clicked in login
once he clicked on login action tag url is sending to server
for that url create the function in that write login check logics : success or fail.
#login.html
<html>
<body>
<form action="/logincheck/" method="POST">
{% csrf_token %}
User Name:<input type="text" name="username"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
#views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
#urls.py
from LoginApplication import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',views.login_page),
path('logincheck/',views.login_check)
]
263 | P a g e
Python Material Mr. Ratan
def login_check(request):
username = request.POST['username']
password = request.POST['password']
if username=="ratan" and password=="anu":
return HttpResponseRedirect("http://www.fb.com")
else:
return HttpResponseRedirect("http://www.nareshit.com")
def login_check(request):
username = request.POST["username"]
password = request.POST["password"]
264 | P a g e
Python Material Mr. Ratan
views.py
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
def emp_page(request):
return render(request,'emp.html')
def employeecheck(request):
empname = request.POST['empname']
company = request.POST['company']
salary = request.POST['salary']
urls.py
from Applicationexample import views
urlpatterns = [
path('admin/', admin.site.urls),
path('emp/',views.emp_page),
path('employeecheck/',views.employeecheck)
]
265 | P a g e
Python Material Mr. Ratan
266 | P a g e
Python Material Mr. Ratan
Pandas
Pandas is the most popular python library that is used for data analysis & manipulate.
Pandas is a high-level data manipulation tool developed by Wes McKinney.
Series Creation
import pandas as pd
#series of int data
data = [3,2,5,7,9,3,2]
s1 = pd.Series(data)
print(s1)
print(s1.dtype)
267 | P a g e
Python Material Mr. Ratan
s= pd.Series(["ramu","anu","raju","ramu"],['i','ii','iii','iv'])
print(s)
import pandas as pd
dict = {1:"a",2:'b',3:'c',4:'d'}
s = pd.Series(dict)
print(s)
s = pd.Series((1,2,3)) + pd.Series([10,20])
print(s)
s = pd.Series((2,3)) + pd.Series([10,20,30])
print(s)
odd = pd.Series(range(1,101,2))
print(odd)
268 | P a g e
Python Material Mr. Ratan
DataFrame
import pandas as pd
dict = {'names':['ratan','ramu','raju'],
'numbers':[1,2,3],
'fruits':['apple','mango',"orange"]}
df = pd.DataFrame(dict)
print(df)
ex- 3:
import pandas as pd
data = {
'apples': [2, 3, 1, 4],
'oranges': [0, 4, 5, 9]
}
purchases = pd.DataFrame(data)
print(purchases)
269 | P a g e
Python Material Mr. Ratan
import pandas as pd
data = {
'even': list(range(2,51,2)),
'odd': list(range(1,51,2)),
'both': list(map(sum,zip(range(2,51,2)),range(1,51,2)))
}
df = pd.DataFrame(data)
df.to_csv("sample.csv")
print("operations are completed")
import pandas as pd
data = {"names":["ramu","anu","raju","rani"],
"age":[45,23,24,47],
"height":[5.6,6.6,5.4,5.3]}
df= pd.DataFrame(data,index=['i','ii','iii','iv'])
df.to_csv("sample.csv")
print("operations are completed.....")
import pandas as pd
dict = {"country":["Brazil", "Russia","India","China", "South Africa"],
"capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
"area": [8.516, 17.10, 3.286, 9.597, 1.221],
"population": [20.4, 143.5, 125.2, 135.7, 52.98] }
user_index = ['i','ii','iii','iv','v']
brics = pd.DataFrame(dict,index=user_index)
brics.to_csv("country.csv")
print("operations are completed....")
270 | P a g e
Python Material Mr. Ratan
df2 = pd.DataFrame({
'Company Name':['WhatsApp'],
'Founders':['Jan Koum, Brian Acton'],
'Founded': [2009],
'Number of Employees': [5000]}, index=['i'])
df = pd.DataFrame(np.random.uniform(1,100,size=(20,5)),columns=['col1','col2','col3','col4','col5'])
print(df)
df = pd.DataFrame(np.random.randint(1,100,size=(10,3)),columns=['col1','col2','col3'])
print(df)
df = pd.DataFrame(np.random.randn(8,2),columns=['col1','col2'])
print(df)
import pandas as pd
data = pd.read_json('sample.json')
data.to_csv("sample.csv")
print("operations are completed...")
271 | P a g e
Python Material Mr. Ratan
import pandas as pd
import numpy as np
import random
import names
n = 20
df = pd.DataFrame({
'eid':np.random.randint(1, 100,n),
'ename':[names.get_first_name() for x in range(n)],
'esal':np.random.uniform(10000,20000,n),
'date_of_join': pd.date_range(start='2020-01-01',periods=n,freq='D'),
'height': np.linspace(5,8,20),
'status': np.random.choice(['Low','Medium','High'],n),
})
df.to_csv("sample.csv",index=False)
print("operations are completed....")
ex 2: read the data from csv perform delete operatons
import pandas as pd
data = pd.read_csv('sample.csv',index_col=0)
data = data.drop([data.index[5]])
data = data[data.Founders != 'Bill Gates']
print(data)
272 | P a g e
Python Material Mr. Ratan
ex-1:
import pandas as pd
data = pd.read_csv("sample.csv")
#printing number of columns
print(data.columns)
print(data.columns[0:2])
E:\>python first.py
Index(['eid', 'ename', 'esal', 'date_of_join', 'height', 'status'], dtype='object')
Index(['eid', 'ename'], dtype='object')
['eid', 'ename', 'esal', 'date_of_join', 'height', 'status']
['eid', 'ename']
eid int64
ename object
esal float64
date_of_join object
height float64
status object
dtype: object
int64
(20, 6)
20
6
273 | P a g e
Python Material Mr. Ratan
ex-2: Reading the data from csv file based on index. [specific rows]
import pandas as pd
data = pd.read_csv("sample.csv")
print(data)
print(data.head())
print(data.head(3))
print(data.tail())
print(data.tail(3))
print(data[0:4])
print(data[3:])
print(data[:4])
print(data[2:10:2])
print(data[3::2])
print(data[::2])
print(data[::-2])
import pandas as pd
data = pd.read_csv("sample.csv")
print(data['status'].unique())
print(len(data['status'].unique()))
print(data['height'].isnull().sum())
274 | P a g e
Python Material Mr. Ratan
print(data.eid.astype(float))
data = data.sort_values('eid',ascending=True)
print(data[['eid', 'ename']].head())
print(data.rank())
print(data.describe())
print(data['eid'].describe())
#print(data.iloc[row][col])
#print(data.at[index][col-name])
print(data.loc[2]['eid'])
print(data.loc[4]['ename'])
print(data.iloc[0][0])
print(data.iloc[1][2])
print(data.at[3,'height'])
print(data.at[4,'status'])
print(data.iat[1,1])
print(data.iat[2,2])
275 | P a g e
Python Material Mr. Ratan
ex-6:
import pandas as pd
data = pd.read_csv('sample.csv',index_col=0)
#print(data.iloc[row][col])
print(data.iloc[0][0])
print(data.iloc[1][2])
print(data.iat[0,0])
print(data.iat[1,2])
#print(data.at[index][col-name])
print(data.loc['i']['age'])
print(data.loc['ii']['names'])
print(data.at['i','age'])
print(data.at['ii','names'])
Note-1 : iloc() iat() these funtions are work only based on default index numbers.
if the csv file contians user defined index column it will ignore that index data.
Note-2 :
loc() at() these are worked based on both predefined & user defined index.
if the csv file does not contains indexes column then it will work for default index(0,1,2,3)
if the csv file contains index it will work for only that corresponding index but not for default index.
ex-7:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1,10,size=(5,3)),columns=['col1','col2','col3'])
print(df)
276 | P a g e
Python Material Mr. Ratan
NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access
and manipulate them very efficiently.
277 | P a g e
Python Material Mr. Ratan
e = np.array([])
print(size(e))
We can see that the difference between the empty array "e" and the array "a" with three
integers consists in 24 Bytes. This means that an arbitrary integer array of length "n" in numpy needs
278 | P a g e
Python Material Mr. Ratan
ex-4: Conversion of list & tuple into Array format because processing arrays are very faster
than list & tuple.
import numpy as np
F = np.array([1, 1, 2, 3, 5, 8, 13, 21])
V = np.array((3.4, 6.9, 99.8, 12.8))
print("F: ", F)
print("V: ", V)
print(b)
279 | P a g e
Python Material Mr. Ratan
np.random. random() : Create an array filled with random values from 0.0 to 1.0.
np. random .randn() : Create an array filled with random values both +ve & -ve values.
np.random.randint() : creating array with random int values.
np.random.uniform() : creating array with random deciaml values.
import numpy as np
a = np.zeros((2,2))
print(a)
b = np.ones((2,3))
print(b)
c = np.full((2,2), 7)
print(c)
d = np.eye(2)
print(d)
d = np.eye(3)
print(d)
e = np.random.random((2,2))
print(e)
e = np.random.randint(1,10,(3,2))
print(e)
e = np.random.uniform(5,10,(2,3))
print(e)
e = np.random.randn(2,2)
print(e)
280 | P a g e
Python Material Mr. Ratan
import numpy as np
data1 = np.arange( 10, 30, 5 )
print(data1)
print(type(data1))
data3 = np.linspace( 0, 2, 9)
print(data3)
data3 = np.linspace( 1, 10, 4)
print(data3)
row_r3 = a[:2,:2]
print(row_r3)
row_r4 = a[1:,2:]
print(row_r4)
row_r5 = a[:1,1:]
print(row_r5)
row_r6 = a[2:,2:]
print(row_r6)
row_r7 = a[::2,::2]
print(row_r7)
row_r8 = a[::-1,::-1]
print(row_r8)
row_r9 = a[:2:2,:2:2]
print(row_r9)
281 | P a g e
Python Material Mr. Ratan
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
print(x + y)
print(np.add(x, y))
print(x - y)
print(np.subtract(x, y))
print(x * y)
print(np.multiply(x, y))
print(x / y)
print(np.divide(x, y))
print(np.sqrt(x))
282 | P a g e
Python Material Mr. Ratan
newarr = arr.reshape(3, 2, 2)
print(newarr)
newarr = arr.reshape(2, 2, 3)
print(newarr)
# Flatten array
arr = np.array([[1, 2, 3], [4, 5, 6]])
flarr = arr.flatten()
a = np.array([1, 2, 5, 3])
# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
283 | P a g e
Python Material Mr. Ratan
284 | P a g e
Python Material Mr. Ratan
Matplotlib module
ex-1:
import numpy as np
import matplotlib.pyplot as matplt
cvalues = [20.1, 20.8, 21.9, 22.5, 22.7, 22.3, 21.8, 21.2, 20.9, 20.1]
C = np.array(cvalues)
matplt.plot(C)
matplt.show()
ex:
import numpy as np
import matplotlib.pyplot as matplt
cvalues = [1,2,5,6,3,7]
C = np.array(cvalues)
matplt.plot(C)
matplt.show()
285 | P a g e
Python Material Mr. Ratan
ex-3:
import numpy as np
import matplotlib.pyplot as plt
# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
286 | P a g e
Python Material Mr. Ratan
plt.figure(figsize=(5,5)
institutes =[ "Nareshit","Satech","Gana Tech.","Pee Tech.","Dreams Solu."]
values =[3803,638,150,374,296]
explode = [0.05,0,0,0,0] #explode 1st i.e slice is separated by 0.05 distance
colors =["c","b","g","r","y"]
Ex-5: This pie chart based on no. of users who logged on this gamming and social media.
import matplotlib.pyplot as plt
plt.figure(figsize=(5,5))
slices=[80, 78, 65, 58, 50]
logins =["youtube", "pub-g", "facebook", "whatsaap", "instagram"]
cols =['cyan', 'g', 'b', 'red', 'y']
plt.pie(slices, labels=logins, colors=cols, explode=(0,0.05,0,0,0), startangle= 225,
shadow=True, autopct="%0.1f%%")
plt.show()
287 | P a g e
Python Material Mr. Ratan
Logging module
Depending on type of information, logging data is divided according to the following 5 levels.
To perform logging, first we required to create a file to store messages and we have to specify which
level messages we have to store. We can do this by using basicConfig() function of logging module.
logging.basicConfig(filename='log.txt',level=logging.WARNING)
The above line will create a file log.txt and we can store either WARNING level or higher level
messages to that file.
logging.basicConfig(filename='log.txt',level=logging.ERROR)
this file contains ERROR & CRITICAL
logging.basicConfig(filename='log.txt',level=logging.INFO)
this file contains ERROR & CRITICAL & WARNING & INFO
After creating log file,we can write messages to that file by using the following methods.
logging.debug(message)
logging.info(message)
logging.warning(message)
logging.error(message)
288 | P a g e
Python Material Mr. Ratan
logging.critical(message)
E:\>python first.py
Enter First Number: 10
Enter Second Number: 0
ZeroDivisionError occurred
E:\>python first.py
Enter First Number: ratan
Enter only integer values
log.txt:
INFO:root:Request processing started:
ERROR:root:division by zero
Traceback (most recent call last):
File "first.py", line 7, in <module>
print(x/y)
ZeroDivisionError: division by zero
289 | P a g e
Python Material Mr. Ratan
logging.basicConfig(filename='log.txt',level=logging.DEBUG)
def my_service():
logging.debug(f'worker Starting {threading.currentThread().getName()}')
time.sleep(3)
logging.debug(f'worker Starting {threading.currentThread().getName()}')
def worker():
logging.debug(f'worker Starting {threading.currentThread().getName()}')
time.sleep(2)
logging.debug(f'worker Starting {threading.currentThread().getName()}')
w1 = threading.Thread(target=worker,name="worker-1")
w2 = threading.Thread(target=worker,name="worker-2")
t.start()
w1.start()
w2.start()
290 | P a g e
Python Material Mr. Ratan
Pillow module
blurred = img.filter(ImageFilter.BLUR)
blurred.save("blurred.png")
print("operations are completed....")
ex-3: converting one image format into another image. [JPG --- PNG]
291 | P a g e
Python Material Mr. Ratan
img.save('rectangle.png')
292 | P a g e
Python Material Mr. Ratan
idraw = ImageDraw.Draw(tatras)
text = "Ratan Material"
font = ImageFont.truetype("arial.ttf", size=30)
idraw.text((10, 10), text, font=font)
tatras.save('watermark_img.png')
293 | P a g e
Python Material Mr. Ratan
Tkinter module
Introduction:
tkinter module used to design GUI application.
In standalone application GUI us developed using tkiner module.
In web application GUI is developed using HTML, CSS , JavaScript.
name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.
window.mainloop()
294 | P a g e
Python Material Mr. Ratan
tk.Label(window,text="Login Application....").grid(row=0,column=1)
tk.Label(window,text="User Name:").grid(row=1,column=0)
tk.Entry(window).grid(row=1,column=1)
tk.Label(window,text="User Password:").grid(row=2,column=0)
tk.Entry(window).grid(row=2,column=1)
295 | P a g e
Python Material Mr. Ratan
def wish_ratan():
tkinter.Label(window, text = "Good Morning Ratan sir!").pack()
def wish_anu():
tkinter.Label(window, text = "Good Morning Anu madam!").pack()
def wish_students():
tkinter.Label(window, text = "Good Morning Students!").pack()
Label(window,text="Password").grid(row=1, column=0)
password = StringVar()
Entry(window, textvariable=password, show='*').grid(row=1, column=1)
window.mainloop()
296 | P a g e
Python Material Mr. Ratan
combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, "Text")
combo.current(3)
combo.grid(column=0, row=0)
window.mainloop()
window.mainloop()
297 | P a g e
Python Material Mr. Ratan
var = IntVar()
var.set(1)
def register(firstname, lastname,var,CheckVar1,CheckVar2,CheckVar3):
Label(window, text = "Registration Successfull, below are your registration
details!!!!!").place(x=150, y=200)
Label(window, text = "Registration Details").place(x=150, y=220)
Label(window, text = "Firstname: "+firstname.get()).place(x=150, y=240)
Label(window, text = "Lastname: "+lastname.get()).place(x=150, y=260)
global selection
selection = var.get()
if selection==1:
Label(window, text = "Gender: Male").place(x=150, y=280)
else:
Label(window, text = "Gender: Female").place(x=150, y=280)
val=""
if CheckVar1.get()==1:
val+="Python, "
if CheckVar2.get()==2:
val+="Django, "
if CheckVar3.get()==3:
val+="Flask"
Label(window, text ="Course: "+val).place(x=150, y=300)
firstname = StringVar()
firstEntry = Entry(window, textvariable=firstname).grid(row=0, column=1)
298 | P a g e
Python Material Mr. Ratan
CheckVar1 = IntVar()
CheckVar2 = IntVar()
CheckVar3 = IntVar()
window.mainloop()
299 | P a g e
Python Material Mr. Ratan
# Let's now define the required functions for the Calculator to function properly.
# 1. First is the button click 'btn_click' function which will continuously update the input field
whenever a number is entered or any button is pressed it will act as a button click update.
def btn_click(item):
global expression
expression = expression + str(item)
input_text.set(expression)
# 2. Second is the button clear 'btn_clear' function clears the input field or previous calculations
using the button "C"
def btn_clear():
global expression
expression = ""
input_text.set("")
# 3. Third and the final function is button equal ("=") 'btn_equal' function which will calculate the
expression present in input field. For example: User clicks button 2, + and 3 then clicks "=" will result
in an output 5.
def btn_equal():
global expression
result = str(eval(expression)) # 'eval' function is used for evaluating the string expressions directly
# you can also implement your own function to evalute the expression istead of 'eval' function
input_text.set(result)
expression = ""
expression = ""
# In order to get the instance of the input field 'StringVar()' is used
input_text = StringVar()
300 | P a g e
Python Material Mr. Ratan
# Once all the functions are defined then comes the main section where you will start defining the
structure of the calculator inside the GUI.
# Then you will create an input field inside the 'Frame' that was created in the previous step. Here
the digits or the output will be displayed as 'right' aligned
input_field = Entry(input_frame, font = ('arial', 18, 'bold'), textvariable = input_text, width = 50, bg =
"#eee", bd = 0, justify = RIGHT)
input_field.grid(row = 0, column = 0)
input_field.pack(ipady = 10) # 'ipady' is an internal padding to increase the height of input field
# Once you have the input field defined then you need a separate frame which will incorporate all
the buttons inside it below the 'input field'
btns_frame = Frame(window, width = 312, height = 272.5, bg = "grey")
btns_frame.pack()
# The first row will comprise of the buttons 'Clear (C)' and 'Divide (/)'
clear = Button(btns_frame, text = "C", fg = "black", width = 32, height = 3, bd = 0, bg = "#eee", cursor
= "hand2", command = lambda: btn_clear()).grid(row = 0, column = 0, columnspan = 3, padx = 1,
pady = 1)
divide = Button(btns_frame, text = "/", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee",
cursor = "hand2", command = lambda: btn_click("/")).grid(row = 0, column = 3, padx = 1, pady = 1)
# The second row will comprise of the buttons '7', '8', '9' and 'Multiply (*)'
seven = Button(btns_frame, text = "7", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor
= "hand2", command = lambda: btn_click(7)).grid(row = 1, column = 0, padx = 1, pady = 1)
eight = Button(btns_frame, text = "8", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor
= "hand2", command = lambda: btn_click(8)).grid(row = 1, column = 1, padx = 1, pady = 1)
nine = Button(btns_frame, text = "9", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(9)).grid(row = 1, column = 2, padx = 1, pady = 1)
multiply = Button(btns_frame, text = "*", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee",
cursor = "hand2", command = lambda: btn_click("*")).grid(row = 1, column = 3, padx = 1, pady = 1)
301 | P a g e
Python Material Mr. Ratan
# The third row will comprise of the buttons '4', '5', '6' and 'Subtract (-)'
four = Button(btns_frame, text = "4", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1)
five = Button(btns_frame, text = "5", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(5)).grid(row = 2, column = 1, padx = 1, pady = 1)
six = Button(btns_frame, text = "6", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(6)).grid(row = 2, column = 2, padx = 1, pady = 1)
minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee",
cursor = "hand2", command = lambda: btn_click("-")).grid(row = 2, column = 3, padx = 1, pady = 1)
# The fourth row will comprise of the buttons '1', '2', '3' and 'Addition (+)'
one = Button(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1, pady = 1)
two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady = 1)
three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor
= "hand2", command = lambda: btn_click(3)).grid(row = 3, column = 2, padx = 1, pady = 1)
plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor
= "hand2", command = lambda: btn_click("+")).grid(row = 3, column = 3, padx = 1, pady = 1)
# Finally, the fifth row will comprise of the buttons '0', 'Decimal (.)', and 'Equal To (=)'
zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(0)).grid(row = 4, column = 0, columnspan = 2, padx = 1, pady
= 1)
point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor
= "hand2", command = lambda: btn_click(".")).grid(row = 4, column = 2, padx = 1, pady = 1)
equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee",
cursor = "hand2", command = lambda: btn_equal()).grid(row = 4, column = 3, padx = 1, pady = 1)
window.mainloop()
302 | P a g e
Python Material Mr. Ratan
Step 2: select the jupyter window (any one). Here I am doing practical by using try jupyter with python.
303 | P a g e
Python Material Mr. Ratan
304 | P a g e
Python Material Mr. Ratan
305 | P a g e
Python Material Mr. Ratan
306 | P a g e