Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Ratan CompleteMaterial

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

Python Material Mr.

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

6. python functions. 57-68


Function usage
Function return type
Function arguments
Inner Functions

7. PEP[Python Enhancement Proposal] . 69-71

1|P ag e
Python Material Mr. Ratan

8. python advanced data types. 73-117


String : str
List : list
Tuple : tuple
Set : set
Dictionary : dict

9. lambda, filter, mapper, reduce. 118-122

10. exception handling. 123-136


try
except
else
finally
raise

11. file handling. 137-145


Modes of the file
Read & write & append operations
Closing the file in different ways

12. assertions. 146-147

13. database connections. 148-161


Oracle database
mysql
postgre

14. Regular expression. 162-170

15. class vs. objects concept 172-184

16. OOPS 185-205


inheritance
poly
abstraction
encapsulation

2|P ag e
Python Material Mr. Ratan

17. packages 206 -227

18. modules 206 -227

19. modifiers 206 -227

20. Predefined Modules 206 -227


names,collections,random,string,names,statistics
sys,os,math,pillow,time...etc

21. multi threading. 228-241

22. JSON. 243-246

23. Rest-API. 247-254

24. Magic function. 255-259

25. Django. 260-266

26. pandas 267-276

27. numpy 277-284

28. predefined modules 285-305


logging
tkinter
logging
matplotlib

3|P ag e
Python Material Mr. Ratan

PYTHON Programing language

 Python is object-oriented, interpreted , dynamic & widely used high-level programming


language for general-purpose programming.
 Python created by Guido van Rossum and first released in 1991 from python software
foundation.
 Python is platform independent & open source language.
 File name extensions in python : .py
 Web site : www.python.org
 Python is a clear and powerful object-oriented programming language, comparable to Perl,
Ruby, Scheme, or Java.
 Python is used to develop the different types of application such as web-apps, standalone
apps, enterprise apps, ERP and e-commerce application, scientific & numeric computing..etc.

What is Python (Programming)?


Python is a general-purpose language. It has wide range of applications from Web development
(like: Django and Bottle), scientific and mathematical computing (Orange, SymPy, NumPy) to desktop
graphical user Interfaces (Pygame, Panda3D).

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.

Why Python was created?


In late 1980s, Guido Van Rossum was working on the Amoeba distributed operating system
group. He wanted to use an interpreted language like ABC (ABC has simple easy-to-understand syntax)
that could access the Amoeba system calls. So, he decided to create a language that was extensible. This
led to design of a new language which was later named Python.

Why the name Python?


No. It wasn't named after a dangerous snake. Rossum was fan of a comedy series from late
seventies. The name "Python" was adopted from the same series "Monty Python's Flying Circus". Python
was named for the BBC TV show Monty Python's Flying Circus.

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

2. python performance good because python is less coding.

3. To run the code in online use python online coompilers


https://repl.it/languages/python3
https://glot.io/

4. The top websites written using python


In google search just type : top website written in python
https://www.quickstart.com/blog/10-famous-websites-built-with-python/
Google, YouTube, Quora,Dropbox.Yahoo!,Reddit,Instagram,Spotify , NSA ,DRDO...etc

5. Technologies are using python


AI , ML , DS , Image process , Deep learning....etc
IOT , chip level designing
selenium, Hadoop......etc

6. Developer practices: we can do the practical’s in different ways.


Terminals Approach
command prompts

Editors
Edit plus
notepad++
subline text
vs editor

IDE : Integrated development environment.


spyder
pycharam

Note books
Jupyter

Tools
Anaconda

5|P ag e
Python Material Mr. Ratan

7. Python is an interpreted, high-level, general-purpose programming language.


C, CPP : performance is very good
not for internet application
platform dependent languages
C : procedure based : functions
Cpp : oop : deals with classes & object

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()

3. oops : deals with classes & objects


class MyClass:
def wish(self):
print("Good Morning ratan")
c = MyClass()
c.wish()

8. The programming languages are two types


1. Low level languages
These are closer to machine
ex: assembly
2. high level languages
These are closer to human
ex: java, python,js

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

1. python 2.x vs. python 3.x


python 3.0 introduced in 2008
present every project using: 3.8
python 2.x interpreter is different & 3.x interpreter is different so the python 3.x interpreter it
does not support 2.x version code.

And changing 2.x to 3.x means checking every line of code do the modification which is not
recommended and not possible.

2. compiler -----> it takes complete code converted to byte code


interpreter -----> it will take line by line code converted to byte code
python is interpreter based

3. interpreter: developed using C : cpython


interpreter convert source code to byte code
CPVM : it will convert byte code to machine code
https://github.com/python/cpython

Interpreter : developed using java : https://www.jython.org/


Interpreter : developed using python : https://www.pypy.org/
Interpreter : developed using C# : https://ironpython.net/

when we download the python by default cpython will come.

4. download the python


https://www.python.org/downloads/windows/
Download Windows x86-64 executable installer
the file will be downloaded

just install it:


checkbox add path : by default it is disable just enable it
while installation just check the folder where it is installation

https://docs.python.org/3/ : to see the documnetation

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

6. Designed by : Guido van Rossum


Developer : Python Software Foundation
Trainer : Ratan
7. Python is open source & platform independent language.
open source:
Free of cost.
Anyone can download the source code can do the modifications.

platform independent: it will support all Operating system.

Python Version release dates:

 Implementation started - December, 1989


 Internal releases at Centrum Wiskunde & Informatica – 1990
 Python 0.9.0 - February 20, 1991
 Python 0.9.1 - February, 1991
 Python 0.9.2 - Autumn, 1991
 Python 0.9.4 - December 24, 1991
 Python 0.9.5 - January 2, 1992
 Python 0.9.6 - April 6, 1992
 Python 0.9.8 - January 9, 1993
 Python 0.9.9 - July 29, 1993

 Python 1.0 - January 1994


 Python 1.2 - April 10, 1995
 Python 1.3 - October 12, 1995
 Python 1.4 - October 25, 1996
 Python 1.5 - December 31, 1997
 Python 1.6 - September 5, 2000
 Python 2.0 - October 16, 2000
 Python 2.1 - April 15, 2001
 Python 2.2 - December 21, 2001
 Python 2.3 - July 29, 2003
 Python 2.4 - November 30, 2004
 Python 2.5 - September 19, 2006
 Python 2.6 - October 1, 2008
 Python 2.7 - July 4, 2010
 Python 3.0 - December 3, 2008
 Python 3.1 - June 27, 2009
 Python 3.2 - February 20, 2011
 Python 3.3 - September 29, 2012
 Python 3.4 - March 16, 2014
 Python 3.5 - September 13, 2015
 Python 3.6 - December 23, 2016
 Python 3.7 - June 27, 2018

8|P ag e
Python Material Mr. Ratan

Other languages vs. python:

1. Python simple language:


I will write the code to print Ratan world on screen in C, Java, Python. Decide yourself which is simple.

Case 1: printing Hello world…..


In java In python
public class Test Print (“ratan world”)
{ public static void main(String[] args)
{ System.out.println("ratan world");
}
}

case 2: Taking input from end-user…..


In java : In python:
Scanner s = new Scanner(System.in); n = input("enter a number")
System.out.println("etner a number"); print(n)
int n = s.nextInt();
System.out.println(n);

case 3: swapping two numbers.


In java :
int a=10,b=20; In python :
int temp; a,b=10,20
temp=a; a,b=b,a
a=b;
b=temp;

2. Python is dynamically typed.


In java we must declare the type of the variables by using data type concept. But python
is dynamically typed no need to declare the data type.

In other languages: byte short int long float double char Boolean(Type declaration mandatory)
int eid=111;
String ename="ratan";
float esal=100000.34;

In python: Type declaration not required because it is dynamically typed.


a=10 by default it is : int
b=10.5 by default it is : float
c=True by default it is : boolean
d="ratan" by default it is : String

9|P ag e
Python Material Mr. Ratan

3. Importance of python & it is a general-purpose language: build anything


Many big names such as Yahoo, IBM, Nokia, Google, Disney, NASA, Mozilla and much
more rely on Python.
Python is used to develop the different types of application such as web-apps, stand
alone apps, enterprise apps, ERP and e-commerce application, scientific & numeric
computing..etc.

4. Python Single line code.


In other languages it will take more lines of code but in python we can write the
code in less number of line.
Case 1 : variable declaration single line of code in python.
In java : in python :
int eid=111; eid,ename,esal=111,”ratan”,100000.34
String ename="ratan";
float esal=100000.34;

case 2: swaping two variables


In java : In python :
int a=10; a,b=10,20
int b=20; a,b=b,a
int temp;
temp=a;
a=b;
b=temp;

5. Python platform independent software.


 Once we develop the application by using any one operating system(windows) that application runs
only on same operating system is called platform dependency.
ex : C,CPP

 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

Web Technology uses PYTHON with django


Mobile Apps uses PYTHON with FLASK
Big Data Hadoop uses PYTHON

Data Science Analytics uses PYTHON


Amazon Web Services uses PYTHON
Automation Tools DevOps uses PYTHON
Reporting Tableau uses PYTHON
Scripting and GUI Apps Uses PYTHON
Scientific Applications uses PYTHON with Numpy, Scipy
Gaming, Networking, Embedded Systems, AI

12 | P a g e
Python Material Mr. Ratan

Python has significant advantages in terms of


 Pyramid, Flask, Bottle and Django are among the well-known frameworks of Python.
 Pyramid is a small framework which makes real-world Web applications productive.
 Django is more mature and is one among the largest Web-based frameworks for Python
But Django is very hard to customise and troubleshoot, in some situations, due to its all-
encompassing nature. This is one of its drawbacks.
 Tornado is lighter in weight and has a few more features than Django. As I said earlier,
Tornado is known for its high performance
 Building API services for Mobile ( Flask )
 Doing Scientific computations ( Numpy, Scipy )
 PlotLib would enable you to create data visualizations.
 Dealing with Data ( Pandas )
 Numerous other things like scripting/ text processing/ machine learning/Natural
Language Processing/ Text mining/ Web mining/ OpinionMining/ Sentiment analysis/
Big data system

13 | P a g e
Python Material Mr. Ratan

Python Day-3 Different ways to run the python code

Appraoch-1: python online compilers


https://repl.it/languages/python3
https://glot.io/new/python

Approach-2: python terminals


in the installation location we will find python executable file: G:\python36\python.exe
>>> num1 = 10
>>> num2 = 20
>>> res = num1 + num2
>>> print(res)
30
a. it shows errors frequently
b. once we written the code we cannot modify.
Managing code is difficult

Approach-3: IDLE: Here we can do the practical’s in two ways


a. terminal approach
b. editor approach:
File menu ---new file --- write the code ---- save the code(.py) --- run the code(f5)
once we save the file we can reopen the file we can do the modification.
Approach-4 : Editors Approach
sublinetext,notepad++,editplus
Editplus : https://www.editplus.com/download.html
step 1: write the applciation in editor then save the application
num1 = 10
num2 = 20
res = num1 + num2
print(res)
I saved above applciation in :
E:
|-->python12pm
|--->first.py
step 2: run the application using command prompt.
To run the python code use comamnd : python
a. open the command prompt move to the location then run the code
C:\Users\RATAN>e:
E:\>cd python12pm
E:\python12pm>python first.py
30
b. goto the file location where we saved type cmd [this is recommanded]
E:\python12pm>python first.py
30

14 | P a g e
Python Material Mr. Ratan

There are different ways to run the python application


Approach- 1: By using python command line

Just click on python.exe file w e will get command prompt shown below start the programming.

Approach-2: By using system command prompt


Open the system command prompt type python command then we will python prompt.

Approach-3 by using python online compiler

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.

Step 2: Execute the above file by using fallowing command.

Approach - 5 : By using IDLE


IDLE is the standard Python development environment. Its name is an acronym of "Integrated
Development Environment". It works well on both Unix and Windows platforms. It has a Python shell
window, which gives you access to the Python interactive mode.
Once we installed python just earch python IDLE.

Approach-6 : We can develop the application by using IDE like PyCharm (jet brains).

16 | P a g e
Python Material Mr. Ratan

Python Day-4 : Data Types in python


ex-1:
case 1: other languages addition of two numbers.
int a=10;
int b=20;
int res;
res = a + b;
print(res);

case 2: python language addition of two numbers


num1 = 10
num2 = 20
res = num1 + num2
print(res)
Note:
i. In other languages must declare the data types. But in python data types declarations are not
required because python is dynamically typed.
ii. in outer languages every line must ends with semicolon But in python semicolon not required.

python basic data types :

Data Type values


Numeric data --- int --- 10 ,20, 30 ,40
Decimal data --- float --- 10.5 20.5 30.6
String --- str --- "ratan" 'anu'
Boolean --- bool --- True-1 False-0 (starts with capital)

ex-2: To check the type of the data using type() function


val1 = 10
val2 = 10.4
val3 = "ratan"
val4 = True
print(type(val1))
print(type(val2))
print(type(val3))
print(type(val4))

E:\python12pm>python first.py
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

17 | P a g e
Python Material Mr. Ratan

ex-3: Take the three int value perform multiplication


Take the three decimal values perform addition

case 1 : student code : but it is not recommended


num1 = 20
num2 = 30
num3 = 40
res = num1*num2*Num3
print(res)

num1 = 2.7
num2 = 4.4
num3 = 3.2
res=num1+num2+num3
print(res)

case 2: this code is recommended


num1,num2,num3 = 20, 30, 40
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

ex 5: if the alignment is not correct we will get Indentation Error


num1 = 10
num2 = 20 IndentationError: unexpected indent
res = num1 + num2
print(res)

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.

There are two types of comments in python.

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 (‘)

Syntax : “ ” ” Syntax : ‘’’


St-1 St-1
St-2 St-2
;;;;;;;; ;;;;;;;;
St-n St-n
“”” ‘’’
Ex:
Case 1: Run the application python 2.7 version.
Python 2.7 to represent numeric data we have two data types
a. int
b. long

x = 35455443535
print(type(x))
x = 4353453453453453534536546546464565464564564545
print(type(x))
$python main.py
<type 'int'>
<type 'long'>

Case 2: Run the application python 3.x version.


Python3 to represent numeric data we have only int type.
x = 10
print(type(x))
x = 4353453453453453534536546546464565464564564545456
print(type(x))

$python main.py
<class 'int'>
<class 'int'>

21 | P a g e
Python Material Mr. Ratan

Python day-5 Different ways to print the data

ex 1: different ways to print the data


eid,ename,esal = 111,"ratan",10000.45
print(eid)
print(ename)
print(esal)

print(eid,ename,esal)

print("Emp id=",eid)
print("Emp name=",ename)
print("Emp sal=",esal)

print("Emp id=",eid,"Emp name=",ename,"Emp sal=",esal)

ex-2 : we can format the data properly in three ways


a. %
int float str
%d %f %g %s
b. {}
c. f

eid,ename,esal = 111,"ratan",10000.45
print("Emp id=%d Emp name=%s Emp sal=%f"%(eid,ename,esal))

print("Emp id={} Emp name={} Emp sal={}".format(eid,ename,esal))


print("Emp id={0} Emp name={1} Emp sal={2}".format(eid,ename,esal))

print(f"Emp id={eid} Emp name={ename} Emp sal={esal}")

ex 3: Escape Sequence characters


print("hi ratan sir")
print("hi \"ratan\" sir")
print("hi \'ratan\' sir")
print("hi \\ratan\\ sir")
print("hi\t\tratan\t\tsir")
print("hi \nratan\nsir")

eid,ename,esal = 111,"ratan",10000.45
print(f"Emp id={eid} \nEmp name={ename} \nEmp sal={esal}")

ex 4: printing the data using seperator.

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="$$$")

#Taking the input from end-user

ex-1: to take the input from end user use input()


input() function take the data in string format.

num1 = input("Enter a num1:")


num2 = input("Enter a num2:")
res = num1 + num2
print(res)

E:\python12pm>python first.py
Enter a num1: 10 10.5 ratan
Enter a num2: 20 20.6 anu
1020 10.520.6 ratananu

ex-2 : type conversion process


num1 = int(input("Enter a num1:"))
num2 = int(input("Enter a num2:"))
res = num1 + num2
print(res)

E:\python12pm>python first.py
Enter a num1:10
Enter a num2:20
30

Observations : if the type conversion is not possible we will get ValueError.


E:\python12pm>python first.py
Enter a num1:10.5
ValueError: invalid literal for int() with base 10: '10.5'

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

#concat the data using : +

in python it is possible to combine only same type of data


if we are trying to combine different types of data we will get TypeError.

in python int + float = Number bool[0,1] = int

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)

print(True+"sravya") #TypeError: unsupported operand type(s) for +: 'bool' and 'str'


print(10.5+"anu") #TypeError: unsupported operand type(s) for +: 'float' and 'str'
print(10+"ratan") #TypeError: unsupported operand type(s) for +: 'int' and 'str'

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

Python Keywords :( 33 keywords in python)


The keywords are altered in different versions of python so some extra keywords are added or
some might be removed. So, it is possible to get the current version of keywords by typing fallowing code
in the prompt.

To check the keyword use kwlist variable.


kwlist is a variable present in keyword module so import the module using import statement.

python 2.7 : 31 keywords


import keyword
print(keyword.kwlist)

['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"

python 3.7 : 33 keywords

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")

keywords removed from 3.7 : print, exec


keywords are added in 3.7 : False True None async await nonlocal

To check the given data is keyword or not use below code:


case 1: python 2.7 : True
import keyword
print(keyword.iskeyword("print"))

case 2: python 3.x : False


import keyword
print(keyword.iskeyword("print"))

25 | P a g e
Python Material Mr. Ratan

# python predefined support

in C,CPP language predefined support in the form of : header files


header files contain: functions

in java language predefined support in the form of : packages


packages contains : classes , interfaces , enums , annotations ,
exception , error

in python language predefined support in the from of : modules


modules contains : classes , variables , functions

To see the modules present in python use help() function


print(help("modules"))
ex : sys , keyword , abc, time,os ........etc

To see the data present in the module use dir() function.


ex:Here we are cheking the keyword module data.
import keyword
print(dir(keyword))

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.

ex:Here we are cheking the abc module data.


import abc
print(dir(abc))

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

 We cannot use special symbols like !, @, #, $, % etc. in our identifier.


name@one=”ratan” invalid
var$123=”durga” invalid

 Identifier can be of any length.

 The identifiers are case sensitive.


Name="ratan"
NAME="durga"

 Keywords are not allowed as identifier. (global, del are keywords)


class del:
global=100

 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

Number system: We can represent numeric values in the following ways


Types Base value Representation Values
a. Binary form : Base 2 : 0b 0B : 0 1
b. Octal form : Base 8 : 0o 0O : 01234567
c. Decimal form : Base 10 : By default : 0123456789
d. Hexadecimal form : base 16 : 0x 0X : 0-9 a-f
[here a=10 b =11 c=12 d=13 e=14 f=15]
Code Representation : 0: disable 1: enabled
64 32 16 8 4 2 1 : count the enables flag values
10 : 2
101 : 5
1010 : 10
10101 : 21
101010 : 42
1010101 : 82

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: conversion of decimal ---> binary, octal, hexadecimal.


In this program, we are used built-in functions bin (), oct () and hex () to convert
the given decimal number into respective number systems.

num = int(input("Enter a num:")) E:\>python first.py


print(bin(num)) Enter a num:20
print(oct(num)) 0b10100
print(hex(num)) 0o24
0x14

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))

ex: Finding CODE values.


c = input ("Enter a character: ") E:\>python first.py
print (f"The Code value of {c} is:",ord(c)) Enter a character: a
The Code value of a is: 97
val = int(input("Enter a Value: ")) Enter a Value: 67
print (f"The charcater of {val} is:",chr(val)) The charcater of 67 is: C

29 | P a g e
Python Material Mr. Ratan

Getting input from the end-user in python 2.7:


In python 2.7 There are two ways to get the input from end-user,
1. Input() function : It takes any type of data
2. raw_input() function : It takes data only String format
in python 3.x it is possible to take the input from end-user only one way
1. input() function : it takes only String data just like raw_input()

ex : python 2.7 Taking data from end-user by using input function.


 If the user gives an integer value, the input function returns integer value
 If the user gives float value, the input function returns float value
 If the user gives string value, the input function returns string value

num1 = input("enter first num:")


num2 = input("enter second number:")
add = num1+num2
print "Addition=",add
output : E:\>python first.py
enter first num :10 20.5 10 "ratan"
enter second number :20 30.3 10.5 "anu"
Addition= :30 50.8 20.5 ratananu
E:\>python first.py
enter first num:10
enter second number:"ratan"
TypeError: unsupported operand type(s) for +: 'int' and 'str'

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.

num1 = raw_input('Enter first number: ')


num2 = raw_input('Enter second number: ')
# Add two numbers
sum=num1+num2
# Display the sum
print "Addition=",sum
output :
E:\>python first.py E:\>python first.py
Enter first number: 10 Enter first number: ratan
Enter second number: 20 Enter second number: anu
Addition= 1020 Addition= ratananu

E:\>python first.py E:\>python first.py


Enter first number: 10.5 Enter first number: 10
Enter second number: 20.3 Enter second number: ratan
Addition= 10.520.3 Addition= 10ratan

30 | P a g e
Python Material Mr. Ratan

ex: Type conversion process.


num1 = int(raw_input('Enter first number: '))
num2 = int(raw_input('Enter second number: '))
# Add two numbers
sum=num1+num2
# Display the sum
print "Addition=",sum
E:\>python first.py
Enter first number: 10
Enter second number: 20
Addition= 30
E:\>python first.py
Enter first number: 10.5
ValueError: invalid literal for int() with base 10: '10.5'
E:\>python first.py
Enter first number: "ratan"
ValueError: invalid literal for int() with base 10: '"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

Material by Mr. Ratan...........

"Don’t expect anything from any one"

********* Completed: Thank you ************

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)

ex: write the output of below program.


print(3+4-5)
print(4+4*3/6)
print(6+12*2-8)
print((19-3)*(2+2)/4)
print(10/2 - 3%2 + (3 + 2) * 5)
Python Mixed-Mode Arithmetic: The calculation which done both integer and floating-point
number is called mixed-mode arithmetic. When each operand is of a different type. 9/2.0 ---> 4.5

32 | P a g e
Python Material Mr. Ratan

Relational operators: it returns Boolean value


x,y = 5,2
print(x>y)
print(x<y)
print(x==y)
print(x!=y)
print(x>=y)
print(x<=y)

33 | P a g e
Python Material Mr. Ratan

Bitwise operator: & | not

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"):

and : for the conditions parenthesis not required


if username=="ratan" and 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.

ex: Other than true or false it return False


print(not True)
print(not False)
print(not 0)
print(not 1)
print(not 23) #False
print(not "ratan") #False

case 1: write the outout.


if True or False or True or False:
print("ratan")
else :
print("anu")

case 2: write the output.


if True and True and True:
print("ratan")
else :
print("anu")

Ans-1 : ratan
Ans-2 : ratan

36 | P a g e
Python Material Mr. Ratan

 Assignment operator :

Assignment operators:
normal assignment : =
Augmented Assignment : *=, += ,-= ,/= , %=

# This is normal assignment


val = 10
print(val)

# Augmented assignment
val += 10 # val = val + 10
val -= 4 # val = val -4
val /= 2 # val = val / 2
val %= 2 # val = val %2
print(val)

increment & decrement operators not supported by python


i++ , i-- , ++i , --i : these are not supported by python

 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.

msg = "hi ratan sir"


print("ratan" in msg)
print("anu" in msg)

print("ratan" not in msg)


print("anu" not in msg)

37 | P a g e
Python Material Mr. Ratan

 Identity operators

To print the memory address use : id()


To perform memory comparison use is & is not

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.

Ans-1: username = input("enter User name:")


password = input("enter User Password:")
if username=="ratan" and password=="anu":
print("Login Success")
else:
print("login Fail")

Ans-2: eid = int(input("Etner Emp id:"))


ename = input("Enter emp name:")
esal = float(input("Enter emp sal:"))
company = input("Enter emp company:")
if esal>10000 or company=="tcs":
print("Good employee...")
else:
print("Very Good employee..")

Material by Mr. Ratan...........

Practical knowledge gives confidence


The confidence will give job satisfaction.

********* Completed: Thank you ************Share the material to friends

39 | P a g e
Python Material Mr. Ratan

Python flow control statements

There are three types of flow control statements:


c. Conditional statement
If
If-else
elif
d. Iteration statements / looping statements
for
while
e. Transfer statements
break
continue
return
try

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")

If-else statement: Takes two options.


 if the condition true if block executed.
 if the condition false else block executed.
ex: Login Success or fail, User existed or not, eligible for vote or not...etc

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 2: In python 0=false 1=true


if 0:
print("hi ratan")
else:
print("hi anu")

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")

case 5: single line of if-else.


# here taking one-line print
print("Good Morning") if 10>20 else print("Good Evening")

#taking multiple lines of print using brasses


{print("Good Morning"),print("HI students")} if 10>20 else {print("Good Evening"),print("hi ratan sir")}

# holding the result value.


x = 10 if 20>10 else 20
print(x)

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

1: Take the year from end-user check leap year or not.


year = int(input("enter year:"))
if year%4==0:
print("this is leap year")
else:
print("not leap year")

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")

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.

num = int(input("enter a number:"))


if num>0:
if num%2==0:
print("number is positive & even")
else:
print("number is positive & odd")
else:
if num%2==0:
print("number is negative & even")
else:
print("number is neagative & odd")

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")

case 2: Take number from end-user check it is positive or negative or zero.

num = int(input("Enter a num:"))


if num==0:
print("Zeroooooooooooo")
elif num>0:
print("Your number is positive")
else:
print("your number Negative")

case 3: printing Discount mon,tue = 2% wed,thr,fri = 3% sat,sun = 5%

day = input("Enter a day:")


if day=="mon" or day=="tue":
print("Discount 2%")
elif day=="wed" or day=="thr" or day=="fri":
print("Discount 3%")
else:
print("Discount 5%")

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().

syntax : for <temp-variable> in <sequence-data>:


statement(s)

range() function :

range(start, end, step)


range(5) : 0,1,2,3,4
range(5, 10) : 5, 6, 7, 8, 9
range(0, 10, 3) : 0, 3, 6, 9

when we will give start & end value,


The starting value is included.
The ending value is ignored.

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)

#printing the even values from 1-20


for x in range(2,22,2):
print(x)

#printing the values from 333 to 444 by steping 8


for x in range(333,444,8):
print(x)

44 | P a g e
Python Material Mr. Ratan

case 3 : printing the data in single line by using end.

for x in range(10):
print(x)

for x in range(10):
print(x,end=" ")

case 4: break vs. continue


break used to stop the loop execution.
continue used to skip the particular iteration.

num = int(input("Boys enter a num to stop the loop:"))


for x in range(10):
if x==num:
break
print(x)

num = int(input("Girls enter a number to skip the data:"))


for x in range(10):
if x==num:
continue
print(x)

case 5: pattern printing


for i in range(1, 5): 1
for j in range(i): 22
print(i,end=' ') 333
print() 4444

Case 6:
#the loop is repeated with every character
for x in "ratan":
print(x)

name = input("Enter u r name:")


for x in name:
print(x)

45 | P a g e
Python Material Mr. Ratan

Assignments

1. In application take pin = 1234


Take the pin from end user
Do the pin verification if pin match congratulations, if pin not matched enter pin
Repeat 4-times after that say bye bye......
Ans:
pincode = 1234
for x in range(1,5):
data = int(input(f"enter pin code attempt {x} :"))
if data==pincode:
print("pin code is valid...congratuations...")
break
if(x==4):
print("Bye bye your attempts are completed.....")

2. Take the name from end user


print the vowels
print the consonants

output : enter your name : ratan


vowels are : aa
consonants are : rtn
Ans :
name = input("Enter your name:")
vowels = ""
consonants = ""
for x in name:
if x=='a' or x=='e' or x=='i' or x=='o' or x=='u':
vowels += x
else:
consonants += x
print("Vowels in ur name:",vowels,"\nConsonants in ur name:",consonants)

3. print the sum of 1-100 even numbers.


Ans : print(sum(range(0,101,2)))

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

case -7: increment & decrement

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)

case 8: Negative indexing.


for x in range(-8,-2):
print("hi students...",x)
for x in range(-7,-3,2):
print("Good morning...",x)
for x in range(-2,-8,-3):
print("Good Evening...",x)

case 9: write the output of below example.


for x in range(-10,-5):
print("ratanit:",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

For Loops with else block:

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')

The else block is not executed in three cases

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")

ex: write a program to print addition of 1-100 numbers.


sum=0
for i in range(1,100):
sum=sum+i
print(sum)

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

While with else block:


Along with the while loop possible to take the else block is always executed when while
loop terminated normally.
a=0
while(a<10):
print ("hi ratan sir",a)
a=a+1
else:
print("else block after while");

The else block is not executed in three cases

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")

ex: The below example represent infinite times.


while(True):
print ("hi ratan sir")

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

Material by Mr. Ratan...........

“Instead of blaming others


Find the right way to the work”

********* Topic Completed: Thank you ************Share the material to friends

51 | P a g e
Python Material Mr. Ratan

Python Variables & functions

 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.

There are three types of variables in python,


1. Local variables.
2. Global variables.
3. Non-local variables.

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)

Every function contains three parts


 Function declaration : Declare the function by using def keyword
 Function body : The main logic of the function.
 Function calling : Call the function by using function name

def wish(): # function declaration


print("good morning")
print("good Evening") # function body

wish() # function calling

There are two types of functions


1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.

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")

ex-2: local variables


 The variables declared inside the function are called local variables.
 The function arguments also local variables.
 The scope of local variables only with in the function. We cannot access outside of the
function.

def wish():
name = "ratan"
print("Good morning...",name)

def add(num1,num2):
print(num1 +num2)

#function call
wish()
add(10,20)

ex-3: global variable :


 The variables which are declared outside of the function is called global variables.
 We can access the global variables in all the functions.

name = "ratan" # global variable


def wish1():
print("Good morning...",name)

def wish2():
print("Good Evening....",name)

#function calling
wish1()
wish2()

53 | P a g e
Python Material Mr. Ratan

ex-4: local variables & global variables : different variable names


num1 , num2 =10,20 #global variables
def add(val1,val2): #local variables(function arguments)
print(val1+val2)
print(num1+num2)
def mul(val1,val2):
print(val1*val2)
print(num1*num2)
#function calling
add(4,5)
mul(5,6)

ex-5: local variables & global variables : same variable names


if the application contains both local & global variables same name then to represent
global variables use global() function.

num1 , num2 =10,20


def add(num1,num2):
print(num1+num2)
print(globals()['num1']+globals()['num2'])
def mul(num1,num2):
print(num1*num2)
print(globals()['num1']*globals()['num2'])
#function calling
add(4,5)
mul(5,6)

ex-6: one function is able to call more than one function.


def happyBirthday(person):
print("Happy Birthday dear ",person)

def wish():
happyBirthday('ratan')
happyBirthday('anu')

wish()

ex 7: local vs. global variables at project level.


id,name,addr,school_name,school_code
student_info():
teacher_info():

#function call
call student_info
call teacher_info

54 | P a g e
Python Material Mr. Ratan

global keyword: used to represent global variables.

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)

case 2: Here taking local & global variables.


name = "ratan"
def wish():
name = "anu" # it is local data
print("Good Morning....",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

ex-2: write the output of the below example: assignment


def a_fun():
global foo
foo = 'A'
def b_fun():
global foo
foo = 'B'
#Function calling
b_fun()
a_fun()
print (foo)

ex 3: write the output of the below example: assignment


a = 10
def f():
print ('Inside f() : ', a)
def g():
a = 20
print ('Inside g() : ',a)
def h():
global a
a = 30
print ('Inside h() : ',a)

#function calling
print ('global : ',a)
f()
print ('global : ',a)
g()
print ('global : ',a)
h()
print ('global : ',a)

ex 4: write the output of the below example: assignment


a,b,x,y = 1,15,3,4
def foo(x, y):
global a
a = 42
x,y = y,x
b = 33
print (a,b,x,y)
#function calling
foo(17,4)
a. print (a,b,x,y)

56 | P a g e
Python Material Mr. Ratan

Function return Type:

The functions are two different formats


a. functions not returning the value.
b. function can return the value.

ex-1: Function return type.


def func1():
print("Good morning")
return 10
def func2():
print("Good Evening")
return 10,"ratan",10.5,True
def func3():
print("Good night")
def func4():
print("Good Afternoon")
return

#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

ex-2: we can handle the function return value in two ways,


 Hold the return value & print it.
 Directly printing return value.
def wish():
print("hi sir")
return "ratan"
#function calling
name = wish()
print(name)

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

ex-6: function return type & arguments.

def hello():
print('Hello!')

def print_welcome(name):
print('Welcome,', name)

def area(width, height):


return width * height

def positive_input(prompt):
number = float(input(prompt))
while number <= 0:
print('Must be a positive number')
number = float(input(prompt))
return number

name = input('Your Name: ')


hello()
print_welcome(name)
print('To find the area of a rectangle, enter the width and height below.')
w = positive_input('Width: ')
h = positive_input('Height: ')
print('Width =', w, ' Height =', h, ' so Area =', area(w, h))

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)

ex-3: mixing arguments : mixing default & required arguemtns


def emp_details(eid,ename="ratan",esal=10000.45):
print(eid,ename,esal)

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

def add(num1=4,num2,num3): invalid


def add(num1=3,num2=5,num3): invalid
def add(num1,num2=5,num3): invalid

def add(num1,num2=5,num3): invalid


def add(num1,num2,num3): 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)

case 2: we can pass the function arguments in two ways.


 Directly we can pass the constant values.
 We can pass the variables also.

def addition(x,y):
print x+y

#function call: directly passing constant values


addition(100 ,200)

#function call : here we are passing the variables


a,b=10,20
addition(a,b)

ex 5: Keyword arguments / named arguments:


def emp_details(eid,ename,esal):
print(eid,ename,esal)

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")

case 2: printing the sum of variable arguments.


def disp(*var):
print(sum(var))

#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

ex - 7: ** : it can take the argument data in key=value format


def disp(*var,**kwarg):
print(var)

#for loop by default it prints keys


for x in kwarg:
print(x)

#if you want values use values() function


for x in kwarg.values():
print(x)

#for loop to print both key=value use items()


for x,y in kwarg.items():
print(x,y)

print(sum(kwarg.values()))

#fnction call
disp(10,20,30,a=10,b=20,c=30)

Material by Mr. Ratan...........

63 | P a g e
Python Material Mr. Ratan

Inner Functions: nonlocal keyword:

ex 1: Declaring function inside another function is called inner functions.


def outer():
print("this is outer function")
def inner():
print("this is inner function")
#inner function calling
inner()

#calling outer function


outer()

ex 2: All inner functions can access outer function data


def outer():
name = "ratan"
def inner1():
print("this is inner fuction-1...",name)
def inner2():
print("this is inner fuction-2....",name)

#inner function calling(outer function code)


inner1()
inner2()

#calling outer function


outer()

ex 3: Inner function variable & outer function variable: just check the output.
def outer():
name = "ratan"
def inner():
name = "sravya"
print(name)

#inner function calling


inner()
print(name)

#calling outer function


outer()

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)

#inner function calling


inner()
print(name)

#calling outer function


outer()

ex 5: write the output of below code.


def outer():
name = "ratan"
def inner1():
nonlocal name
name = "naresh"
def inner2():
nonlocal name
name = "sravya"

print(name)
inner2()
inner1()
print(name)

#function call
outer()

65 | P a g e
Python Material Mr. Ratan

ex 6: write the output of the below example : assignment


def outer():
s="ratan"
def inner1():
s="durga"
def inner2():
nonlocal s
s="anu"
def inner3():
global s
s="sravya"
#Function calling [outer function code]
print(s)
inner1()
print(s)
inner2()
print(s)
inner3()
print(s)

outer()
print(s)

ex 7: writhe the output of the below example: assignment


y = 10
def outer():
x = 42
def inner():
nonlocal x
x=65
global y
y = 43

print(x)
inner()
print(x)

outer()
print(y)

66 | P a g e
Python Material Mr. Ratan

ex-8: writhe the output of the below example: assignment


val = 100
def outer():
name = "ratan"
def inner1():
nonlocal name
name = "anu"
def inner2():
global val
val =200
print(name)
inner1()
inner2()
outer()
print(val)

ex-9:
case 1: valid & recommended
def my_func():
print("hi students")
print("sat exam")

my_func()

case 2: valid but not recommended


def my_func():print("hi students"),print("sat exam")

my_func()

ex 10: doc string (documentation strings)


get the doc string using __doc__

def my_func():
"""
Author : Ratan
team size : 10
vendor : nareshit
"""
pass

print(my_func.__doc__)

67 | P a g e
Python Material Mr. Ratan

ex-11: type conversion process.


print(int(10))
print(int(10.7)) # 10.7 float format it is able to covert int
print(int(True))
print(int("10"))
#print(int("10.8"))ValueError
#print(int("ratan")) ValueError

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)))))

Material by Mr. Ratan...........


“focus on work
After completion of some work we will get some great feeling that is important”
*********** Topic completed ************

68 | P a g e
Python Material Mr. Ratan

PEP 8: PEP stands for Python Enhancement Proposal

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)

 while taking variable names, these names should be meaningful.


 if the variable name contains more than one word every word is separated with
underscore.
 variable name starts with lower case

pycharm IDE : (integrated development Environment)


1. community edition : support only python
2. professional edition: support all: Django flask , HTML , CSS , SQL

https://www.jetbrains.com/pycharm/download/

Assignment operator: pep


# valid but not recommended
num=10 # pep8 : missing whitespaces around operator

# valid and recommended


num = 20

Comma (,): pep


# valid but not recommended
num1,num2,num3 = 10,20,30 # pep8:missing whitespaces after ,

# valid and recommended


num1, num2, num3 = 10, 20, 30

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)

 while taking function name these names should be meaningful.


 if the function name contains more than one word every word is separated with
underscore.
 function name starts with lower case.
 function declaration to declaration two blank lines required.

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

# valid and Recommended


import time
import keyword

module names & package names PEP:


All predefined module names all characters are lower case.
All user defined module, package names must be short & lower case letters.

class-name PEP8: Class name should be camel case convention


#Valid Not Recommended
class myClass:
pass

camelCase: stats with upper & inner words start with upper.

#Valid & Recommended


class MyClass:
pass

line space:
line data break it is recommended to take 79 characters.

Material by Mr. Ratan...........

“Attend the classes Regularly then you will get the clarity on subject”

*********** Topic completed ************

71 | P a g e
Python Material Mr. Ratan

Material by Mr. Ratan...........

72 | P a g e
Python Material Mr. Ratan

Python Data types

 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

Strings Data type

There are two type of data,


1. mutable data : modifications are allowed.
2. immutable data : modifications are not allowed.

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.

name1 = "hi 'ratan' sir"


name2 = 'hi "ratan" sir' E:\>python first.py
name3 = '''hi "ratan" sir 'anu' madam''' hi 'ratan' sir
print(name1) hi "ratan" sir
print(name2) hi "ratan" sir 'anu' madam
print(name3)

 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

ex 3: Escape sequence characters: apply on string data


print("hi ratan sir")
print("hi \"ratan\" sir")
print("hi \'ratan\' sir")
print("hi \\ratan\\ sir")
print("hi\t ratan \t sir")
print("hi \n ratan \n sir")

ex 4: There are two types of strings


1. normal string: it allows escape sequence characters
2. raw string : it not allowed escape sequence characters : it starts with r

print("hi \t ratan \t sir") E:\>python first.py


print(r"hi \t ratan \t sir") hi ratan sir
print("hi \nratan \nsir") hi \t ratan \t sir
print(r"hi \n ratan \n sir") hi
ratan
sir
hi \n ratan \n

ex 5: There are three ways to format the data


a. %
b. {}
c. f
username,password = "ratan","anu"
print("User name=%s User password=%s"%(username,password))
print("User name={} User password={}".format(username,password))
print("User name={0} User password={1}".format(username,password))
print(f"User name={username} User password={password}")
print(f"User name={username} \nUser password={password}")

ex-6: Type conversion.


print(str(10)+str(20)) Output:
print(str(10.5)+str(20.5)) E:\>python first.py
print(str(True)+str(False)) 1020
print(str(0)+str(1)) 10.520.5
print(str("ratan")) TrueFalse
01
print(int(str(10))+int(str(20))) ratan
print(float(str(10.5))+float(str(20.3))) 30
30.8
print(bool(str(int(10.5)))) True
print(bool(int(str(20)))) True
2

76 | P a g e
Python Material Mr. Ratan

Ex-7: Data slicing: string allowed positive indexing

<string _name> [start _value: end _value: stepping _value]

<string _name> [low _value: high _value: increment _value]


name [2:6:2]

<string _name> [high _ value: low _value: decrement _value]


name [6:2: -2]

Note: The increment is done automatically by +1 but not decrement

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])

print(name[10]) IndexError: string index out of range

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

Ex-8: Data Slicing: Negative indexing


name = "nareshit"
#-8 -7 -6 -5 -4 -3 -2 -1

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])

print(name[-9]) IndexError: string index out of range

Ex-9: printing the string data using for loop.


name = "ratan"
for x in name:
print(x,end="")
print()

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)

res = s1*2 + s2*2


print(res)

Ex-11: Relational Operators: a = 97 A = 65 1 = 49 code representation


 possible to apply relational operators in string data. It returns Boolean value.
 The Strings are compared based on dictionary Order.
print("ratan">"anu")
print("ratan"<"anu")
print("ratan">="anu")
print("ratan"<="anu")
print("ratan"=="ratan")
print("ratan"!="anu")
print("ratna">"ratan")

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

Ex-13: len() function : To find the length of the string data.


strip() Functions : To remove the starting and ending spaces.
lstrip() : To remove the left side data.
rstrip() : To remove the right side data.

msg = " ratan "


print(msg)
print(msg.strip())

print(len(msg))
print(len(msg.strip()))

name = "@@@ratan###"
print(name.lstrip("@"))
print(name.rstrip("#"))
print(name.rstrip("#").lstrip("@"))

ex 14: index() rindex() find() rfind()

index()&find():Both functions returns index position of the data.


When we use find function, the element is no present it returns -1
When we use index function, the element is not present it will generate ValueError.

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

msg = "hi ratan sir"


print(msg.index("ratan"))
print(msg.find("ratan"))

80 | P a g e
Python Material Mr. Ratan

ex 15: startswith() endswith() functions return Boolean value.


s = "1AR12JR2345"
print(s.startswith("1AR"))
print(s.startswith("2JR"))
print(s.endswith("345"))
print(s.endswith("222"))

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))

ex 16: split () function used to split the data.


#The default splitting char is space
msg = "hi ratan sir"
result = msg.split()
for x in result:
print(x)
#Here the splitting char is comma
msg = "hi this,is class,hi ratan,sir sorry"
result = msg.split(",")
for x in result:
print(x)
#Here splitting the data using word: ratan
msg = "hi ratan sir"
words = msg.split("ratan")
for x in words:
print(x)

ex 17: upper() lower() capitalize() replace() swapcase()


text = "hi Ratan sir python is very good"
print ("upper =>", text.upper())
print ("lower =>", text.lower())
print ("capitalize =>", text.capitalize())
print ("replace =>", text.replace("python", "Django"))
print ("swap case=>",text.swapcase())

81 | P a g e
Python Material Mr. Ratan

ex 18: finding minimum and maximum using min() & max().


name = "ratan"
print(min(name))
print(max(name))

name = "ratan124"
print(min(name))
print(max(name))

ex 19: Isalnum() isalpha() isdigit()


#isalnum() it will take alphabets , numarics & both
str1 = "python"
print (str1.isalnum())
str2 = "121223"
print (str2.isalnum())
str3 = "Python36"
print (str3.isalnum())
#isalpha() it will check only alphabets
str1 ="python"
print (str1.isalpha())
str2 ="Python3.1.6"
print (str2.isalpha())
#isdigit() it will check only digits
str1 = "python";
print (str1.isdigit())
str2 = "98564738"
print (str2.isdigit())

ex 20 : islower() isupper() isspace()


# Here checking the data is lower case or not.
str1 = "RATAN";
print (str1.islower())
str2 = "ratan"
print (str2.islower())
#Here checking the data is upper case
str1 = "RATAN";
print (str1.isupper())
str2 = "ratan"
print (str2.isupper())
#Here checking the data is space or not
str1 = "python"
print (str1.isspace())
str2 = " ";
print (str2.isspace())

82 | P a g e
Python Material Mr. Ratan

Assignments & interview questions:


Assignment-1 Count the number of a occurrences in given string without using count function.
count=0
for i in "ratanit":
if(i=="a"):
count=count+1
print("a charcater occur:",count)

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)

Assignment 3 : python program perform sorting of words in given input String


mystr = input("Enter a string: ")
# breakdown the string into a list of words
words = mystr.split()

# sort the list


words.sort()
for word in words:
print(word)

# reverse sort the list


words.sort(reverse=True)
for word in words:
print(word)
Errors in Strings data type:
NameError:
str = "hi sir" G:\>python first.py
print (substring(2,4)) NameError: name 'substring' is not define

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'

***********String completed : Thank you **********

83 | P a g e
Python Material Mr. Ratan

List data type: (list)

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]

Homogeneous Data: numbers = [10,20,30,40]


Heterogeneous Data: data = [10,10.4,'ratan']

 List is mutable object so we can do the manipulations.


 In list insertion order is preserved it means in which order we inserted element same order
output is printed.

 List duplicate objects are allowed.


Data = [10,20,10,10.5,10]
 list supports both positive & negative indexing.
Positive index starts from: 0 forward
Negative index starts from: -1 backward

ex-1: Declaration of list data.


#list of homogenous data
numbers = [10,20,30,40]
print(numbers)

#list of heterogeneous data


data = [10,10.5,'ratan']
print(data)

#list of duplicate values


duplicate_date = [10,20,10,10.5,30,10]
print(duplicate_date)

# empty list declaration


list_data = []
print(list_data)
print(type(empty_list)

84 | P a g e
Python Material Mr. Ratan

ex-2: list type conversion process.


l1 = list("ratan")
print(l1)
l2 = list("2020")
print(l2)

l3 = list(range(1,11))
print(l3)
l4 = list(range(1,10,3))
print(l4)

l5 = list()
print(l5)

#l6 = list(True) TypeError: 'bool' object is not iterable


#l6 = list(10.5) TypeError: 'float' object is not iterable
#l6 = list(10) TypeError: 'int' object is not iterable

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

ex 3: data slicing: positive indexing


[start _ index: end index: stepping _value]

[low _value: high _value]


by default, increment is +1

[low_ value: high _value: increment _value]


[3:9:3]
[high_ value: low_ value: decrement _value]
[9:3:-2]

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

ex 4: data slicing: Negative indexing


data = [10,20,30,40,50]
# -5 -4 -3 -2 -1

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])

print(data[-8]) IndexError: list index out of range

ex 5: List data unpacking.


 we are unpacking the list data storing into multiple variables.
 If the unpacking is not possible we will get : ValueError.

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

ex 6 : print the data using for loop.


names = ["ratan","ranu","raju","rani"]
for x in names[2:4]:
print(x)

#here names[2] taking only one element in str format


names = ["ratan","ranu","raju","rani"]
for x in names[2]:
print(x)
names = ["ratan","ranu","raju","rani"]
for x in names[2]+names[3]:
print(x)

#herenames[1:2] it is slicing so it returns the data list format


names = ["ratan","ramu","raju","rani"]
for x in names[1:2]:
print(x)

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)

ex 7: Adding data in list using for loop.


l1 = [x for x in range(1,6)] l6 = [[x,x*x] for x in range(1,6)]
print(l1) print(l6)

l2 = [x*99 for x in range(1,6)]


print(l2) Output:
E:\>python first.py
l3 = [x//2 for x in range(1,6)] [1, 2, 3, 4, 5]
print(l3) [99, 198, 297, 396, 495]
[0, 1, 1, 2, 2]
l4 = [x//2 for x in range(1,6) if x%2==0] [1, 2]
print(l4) [2, 4, 6]
[[1, 1], [2, 4], [3, 9], [4, 16],
l5 = [x for x in range(1,10) if x%2==0 and x<7] [5, 25]]
print(l5)

88 | P a g e
Python Material Mr. Ratan

ex 8: Working with sub list.

list_data = [[1, 10,"ratan"],[2,"anu",9],[1,2,3]]


print(list_data[0])
print(list_data[1])
print(list_data[2]) Output :
E:\>python first.py
print(list_data[0][0]) [1, 10, 'ratan']
print(list_data[1][1]) [2, 'anu', 9]
print(list_data[2][2]) [1, 2, 3]
1
print(list_data[0][1]) anu
print(list_data[1][0]) 3
print(list_data[2][1]) 10
2
print(list_data[0][2][-1]) 2
print(list_data[1][1][0]) n
a
#to use this for loop the sub list length must be same 10 anu 2
for x,y,z in list_data:
print(y,end=" ")

ex 9: in ,not in : To check the data available or not& it return Boolean value.

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

Ex-10: == & is , is not


 To check the memory address use is & is not operator it returns Boolean value
 == operator for data comparison it returns Boolean value.

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)

ex 11 : concat & replication


#Concat (combining the data stored in new variable)
l1 = [10,20,30]
l2 = [40,50,60]
result = l1 + l2
print(result)

# replication (same data duplicated)


result = l1*2 + l2*2
print(result)

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

ex 12: sort() sorted() functions to perform sorting.


 sort() function will sort the data in memory.
 sorted() function data will print in sorting order but data in memory is not sorted.
 To perform sorting operation the must be homogenous otherwise we will get TypeError.

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))

#here the data will sort because int,float,bool is number type.


data = [10,10.5,True]
data.sort()
print(data)
list_data = [10,10.3,"ratan"]
list_data.sort()
print(list_data) #TypeError
ex 13: min() max() sum() functions
numbers = [1,2,3]
print(sum(numbers))

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))

data = [10,10.5,"ratan"] TypeError


print(min(data))
print(max(data))
Note : To find max & min the must be homogenous otherwise we will get TypeError.

91 | P a g e
Python Material Mr. Ratan

ex 14: it is possible to apply relational operators on list data.


l1 = [1,4,5,6]
l2 = [1,4,8,6]
print(l1>l2)
print(l1<l2)

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

ex-15: list data is mutable it allows modifications.


 The append function list.append(x) will add an item (x) to the end of a list.
 The list.insert(i,x) method takes two arguments, where i = index x= item .
 To add one list data into another list use the list.extend(L) method.
 we can use list.copy() to make a copy of the list.
 It is possible to replace the data using index position.

#Append the data at last


fruits = ['mango','banana','apple']
fruits.append("orange")
print(fruits)

#insert the data at specified location


numbers = [1,2,3,4]
numbers.insert(2,100)
numbers.insert(8,"ratan") # if the index is not available by default it will add the data at last.
print(numbers)

#adding one list into another list


l1 = [10,20,30]
l2 = [1,2,3]
l1.extend(l2)
print(l1)

#copy the data using copy()


data = [10,"ratan",True,10.5]
copydata = data.copy()
print(data is copydata)
print(data==copydata)

#Replace the data in index


animal = ['rat','tiger']
animal[1]="lion"
print(animal)

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

ex-16: Removing the data from list.

 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.

#remove the data at last


fruits = ['mango','banana','apple']
fruits.remove("banana")
print(fruits)

#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)

#remove the data using slicing


numbers = [1,2,3,4]
del numbers[2:]
del numbers[:1]
print(numbers)

#clear all elements from list using clear()


data = [10,"ratan",True,10.5]
data.clear()
print(data)

94 | P a g e
Python Material Mr. Ratan

ex-17: Functions of list.


 len() function to find the length of the list.
 List.index() used to print the index of element. If the element is not available generates
error : ValueError: 'banana' is not in list.

 The reverse() function is used to reverse the order of items.


 The list.count(x) method will return the number of times the value x occurs within a
specified list.

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)

ex -18: operations on list data.


data = [1,2,["ratan","anu"],"sravya"] Output:
print(len(data)) E:\>python first.py
4
print(data[2][1]) anu
print(data[2][1][2]) u
print(data[3][1]) r
[1, 34, [1, 2, 3], 'ratan', 100]
l1 = [1,34,[1,2],"ratan"]
l1[2].append(3)
l1.append(100)
print(l1)

ex-19: sub list replication


print([10,20]*2) output:
print([["ratan"]*2]) E:\>python first.py
print([["ratan"]*2]*2) [10, 20, 10, 20]
[['ratan', 'ratan']]
data = [[1,2],[1,2]] [['ratan', 'ratan'], ['ratan', 'ratan']]
print(data*2) [[1, 2], [1, 2], [1, 2], [1, 2]]
print(data[0]*2) [1, 2, 1, 2]

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:

Note: This generates a list containing 3 different lists of length two.

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)

[['ratan', 'ratan'], ['ratan', 'ratan'], ['ratan', 'ratan']]


[['ratan', 'ratan'], ['ratan', 'ratan'], ['ratan', 'ratan']]

***********List Completed ******************Thankyou**************

96 | P a g e
Python Material Mr. Ratan

Tuple data type : (tuple)

list vs. tuple:


list is mutable : modifications are allowed : [] : [10,20,30,40]
tuple is immutable : modifications are not allowed : () : (10,20,30,40)

Ex-1: tuple declarations. # comments are to understand the application

# tuple of integers (homogenous data)


t1 = (10,20,30)
print(t1)

# tuple of heterogeneous data


t2 = (10,20.5,"ratan")
print(t2)

# tuple of duplicates is allowed


t3 = (10,20,10,20,30)
print(t3)

# In tuple only one element it must separate with comma otherwise it is <class 'int'>
t4 = (10)
print(type(t4))

#Tuple only one element it is separate with comma <class 'tuple'>


t5 = (10,)
print(type(t5))

# empty tuple
t6 = ()
print(t6)

# tuple parenthesis is optional but recommended.


t7 = 10,20,30
print(t7)

when we declare the tuple parenthesis optional but recommended:


t1 = 10,20,30 valid: but not recommended
t2 = (10,20,30) valid : recommended

97 | P a g e
Python Material Mr. Ratan

ex 2: Type conversion process.


t1 = tuple("ratan")
print(t1)
t2 = tuple("2020")
print(t2)

t3 = tuple(range(1,11))
print(t3)
t4 = tuple(range(1,10,4))
print(t4)

t5 = tuple()
print(t5)

t6 = tuple(True) TypeError: 'bool' object is not iterable


t7 = tuple(10) TypeError: 'int' object is not iterable
t8 = tuple(10.5) TypeError: 'float' object is not iterable
Note: When we are doing type conversion the data must be iterable data, But if we give only one
element we will get TypeError.

ex 3: printing the data using for loop.


fruits = ("apple","orange","mango","banana")
for x in fruits:
print(x)
for x in fruits:
if x=="mango":
break
print(x)

for x in fruits[2:5]:
print(x)

# this for loop having one element but tuple format


for x in fruits[2:3]:
print(x)

# this for loop having one element only but string format
for x in fruits[3]:
print(x)

ex-4: Adding the data using for loop.


#list data type conversion not required
list_data = [x*99 for x in range(1,11)]
print(list_data)

# tuple data type conversion required


tuple_data = tuple(x*99 for x in range(1,11))
print(tuple_data)

98 | P a g e
Python Material Mr. Ratan

Ex-5: Indexing both forward & backward.

<tuple _name> [start _value: end _value: stepping _value]

< tuple _name> [low _value: hig0h _value: increment _value]


name [2:6:2]

< tuple _name> [high _ value: low _value: decrement _value]


name [6:2: -2]

Note: The increment is done automatically by +1 but not decrement

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])

print(data[8]) IndexError: tuple index out of range

99 | P a g e
Python Material Mr. Ratan

ex 6: data slicing: negative slicing

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])

#print(data[-7]) IndexError: tuple index out of range

ex 7: unpacking one elements & multiple elements.


t1 = (10,20.5,"ratan")
a,b,c = t1
print(a,b,c)
print(type(a),type(b),type(c))

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)

ex 9 : concat & replication.


t1 = (10,20,30)
t2 = (40,50,60)
res = t1+t2
print(res)

res = t1*3 + t2*2


print(res)

ex 10: tuple sorting not allowed because it is immutable data.


But sorted() allowed because it is not doing modifications, just it is print report in sorted format.
numbers = (45,32,4,5,10)
print(sorted(numbers))
print(sorted(numbers,reverse=True))
print(numbers)

ex 11: Finding minimum & maximum


t1 = (10,20,4,3,5)
print(max(t1))
print(min(t1))
t2 = ("ratan","anu","sravya")
print(max(t2))
print(min(t2))

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

ex-12: is, is not : memory comparison


== , != : data comparison
#tuple is immutable so ref-variables are pointing to same memory
t1 = (10,20,30)
t2 = (10,20,30)
print(t1 is t2)
print(t1==t2)

#string is immutable so ref-variables are pointing to same memory


str1 = "ratan"
str2 = "ratan"
print(str1 is str2)
print(str1==str2)

#list is mutable so ref-variable are pointing to different memory


l1 = [10,20,30]
l2 = [10,20,30]
print(l1 is l2)
print(l1==l2)

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

ex 14: in , not in : to check data available or not.


t1 = (10,20,30)
print(10 in t1)
print(100 in t1)

print(10 not in t1)


print(100 not in t1)

ex-15: tuple functions.


data = (10,20,30,10)
print(sum(data))
print(len(data))

print(data.index(30))
print(t.index(10,2,4))

print(t.count(10))

t1 = ("HELLO", 5, [], True)


t1[2].append(100)
print(t1)
print(id(t1))

************ Tuple completed: Thank you ******************

103 | P a g e
Python Material Mr. Ratan

Set Data Type

list vs. set:


list duplicates are allowed.
set duplicates are not allowed.

set data type:


1. set is a data type to store group of elements.
2. declare the set data using {}
3. set duplicates are not allowed.
4. set does not support indexing so no data slicing.
5. set insertion order not preserved
6. set is mutable so we can do the modifications.

ex-1:
# set of integers
my_set = {1, 2, 3}
print(my_set)
print(type(my_set))

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

# set duplicates not allowed


my_set = {1,2,3,1,2,3}
print(my_set)
print(len(my_set))

#creates empty set : but it is empty dictionary but not set


s={}
print(s)
print(type(s)) # <class, ‘dict’>

#creates empty set


s=set()
print(type(s)) #<class 'set'>

 In set it is possible to insert only immutable data : String , Number , Tuple


 In set it is not possible to insert mutable data like set,list ,dict , if we are trying to insert
mutable data we will get Type error.
o s = { [1,2,3],"ratan"} TypeError: unhashable type: 'list'
o s = { {1,2,3},"ratan"} TypeError: unhashable type: 'set'
o s = {{10:"aaa"},10,20} TypeError: unhashable type: 'dict'

104 | P a g e
Python Material Mr. Ratan

ex 2: type conversion process.


s1 = set("ratan")
print(s1)

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)

#eliminating duplicated from list


print(set([10,20,10,40,30]))

s6 = set(10) TypeError: 'int' object is not iterable


s7 = set(10.5) TypeError: 'float' object is not iterable
s8 = set(True) TypeError: 'bool' object is not iterable

ex 3: unpacking operations: valid but not recommended


s1 = {10,20,30}
a,b,c = s1
print(a,b,c)

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)

ex 4: print the data using for loop


s1 = {10,20,30}
for x in s1:
print(x)

for letter in set("apple"):


print(letter)

105 | P a g e
Python Material Mr. Ratan

ex 5: we can add the data into set in two ways.


#add():
a. using add() we can add only one element.
b. using add() we can add only immutable data.
#update()
a. using update() we can add multiple elements.
b. by using update we can add the mutable & immutable data in set.
c. by using update not possible to add the single element.

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.

ex 6 : id() is & is not in, not in


 To print the id of the dictionary id() function, it print memory address.
 To check the memory address use is & is not operator.
 == operator will check the data in set not memory If the data same returns true otherwise false.

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)

y = {i*i for i in range(10) if i%2==0}


print(y)

z= {(i,i*10) for i in range(10,20,2)}


print(z)

ex 8 : remove the data from set.


my_set = {1,2,3,4,5}
my_set.discard(4)
my_set.discard(7) # if the data not present : no error
print(my_set)

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'}

# Removes all elements


my_set = {1,2,3,4,5}
my_set.clear()
print(my_set)

ex 9: copy the set data


my_set = {1,2,3}
copy_set = my_set.copy()

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

ex 10 : finding min & max


s1 = {10,20,30,3,2}
print(min(s1))
print(max(s1))

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'

ex 11: operations on set data.


s1 = {10,20,30,3,2}
s2 = {10,4,5,3,2}
print(s1-s2) # preset in s1 not in s2 # 20 30
print(s1 & s2) # all comman elements # 10 3 2
print(s1 | s2) # all unique elements # 10 20 30 3 2 4 5
print(s1^s2) # without comman elements #20 30 4 5

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

basket1 = {'orange', 'apple', 'pear','banana'}


basket2 = {'pear', 'orange', 'banana'}
print(basket1-basket2)
print(basket1&basket2)
print(basket1|basket2)
print(basket1^basket2)

***********Thank you ************

108 | P a g e
Python Material Mr. Ratan

Dictionary data type


dict introduction:
 dict is a data type to store the group of elemetns in the form of key,value pairs. here key is a
object & value also object.
The key,value pair also known as item.
The key,value separator is colan.

 declare the dict data using {}


{111:"ratan",222:"anu",333:"sravya"}

 key must be unique, values can be duplicated.


 Insertion order is not preserved.

 Dict not support indexing so slicing not possible.


 dict is mutable so modifications are allowed.

ex 1: dict declarations.
phone = {"ratan":9090909,"anu":8080808,"sravya":707070}
print(phone)

# dict contains dif types of data


d1 = {1:"ratan","anu":10.6}
print(d1)

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

ex 2: type conversion process.


l1 = [10,20,30]
l2 = ["ratan","anu","sravya"]
d1 = dict(zip(l1,l2))
print(d1)

t1 = (1,2,3)
t2 = ("aaa","bbb","ccc")
d2 = dict(zip(t1,t2))
print(d2)

d3 = dict(zip(range(1,6),[x*x for x in range(1,6)]))


print(d3)

d4 = {x:x*x for x in range(1,6)}


print(d4)

# empty dictionary
x = dict()
print(x)

res = dict(zip(range(1,6),range(10,60,10)))
print(res)

d1 = {[1,2,3]:"ratan"} TypeError: unhashable type: 'list'

ex-3 : we can read the data from dictionary in two ways


a. By using keys : If the key is not present generate KeyError
b. By using get method : If the key not present return None

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

ex 4 : keys() : To read all the keys.


values() : To read all the values.
items() : To read both key & value

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()))

ex 5: Assignment: create the new dict using d1 keys() d2 values().


d1 = {11:"aaa",22:'bb',33:'cc'}
d2 = {1:"ratan",2:'sravya',3:'anu'}

ans:
d1 = {11:"aaa",22:'bb',33:'cc'}
d2 = {1:"ratan",2:'sravya',3:'anu'}
res = dict(zip(d1.keys(),d2.values()))
print(res)

ex 6: printing the data using for loop


phone = {"ratan":9090909,"anu":8080808,"sravya":707070}
# by default the for loop will print only keys
for x in phone:
print(x)
for x in phone.values():
print(x)

#Here the key value is coming in tuple format


for x in phone.items():
print(x)
for k,v in phone.items():
print(k,v)

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}


for i in squares:
print(i,squares[i])

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)

ex 8: for loop to add the data.


data = {i:i*i for i in range(1,6)}
print(data)

data = {i:i*i for i in range(1,6) if i%2==0}


print(data)

data = {i:i/i for i in range(1,6) if i%2==0}


print(data)

data = {i:i//i for i in range(1,6) if i%2==0}


print(data)

data = {i:i%i for i in range(1,6) if i%2!=0}


print(data)

112 | P a g e
Python Material Mr. Ratan

ex 9: adding the data into dict.

#Updating data
mydict = {"ratan":28,"anu":25,"durga":30}
mydict["ratan"]=35
print(mydict)

# substituting one dict into another dict


d1 = {1:"ratan",3:"anu"}
d2 = {2:"aaa",4:"bbb"}
d3 = {**d1,**d2,111:"naresh"}
print(d3)

#adding one dict into another dict


d1={1:"ratan",2:"anu"}
d2={3: "ratan",4:"anu"}
d1.update(d2)
print(d1)

#Copying Dictionary data


d1={1:"ratan",2:"anu",3:"durga",4:"aaa"}
d2 = d1.copy()
print(d2)

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 **.

ex 10: remove the data from dict.


phonebook = {“ratan":938477,"anu":938372,"sravya":909090}
del phonebook["sravya"]
#del phonebook["naresh"] KeyError: 'naresh'
print(phonebook)

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

ex 11: creating duplicate value for multiple keys.


l1 = [1,23,31,40]
res = dict.fromkeys(l1,"ratan")
print(res)

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'}

ex 12: sorting operations.


# printing the data ascending order
d1 = {'b':"ratan",'c':"anu",'a':"sravya"}
print(sorted(d1)) #sorting is done based on keys
print(sorted(d1.values()))
print(sorted(d1.items()))

#Printing the data descending order


print(sorted(d1,reverse=True)) #sorting is done based on keys
print(sorted(d1.values(),reverse=True))
print(sorted(d1.items(),reverse=True))

#length of the dictionary


d1 = {1:"ratan",2:"anu",3:"durga"}
print(len(d1))
print(len(d1.keys()))
print(len(d1.values()))

ex 13 : min & max based on keys


d1 = {1:"ratan",2:"anu",3:"sravya"}
print(min(d1))
print(max(d1))

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

ex-14: write the output of below example.


d2 = {1:{11:"ratan",22:"anu"},2:[10,20,30]}
print(d2[1][22])
print(d2[2][1])
print(d2[1][22][-1])

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

Ex-2 : eval() function to take multiple inputs.


res = eval(input("Enter a expresson:"))
print(res)

x,y,z = eval(input("Enter three numbers:"))


res = x+y+z
print(res)
x,y,z = eval(input("Enter three numbers:"))
res = x+y+z
print(res)

x,y,z = eval(input("Enter three numbers:"))


res = x+y+z
print(res)
x,y,z = eval(input("Enter three numbers:"))
res = x+y+z
print(res)

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

ex-3: join() function to join the data.

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

Lambda, Filter, Map, Reduce


Lambda Expression:
 A lambda function is an anonymous function (A function without name).
 This function can have any number of arguments but only one expression, which is evaluated
and returned. This is single line of expression to reduce the length of the code.
 def keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions.
 Lambda functions are used along with built-in functions like filter(), map() etc.
syntax: lambda arguments: expression

ex 1: function code vs. lambda code


#function code
def my_func(num):
return num*num
print(my_func(10))
#lambda code
lamb = lambda num:num*num
print(lamb(10))
#funcion code
def my_func1(num1,num2):
return num1*num2
print(my_func1(10,20))
#lambda code
lamb = lambda num1,num2:num1*num2
print(lamb(10,20))
#lambda code
lamb = lambda num1,num2:num1 if num1>num2 else num2
print(lamb(10,20))

ex-2: single line of lambda to give the input also.


res = (lambda x: x + 1)(2)
print(res)
res = (lambda x,y:x*y)(2,3)
print(res)
full_name = lambda first, last: f'Full name: {first.title()} {last.title()}'
print(full_name('guido', 'van rossum'))

ex-3: lambda with different inputs.


print((lambda x, y, z: x + y + z)(1, 2, 3))
print((lambda x, y, z=3: x + y + z)(10, 20))
print((lambda x, y, z=3: x + y + z)(4, y=2))
print((lambda *args: sum(args))(10,20,30))
print((lambda **kwargs: sum(kwargs.values()))(one=11, two=22, three=33))

118 | P a g e
Python Material Mr. Ratan

Filter: filter used to filter some data from complete data.


filter(filter_logics , input_data)

ex 1 : filter the values from given list.


#Normal code to filter the even values
data = [4,5,6,22,3,9,8]
even = []
for x in data:
if x%2==0:
even.append(x)
print(even)

#Normal code to filter the even values


print([x for x in data if x%2==0])

#filter logics with function


data = [4,5,6,22,3,9,8]
def my_func(num):
if num%2==0:
return True
print(list(filter(my_func,data)))

#filter logics with lambda


data = [4,5,6,22,3,9,8]
print(list(filter(lambda x:x%2==0,data)))

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)))

#Filtering the even values below 10


data = [5,34,24,45,2,7,4]
print(list(filter(lambda x:x%2==0 and x<10,data)))

#filter vowels from name


name = "niveditha"
print(list(filter(lambda x : x in ['a','e','i','o','u'],name)))

#filter consonants from name


name = "niveditha"
print(list(filter(lambda x : x not in ['a','e','i','o','u'],name)))

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)))

#Adding “it” for all elements


names = ["ratan","anu","sravya","naresh"]
print(list(map(lambda x : x+"it",names)))

#perform floor division on all elements


data = [4,6,8,3,5,9]
res = list(map(lambda x:x//2,data))
print(res)

ex 2: converting 2020 to different formats(int,float,bool....)

print(list(map(int,"2020"))) E:\>python first.py


print(list(map(float,"2020"))) [2, 0, 2, 0]
print(list(map(str,"2020"))) [2.0, 0.0, 2.0, 0.0]
print(list(map(bool,"2020"))) ['2', '0', '2', '0']
print(list(map(bool,[1,0,0,1]))) [True, True, True, True]
[True, False, False, True]

Observation: print(list(map(int,2020))) # Type Error


while conversion if you are passing only one element, we will get Type Error.

ex 3: Applying function on every element.

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

ex 4: passing multiple inputs


l1 = [1,2,3]
l2 = [10,20,30]
l3 = [100,200,300]
res = list(map(lambda x,y,z:x+y+z,l1,l2,l3))
print(res)

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]

Material by Mr. Ratan...........

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

Two distinguishable kinds of errors:


1. syntax errors
2. Exceptions.

 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.

 The dictionary meaning of the exception is abnormal termination.


 An unexpected event raised during the execution of the application to disturb the normal flow of
execution is called exception.

Whenever the exception raised in program,


o Program terminated abnormally
o Rest of the application not executed.
 To overcome above problem, we can handle the exceptions by using try-except blocks.

Once we handle the exception: Advantages of Exception handling:


 Program terminated normally.
 Rest of the application executed.
Keywords in exception handling:
try : Logics it may or may not raise an exception.
except : These logics are executed when exception raised in try.
else : These logics are executed when there is no exception try.
finally : These logics are executed both normal cases & abnormal cases.
raise : We can raise both predefined exceptions & user defined exceptions.

ZeroDivisionError : Occurs when a number is divided by zero.


NameError : It occurs when a name is not found. It may be local or global.
IndentationError : If incorrect indentation is given.
IOError : It occurs when Input Output operation fails.
IndexError : Raised when a sequence subscript is out of range.
ImportError : Raised when an import statement fails to find the module definition
KeyError : Raised when a dictionary key is not found in the set of existing keys.
MemoryError : Raised when an operation runs out of memory
SyntaxError : Raised when the parser encounters a syntax error.

123 | P a g e
Python Material Mr. Ratan

Exception handling hierarchy:

124 | P a g e
Python Material Mr. Ratan

Exceptions handling by using try-except blocks:


Syntax:
try:
Exceptional code (it may or may not raise an exception)
except :
Code runs when exception raised in try block

 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.

# Application with try-except block


try:
a=10/0
except ArithmeticError:
print (10/2)
print("rest of the Application")

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 4: syntax error: only try blocks are not allowed.


try:
print("ratan")

ex 5 : syntaxerror : try with immidiate except block required


in between the blocks statemetns are not allowed
try:
st-1
st-2
print("ratan")
except:
st-1
st-2

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

Category-1: try with multiple except blocks

case 1: try with multiple except blocks


try:
n = int(input("enter a number:"))
print(10/n)
print(10+"ratan")
except ZeroDivisionError as e:
print("ratanit...",e)
except TypeError as a:
print("nareshit.....",a)
except ValueError as x:
print("anuit ....",x)
print("rest of the app")

case 2: Exception or BaseException can handle all the exceptions.


try:
n = int(input("enter a number:"))
print(10/n)
print(10+"ratan")
except Exception as e:
print("ratanit...",e)
print("rest of the app")

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")

in above example ZeroDivisionError will be ignored.

127 | P a g e
Python Material Mr. Ratan

Category-2 : else block

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

Category-3 : default except

case 1: The except without any exception is called default except


The default except can handle all types of exception.

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")

case 2: the default except must be last statment.


try:
n = int(input("enter a num:"))
print(10/n)
except:
print("exception raised")
except ZeroDivisionError as a:
print("expetio info=",a)
print("Rest of the app")

SyntaxError: default 'except:' must be last

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

Category-5 : exception handling


Case 1: here we are handling the exceptions in function body.
def my_func():
try:
n = int(input("Enter a num:"))
print(10/n)
except (ZeroDivisionError,ValueError) as e:
print("got it in the function :-) ", e)

#function call
my_func()

Case : Here we are handling exceptions in function calling.


def m1():
n = int(input("enter a num:"))
print(10/n)
#function calling
try:
m1()
except (ArithmeticError,ValueError) as a:
print("exception raised=",a)
print("Rest of the app")
write the output of above two cases using below three options.
enter a num : 0
enter a num : 5
enter a num : "ratan"

129 | P a g e
Python Material Mr. Ratan

Category-6 Nested try-except block:


 In outer try block if there is no exception then outer else block will be executed.
 In inner try block if there is no exception then inner else block will be executed.

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")

enter a number: 0 enter a number: 2


outer try block outer try block
Inner try block Inner try block
Inner finally block 5.0
outer except block Inner finally block
outer finally block else block execute
Rest of the Application outer finally block
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>

case 1: Normal termination


try: case 4: Abnormal Termination
print("try") try:
except ArithmeticError as e: print(10/0)
print("except") except ArithmeticError as e:
finally: print(10+"ratan")
print("finally") finally:
print("finally block")
case 2: Normal termination
try: case 5: Abnormal Termination
print(10/0) try:
except ArithmeticError as e: print("try")
print("except") except ArithmeticError as e:
finally: print("except")
print("finally") finally:
print(10/0)
case 3: Abnormal Termination
try: case 6: Normal termination
print(10/0) try:
except TypeError as e: print("try")
print("ratanit") finally:
finally: print("finally")
print("finally")

131 | P a g e
Python Material Mr. Ratan

In two cases finally block is not executed


 if the control is not entered in try block
 when we use os._exit(0)

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

write the valid & invalid cases:

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:

There are two types of exceptions.


1. predefined exception : ArithmeticError
2. user defined exceptions : InvalidAgeError

 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")

ex : raising predefined exceptions valid but not recommended


because predefined exception having some fixed meaning.

age = int(input("Enter u r age:"))


if age>22:
print("eligible for mrg")
else:
raise ValueError("u r not eligible")

creation of user defined exceptions:


 Exception without description : constructor not required.
 Exception with description : constructor required.

ex-1 : creating user defined exception without description.


#step 1: create the user exception
class InvalidAgeError(Exception):
pass

#step2: use the excetion i project


age = int(input("Enter u r age:"))
if age>22:
print("eligible for mrg")
else:
raise InvalidAgeError()

135 | P a g e
Python Material Mr. Ratan

ex -2 : creating user defined exception with description.


step 1: create the exception
#userexceptions.py
class InvalidAgeError(Exception):
def __init__(self,msg):
pass

step 2: use the exception in our application


#first.py
from userexceptions import InvalidAgeError
age = int(input("Enter u r age:"))
if age>22:
print("eligible for mrg")
else:
raise InvalidAgeError("u age is too less try after some time")
E:\>python first.py
Enter u r age:12
userexceptions.InvalidAgeError: u age is too less try after some time

Assignment:
Create exception : TooYoungError : without description

Create Exception : TooOldError : with description

Take the age from end user:


If age below 22 years : age <22 : raise TooYougError
If the age above 35 years age>35 : age>35 : raise TooOldError
If the age between 22 to 35 : "Happy Married Life"

Material by Mr. Ratan...........

"Focus on how to get the job......"

********* Completed: Thank you ************

136 | P a g e
Python Material Mr. Ratan

File Handling in Python

 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.

Generally, we divide files in two categories,


a. Text file
b. Binary file.

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

To perform file handling, we need to perform steps:


Open File
Read / Write File
Close File

The steps are fallowed to design application:


step 1: open the file : using open() function.
step 2: read or write operations : using read() write() functions.
step 3: close the file : using close() function

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

Step 1: open the file


Opening a File:
Before working with Files you have to open the File. To open a File, Python built in
function open() is used. It returns an object of File which is used with other functions.

The open function takes two arguments, the name of the file and the mode of operation.
f = open (filename, mode)

The default file operations is read mode


f = open("test.txt") # open file in current directory
f = open("C:/Python33/ratan.txt") # specifying full path

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.

Step 3: close the file


Once you are finished with the operations on File at the end you need to close the file. It
is done by the close() method.

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

ex-1: writing the data to file


write operations: mode 'w’: file is optional
if the file is not available then it will create & write the data.
if the file is available it overrides the data.

f = open("sample.txt",'w')
f.write"hi ratan sir \n welcome to ratanit")
f.close()
print("operations are completed.....")

ex-2: Reading the data from the file.


read operations: mode 'r ‘: file is mandatory: it is default mode
if the file is available it will read the data.
if the file is not available it will give FileNotFoundError.

f = open("sample.txt")
data = f.read()
print(data)
f.close()
print("Operations are successfull.....")

ex-3: appending the data to file.


Append operations: mode 'a’: file is optional
if the file is available it will append the data.
if the file is not available then it will create append the data.

f = open("sample.txt",'a')
f.write("\n Good Morning")
f.close()
print("Operations are successfull")

ex 4: getting some file information.


name Returns the name of the file.
mode Returns the mode in which file is being opened.
closed Returns Boolean value. True, in case if file is closed else false.

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

ex 5: a. The read() function read the data char by char.


b. After reading the characters the control in last character location.
c. to know the cursor position use tell() function.
d. To move the cursor to specefic location use seek()

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.seek(3) # moving the control to 3rd location


print(f.read(7))

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

ex 7 : There are three ways to read the data from file.


1. using read() : Reading the data char by char.
2. using readline() : Reads single line.
3. using readlines() : Reads all lines in list format.

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

ex 9: Reading the data from file using for loop.


The for loop will read the data line by line format.

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....")

ex 10: removing & renaming the file.


import os
os.rename("sample.txt","sample1.txt")
os.remove("ratan.txt")
print("operations are completed....")

ex-11: mode r+ : read,write oprations : file is mandatory


to read the data file is mandatory if the file is not available, we will get FileNotFoudError
here the write operations will add the data instead of overriding.

f = open("sample.txt",'r+')
print(f.read())

f.write("\nHi stuents.....")
f.close()

ex-12: mode w+: write & read operations: file is optional


if the file is not available it will create & write the data
if the file is available it overrides the data.

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

ex-13: mode a+: append & read operations: file is optional


if the file is not available it will create & append the data
if the file is available it will append the data at last.
f = open("sample.txt",'a+')
f.write("\n Good Morning.....")
f.seek(0)
print(f.read())
f.close()

Here after appending the data the control is poining at last but to read the data move
the cursor first location using seek.

ex-14: mode 'x': exclusive creation with write mode


if the if is not available it will create & write the data.
if the available is available we will get FileExistsError.
f = open("anu.txt",'x')
f.write("Good Morning.....")
f.close()

ex-15: file with exception handling


#problem
f = open("sample.txt","w")
f.write("hi sir how are you")
print(10/0)
f.close()

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-16: file closing operations


we can close the file in three ways
1. using close() function.
we are closing file explicitly use close () function.
ex: file.close()

2. using with statement.


when we open the file using with statement once the with statement is
completed file is automatically closed.
with open("sample.txt") as f:
print(f.read())

3. Reassigning reference variable.


when we assign existing file reference to new file the existing file will be
automatically closed.
f1 = open("sample.txt")
f1 = open("ratan.txt")
here sample.txt file is closed automatically.

ex-17: working with directory.


 Create directory using mkdir() function
 Change the control to current corking directory use chdir() function.
 Get the current working directory location use getcwd() function.
 Remove the directory using rmdir() function.
import os
os.mkdir("Venu")
os.chdir("Venu")
print(os.getcwd())
os.rmdir("Venu")
print("operatiosn are completed...")

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()

Material by Mr. Ratan...........

********* Completed: Thank you: Believes only practical Knowledge************

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.

bebug : identifying the error & rectify the error.

syntax: assert condition , msg

if the condition is success nothing happened: application executed normally


if the condition is fail, we will AssertionError with msg.

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"

print("Happy married Life.....")

ex 3:
name = input("enter comp name:")
sal = int(input("enter sal:"))
house = input("enter house name:")

assert name=="tcs" or sal>60000 or house=="yes","sorry better try for others"

print("Happy married life......")

146 | P a g e
Python Material Mr. Ratan

ex 4: statuscode = int(input("Enter a status code:"))


assert statuscode==200,"we got fail response code"
print("Application working fine")

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

shoes = {'name': 'Fancy Shoes', 'price': 12300}


print(apply_discount(shoes, 0.25))
print(apply_discount(shoes, 2.0)) #"200% off" discount
print(apply_discount(shoes, -0.3)) #"-30% off" discount:

ex-7: def avg(marks):


assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)

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

Python working with Database

Oracle versions:
oracle 9i
oracle 10g
oracle 11g
oracle 12c
oracle 18c

express edition : trail version


default user name : system
password : at the time if insall # manager
enterprise edition : licensed version
user name : scott
password : at time of install #tiger

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;

insert into emp values(111,'ratan',10000.45)


insert into emp values(222,'anu',20000.45)

select * from emp;


select eid,ename from emp;

update emp set esal = esal + 500 where esal>10000;


update emp set eid=11 where eid=111;

delete from emp where esal>10000;


delete from emp where eid=222;

truncate table emp;


drop table emp;

Types of commands in oracle:


DDL : create alter drop
DML : insert update delete select
DCL : grant revoke
TCL : commit rollback

DDl,DCL : database admin team responsibility.


DML,TCL : developer responsibility.

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

Steps to design first Apllication :


step 1: connect to database : connect()
step 2: create the cursor : cursor()
step 3: using cursor execute the query : execute()
step 4: close the resources : close()

ex-1: create the table


import cx_Oracle
#step 1: create the connection python to database
conn = cx_Oracle.connect("system","ratan")
print("Connection created successfully....")

#step 2: create the cursor


cs = conn.cursor()

#step3: execute the query


cs.execute("create table emp(eid number,ename varchar2(20),esal number)")
print("Table created succesfully....")

#step 4: close the resources


cs.close()
conn.close()
print("Connection closed successfully....")

ex-2: insert the data


import cx_Oracle
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)")
print("Data Inserted succesfully....")
conn.commit()

cs.close()
conn.close()
print("Connection closed successfully....")

149 | P a g e
Python Material Mr. Ratan

ex 3: update the data


cs.execute("update emp set esal = esal+500 where esal>10000")
conn.commit()

ex 4 :
#reading all columns data
res = cs.execute("select * from emp")
for x in res:
print(x)
cs.close()

#reading specific columns data


res = cs.execute("select * from emp")
for x in res:
print(x[0],x[1])

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.execute("insert into product values(111,'pen',230)")


cs.execute("insert into product values(222,'chair',400)")
cs.execute("insert into product values(333,'book',33)")
conn.commit()
print("data inserted successfully....")

data = cs.execute("select * from product")


for records in data:
print(records[0],records[1],records[2])

cs.execute("update product set cost = cost +5 where cost>100")


conn.commit()
print("records updated....")

data = cs.execute("select * from product")


for records in data:
print(records[0],records[1],records[2])

cs.execute("drop table product")


print("table dropped successfully.......")

cs.close()
conn.close()
print("Conneciton closed successfully....")

151 | P a g e
Python Material Mr. Ratan

ex 7: Simple Execution vs. Batch execution.


case 1: Simple execution
import cx_Oracle
conn = cx_Oracle.connect("system","ratan")
print("connection created successfully....")

cs = conn.cursor()

#these are list of login values


login_info = [("aaa","bbb"),("ratan","anu"),("sravya","naresh")]
for x in login_info:
cs.execute("insert into login_details values(:1,:2)",x)
conn.commit()
print("data inserted successfully....")

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.

To overcome above problem use batch operations.

case-1: batch operations


#here we are inserting the data using exectemany() this is batch execution in this we are sending all the
details at a time to database
import cx_Oracle
conn = cx_Oracle.connect("system","ratan")
print("connection created successfully....")

cs = conn.cursor()

#these are list of login values


login_info = [("aaa","bbb"),("ratan","anu"),("sravya","naresh")]
cs.executemany("insert into login_details values(:1,:2)",login_info)
conn.commit()
print("data inserted successfully....")

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)})")

#Batch execution inserting 100 records into emp table.


query = "insert into emp values(:1,:2,:3)"
details = list(zip(list(range(1,101)),[names.get_first_name() for x in
range(100)],[random.uniform(5,9) for x in range(100)]))

cs.executemany(query,details)

conn.commit()
cs.close()
conn.close()
print("Connection closed successfully.......")

ex-9: Database connection with exception handling.


import cx_Oracle
conn = cx_Oracle.connect("system","ratan")
print("Connection created successfully...")
print(10/0)
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

ex-10: Transaction management: set of operations are called Transaction

the transaction main principle is


do everything: commit () : save the data
do nothing : rollback() : undo operation

step 1: create the connection.


step 2: try block do the operations use commit.
step 3: except block do the rollback.
step 4: finally block close the resources.

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

E:\>pip install mysql.connector

155 | P a g e
Python Material Mr. Ratan

ex-1: Table creation process.

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.execute("create table emp(eid int,ename varchar(20),esal int)")


print("table 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;

ex-2: Data insertion process.


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.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)")
con.commit()
print("Data inserted successfully....")

cs.close()
con.close()
print("Connection closed.........")

156 | P a g e
Python Material Mr. Ratan

ex-3: fetching (select) data from database.


mycursor.execute("SELECT * FROM login_table")
myresult = mycursor.fetchall()
for x in myresult:
print(x)

Fetching selected columns from the database table:


mycursor.execute("select eid,ename from emp")
myresult = mycursor.fetchall()

Reading first row of the table :


mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()

ex-4: Table data updating process by using UPDATE command.


mycursor.execute("update emp set esal=esal+{} where esal>{}".format(100,1000))
print("values are updated successfully....",mycursor.rowcount)

ex-5: Table data deleting process by using DELETE command.


mycursor.execute("delete from emp where eid=%d"%(111))
print("deleted records....",mycursor.rowcount)

ex-6: CURD operations with MySQL.


product table eid , ename , ecost
insert three emp records intp emp table.
print the emp data
update the data increase the emp sal+500 where esal>10000
print the emp data
drop the emp table.

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'")

cs.execute("select *from Login_table")


print(cs.fetchall())
conn.commit()
cs.close()
conn.close()

159 | P a g e
Python Material Mr. Ratan

ex-5: registration process.


import psycopg2
import time
class Registration:
def registration(self):
try:
conn = psycopg2.connect(user='postgres',password='Raja1234',port
="5432",host="127.0.0.1",database ='postgres')
cs = conn.cursor()
#cs.execute("create table Registration_table(date DATE ,full_name varchar(30),father_name
varchar(30),Aadhar_number bigint ,user_name varchar(30) ,password varchar(30),key_security
varchar(20),account_number bigint not null primary key,balance bigint,bank_name
varchar(30),IFSC_number varchar(30))")
while True:

full_name = input("enter your name:")


father_name = input("enter father's name:")
Aadhar_number =int(input("enter aadhar number:"))
user_name = input("Enter user name:")
password = input("set your passwod:")
key_security = input("enter a key:")
account_number = int(input("enter account number:"))
balance = float(input("enter mininum deposite:"))
bank_name = input("enter bank name:")
IFSC_number = input("enter IFSC_number: ")
date =time.asctime(time.localtime(time.time()))
cs.execute(f"insert into Registration_table
values('{date}','{full_name}','{father_name}',{Aadhar_number},'{user_name}','{password}','{key_security}
',{account_number},{balance},'{bank_name}','{IFSC_number}')")
print("do you to again to registration for another person")
res = input("enter your option (y or n)")
if res == 'y'or res == 'yes':
continue
elif res == 'n' or res =='no':
print("your registration is succussfully")
break
else:
print("your option is wrong")
break

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))

Methods in Regular Expression:


re.match()
re.search()
re.findall()
re.compile()
re.sub()
re.split()
re.finditer()

Normal string vs. raw string


A normal string is a string literal in which the normal escaping rules have consider.
For example, the string literal "\n" consists of one character escape sequence character (newline).

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

ex-1: This method finds match if it occurs at start of the string


If the match is not available it returns None.
re.match(pattern, string)

import re
result = re.match(r'ratan', 'ratan sir good')
print (result)
print (result.group(0))
print (result.start())
print (result.end())

result = re.match(r'durga', 'hi sir')


print (result) #None

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)

result = re.fullmatch(r'ratan', 'ratan sir')


print (result)

result = re.fullmatch(r'ratan', 'ratan')


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))

result = re.search(r'anu', 'hi ratan sir good')


print(result)

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)

result = re.findall(r'anu', '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)

#application code with compile() function


ptrn = re.compile("ratan") #making pattren as object
result1 = ptrn.findall('hi ratan sir ratan sir good')
print(result1)
result2 = ptrn.findall('hi good ratan sir')
print(result2)
result3 = ptrn.findall('hi ratan sir ratan sir great')
print(result3)

ex 6: re.sub(pattern , sub_string , string_msg):


It helps to search a pattern and replace with a new sub string.
If the pattern is not found, string is returned unchanged.
import re
result = re.sub("ratan",'anu',"hi ratan sir this is ratanit")
print(result)

result = re.sub("anu",'sravya',"hi ratan sir this is ratanit")


print(result)

s = " hi sir \n please stop \n the class"


print(s)
x = r.sub(“\n”," ",s)
print(x)

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"

# the result will be the list of elements.


print(re.findall("beer",s))

# the result will be the list of objets.


data = list(re.finditer("beer",s))
for x in data:
print(x.span())

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

ex-1: write the output.


* : zero or more
+ : one or more
? : zero or one

[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)

ex 2: write the output.


import re
result = re.findall(r"[a-z]*an","ratan sir ratan how can an are you")
print(result)
result = re.findall(r"[rs]+an","ran ban rrran an how are you")
print(result)
result = re.findall(r"[^a-h]?an","ran sir ratan ban how an are you")
print(result)

E:\>python first.py
['ratan', 'ratan', 'can', 'an']
['ran', 'rrran']
['ran', 'tan', 'an', ' an']

167 | P a g e
Python Material Mr. Ratan

ex-3: write the output.


import re
result = re.search(r"[abcdef]*soft","dabsoft is birlasoft sir how are you")
print(result.group())

result = re.search(r"[a-x]+w","ratanw sir how dabsoft are you")


print(result.group())

result = re.search(r"[^xyz]?soft","ratan sir how dabsoft are you")


print(result.group())

input = "at hat cat hhat chat hcat cchchat"


result1 = re.findall("[hc]*at",input)
print(result1)

result2 = re.findall("[hc]+at",input)
print(result2)

result3 = re.findall("[hc]?at",input)
print(result3)

ex-4: write the output of below example.


{3} : exactly 3
{3,} : 3 or more
{3,5} : 3,4 or 5
\d : digits

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 6789 657 78 909090"


print(len(re.findall("\d{5}",num)))
print(len(re.findall("\d{4,7}",num)))

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

ex-5: extracting email & dates & both


import re
x = re.findall("\d{1,2}/\d{1,2}/\d{4}","hi 12/01/2020 hi sir how 22/9/2021 is 1/1/2018")
print(x)

y = re.findall("[a-z]+@[a-z]+.[a-z]+","hi ratan@gmail.com this is good anu@gmail.com hi")


print(y)

y = re.findall("\w+@\w+.\w+","hi ratan@gmail.com this is good anu@gmail.com hi")


print(y)

x = re.findall("\d{1,2}/\d{1,2}/\d{4}|\w+@\w+.\w+","hi 12/01/2020 hi ratan@gmail.com")


print(x)

ex-6: write the output of below example.


import re
nameage="Balu age is 59 Chiru age is 61"
age = re.findall(r"\d{1,3}",nameage)
names = re.findall(r"[A-Z][a-z]*",nameage)

res = dict(zip(names,age))
print(res)

170 | P a g e
Python Material Mr. Ratan

Material by Mr. Ratan...........

171 | P a g e
Python Material Mr. Ratan

Python Class concept

The object-oriented languages deal with classes & objects .


The class name starts with upper case, if the class contains multiple words every inner words starts with
upper case. This is called camel case.
ex: Test, MyClass

The class contains three types of methods.


1. instance method
first argument must be self.
Access the method using object-name.

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.

ex-1: methods without arguments.


class MyClass:
def disp(self):
print("hi students")

@staticmethod
def wish():
print("Good morning")

#Access the data


c = MyClass()
c.disp()
MyClass.wish()

ex-2: methods with arguments.


class Operations:
def add(self,num1,num2):
print(num1+num2)

@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

class vs. object:


a. class is a logical entity it contains logics
whereas object is physical entity it is representing memory.

b. class is blue print it decides object creation


without class we are unable to create object.

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)

#Access the data


c1 = MyClass()
c1.disp("ratan")

c2 = MyClass()
c2.disp("Anu")

ex 4: There two formats to create object


1. named object : an object with name
2. nameless object : an object without name

class MyClass:
def wish(self):
print("Good evening...")

#an object with name


c = MyClass()
c.wish()

#an object without name


MyClass().wish()

173 | P a g e
Python Material Mr. Ratan

ex 5: printing memory id & memory comparison


class MyClass:
pass
c1 = MyClass()
c2 = MyClass()
c3 = MyClass()
c4 = c3 # c4 is pointing to c3

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()

instance method access:


instance methods inside the class access using self.
instance methods outside of the class access using object name.
static methods:
Always Access the static methods using class-name

175 | P a g e
Python Material Mr. Ratan

ex: check above diagram for this example.


case 1: instance variables : Every object separate memory created.
class Emp:
def __init__(self,eid,ename,esal,comp,addr):
self.eid = eid
self.ename = ename
self.esal = esal
self.comp = comp
self.addr = addr

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.

case 2: class variables: for all objects single copy created


class Emp:
#class varailes
comp, addr = "tcs","hyd"
def __init__(self,eid,ename,esal):
self.eid = eid
self.ename = ename
self.esal = esal

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

ex: Variables Accessing


Case 1: Class variables Accessing
we can access the class variables inside the class
a. using class-name: valid: recommended
b. using self : valid : not recommended

we can access the class variables outside of the class


a. using class-name: valid: recommended
b. using object name: valid: not recommended

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)

case 2: instance variables Accessing


we can access the instance variables inside the class using self.
we can access the instance variables outside of the class using object 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

ex : write the out of the below example.


class MyClass:
a = 10
def m1(self):
print("m1 Method")
@staticmethod
def wish(name):
print("Good morning....",name)

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

ex-: __init__ :it will execute when we create the obj


__str__ : it will execute when we print the obj

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.

ex: Employee count


class Employee:
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print ("Total Employee %d" % Employee.empCount)

def __str__(self):
return "Name : {0} Salary: {1}".format(self.name,self.salary)

emp1 = Employee("ratan", 20000)


print(emp1)
emp2 = Employee("anu", 5000)
print(emp2)

emp2.displayCount()

180 | P a g e
Python Material Mr. Ratan

ex : class predefined functions.


class Student:
def __init__(self,id,name,age):
self.id = id
self.name = name
self.age = age

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)

amt = int(input("enter amount to withdraw"))


c.withdraw(amt)

print(c.remaining())

181 | P a g e
Python Material Mr. Ratan

ex: Getting information about class


class MyClass:
"""
instance & static methods
printing messages
"""
num = 10
def __init__(self,fname,lname):
self.fname = fname
self.lname = lname

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>}

instance & static methods


printing messages

MyClass
__main__

182 | P a g e
Python Material Mr. Ratan

ex: printing instance & class variables with values.


class MyClass:
num1,num2,mum3 = 10,20,30
def __init__(self,fname,lname):
self.fname = fname
self.lname = lname

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

print(c.__dict__) # it prints only instance variables with vlaues


print(MyClass.__dict__) # it prints only static variables with vlaues

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']

['__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', 'mum3', 'num1', 'num2']

{'fname': 'ratan', 'lname': 'addanki'}

{'__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

ex: Just printing only instance & static variables clearly.


class MyClass:
num1,num2,mum3 = 10,20,30
def __init__(self,fname,lname):
self.fname = fname
self.lname = lname

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

1. inheritance introduction: "is-a" relation


The process of acquiring properties from parent to child class is called inheritance.
class A: # parent super base
func1
func2
class B(A): # child sub derived
func3
func4
class C(B):
func5
func6

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

3. default super class


class A:
pass
class B(A):
pass
class C(B):
pass

a. The default super class in python is: object


b. the root class in python is: object
c. in python every class contains parent class except: object

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.

1. Single inheritance: one parent with one child.

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

3.hierarchical inheritance: one parent with multiple child classes


class A:
pass
class B(A): A
pass /\
class C(A): B C
pass

4. multiple inheritance: multiple parent classes with one child

class A:
pass
class B: A B
pass \/
class C(A,B): C
pass

5. hydrid inheritance: hierarchical + multiple


class A:
pass A
class B(A): /\
pass B C
class C(A): \/
pass D
class D(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()

ex 3: child & super class variables.


case 1: variables are different names
class Parent:
num1,num2 = 10,20
class Child(Parent):
val1,val2 = 100,200
def add(self,i,j):
print(i+j)
print(self.val1+self.val2)
print(self.num1+self.num2)

c = Child()
c.add(1000,2000)

case 2: variables are same names


class Parent:
num1,num2 = 10,20

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

ex 2: To call the super class methods use super()

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()

we can call the current class instance methods in one way,


using self-keyword
we can call the super class instance methods in two ways,
1. using super() : direct access
super().m1()
2. using class-name : first argument must be self
Parent.m1(self)
Note: it is not possible to use self-keyword inside the static area.

189 | P a g e
Python Material Mr. Ratan

ex 4: super class constructors.


case 1: call the super class cons use super() : direct access
class A:
def __init__(self):
print("A class constructor")
class B(A):
def __init__(self):
print("B class constructor")
super().__init__()
class C(B):
def __init__(self):
print("C class constructor")
super().__init__()

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)

case 2: two classes with 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"First name:{self.first_name} Last Name:{self.last_name} email:{self.email}"

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

create the Student object access the data


create the Teacher object access the data

Ans: with relation


class Student:
def __init__(self,first_name,last_name,school_name):
self.first_name = first_name
self.last_name = last_name
self.school_name = school_name
def __str__(self):
return f'{self.first_name} {self.last_name} {self.school_name}'

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}'

#create the objects access the data


s = Student("ratan","addanki","Vidyanikethan")
print(s)
t = Teacher("anu","dasari","nareshit","python",10000.45)
print(t)

192 | P a g e
Python Material Mr. Ratan

ex 3: using one class reference in another class. : Aggregation


in below example we are using movies & addr in Hero class.

#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} "

# data access : creating object then passing the object to constructor


a1 = Address(111,"Madhapur","ts") # Here Address class present in addr.py so import the module
t1 = MovieTypes(50,40) # Here MovieTypes class present in movies.py so import the
module
h1 = Hero("Mahesh babu",40,5.9,a1,t1)
print(h1)

#data access : directly passing the object to constructor


h2 = Hero("alluArjun",33,5.4,Address(222,"hitech","ts"),MovieTypes(20,10))
print(h2)

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}"

p=Parent("Riyaz ahmad","Nahid afroj")


m=Marks(99,90,80)
a=Address(111,"UP",222002,"India")
s=Student(111,"Adil khan","Savitri",p,m,a)
print(s)
#direct accress
s=Student(111,"Adil khan","Savitri",Parent("Riyaz
ahmad","Nahidafroj"),Marks(99,90,80),Address(111,"UP",222002,"India"))
print(s)

194 | P a g e
Python Material Mr. Ratan

OOPS: polymorphism

one functionality with multiple behavior is called polymorphism.


The ability to appear more than one form is called polymorphism.

in polymorphism we will discuss two parts,


1. method overriding
2. polymorphic functions

ex-1 : Method Overriding.


Method overriding means implementations already present with parent class,
 if child required parent implementations then access it.
 if the child is not satisfied with parent method implementation then override the parent method
in child class to write the child specific implementation.
 To achieve the Method overriding we required minimum two classes with parent & child relation.

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()

# if the child is overriding then child implementation executed


money + land + gold +cars...
kajal......

# if the child is not overriding then parent implementation exe


money + land + gold +cars...
very black girl....

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")

#polymorpic function:Takes any type of input gives proper result


def comman_func(obj):
obj.fly()
obj.swim()

#client1 calling the func by passing parrot obj


comman_func(Parrot())

#client2 calling the func by passing Penguin obj


comman_func(Penguin())

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()

create the polymorphic function can take any type of data.

client can pass either unicorn obj or cbz obj access the data.

196 | P a g e
Python Material Mr. Ratan

ex 4: user defined polymorphic functions


def add(a,b=2,c=3):
print(a+b+c)

add(10)
add(10,20)
add(10,20,30)

ex 5: pre-defined polymorphic functions


print(len("ratan"))
print(len([10,20,30,40]))
print(len((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)

#create the polymorphic fuction


def data_access(obj):
obj.show()

#client code : passing objects one by one


text = TextDoc("sample.txt")
data_access(text)
pdf = PdfDoc("sample.pdf")
data_access(pdf)
word = WordDoc("sample.word")
data_access(word)

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

OOPS: Abstract Classes

There are two types of methods


1. normal methods
2. abstract methods

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

Based on above implementations thee classes are two types


1. normal classes : The class contains only normal methods.
2. abstract class : The class contains some abstract methods.

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

ex 1: abstract classes coding style-1


from abc import ABC,abstractmethod
class Message(ABC):
@abstractmethod
def wish(self):
pass
class Ratan(Message):
def wish(self):
print("Good Morning")
class Anu(Message):
def wish(self):
print("Very Good morning")
#Data Access
r = Ratan()
r.wish()
a = Anu()
a.wish()
#m = Message() TypeError: Can't instantiate abstract class Message with abstract methods wish

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

ex-3: abstract classes coding style-2

from abc import ABC,abstractmethod


class MyClass(ABC):
@abstractmethod
def add(self,num1,num2):
pass
@abstractmethod
def mul(self,num1,num2):
pass

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

ex 6: write the output of below example.


from abc import ABC,abstractmethod
class A(ABC):
def __init__(self,value):
self.value = value
@abstractmethod
def disp(self):
pass
class Add(A):
def disp(self):
print(10+self.value)
class Mul(A):
def disp(self):
print(10*self.value)

a = Add(10)
a.disp()
b = Mul(5)
b.disp()

In above example Add,Mul classes using abstract class constructor commonly.

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.

sales team: contains sales data with private restriction.


finance team: need the information about sales team, but finance team cannot access the sales data
directly but finance team can access sales data with the help of superior(getters & setters).
a. setters are used to set the specific data.
b. getters are used to get the specific data.

ex-1 : Here we have two modules.


#salesinfo.py
class Sales:
def __init__(self,name,cost,quantity):
self.__name = name
self.__cost = cost
self.__quantity = quantity

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)

Material by Mr. Ratan...........

"No one is Perfect......just do it"

********* Completed: Thank you ************

205 | P a g e
Python Material Mr. Ratan

Packages & Modules

 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.

There are two types of import


 1. normal import : Access the data using module name.
 2. from import : Access the data directly without using module name

Note: it is possible to import the multiple modules in single line of import but it is not recommended.

#valid but not recommended


import first , second

# valid recommended
import first
import second

206 | P a g e
Python Material Mr. Ratan

ex-1: Here the module contains variables & functions.


#operations.py
name = “ratan”
def add(x, y):
print(x + y)
def mul(x, y):
print(x * y)
#client.py
import operations
operations.add(10,20)
operations.mul(4,5)
print(operations.name)

from operations import add,mul,name


add(10,20)
mul(5,5)
print(name)

from operations import *


add(10,20)
mul(5,5)
print(name)

ex -2: Here the module contains classes.


#first.py
class Fruits:
def disp(self):
print(“mango apple banana.......”)
#second.py
class Food:
@staticmethod
def disp():
print(“idli dosa puri.......”)
#client.py
import first
import second
f = first.Fruits()
f.disp()
second.Food.disp()

from first import Fruits


from second import Food
f = Fruits()
f.disp()
Food.disp()

207 | P a g e
Python Material Mr. Ratan

Ex 3: Assignment: the module contains: variables , functions , classes


#first.py
declare two global variables
def add(num1,num2):
print the local add
print the global add

#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()

from first import val1,val2,add


from second import Student
print(val1)
print(val2)
add(40,20)
f = Student()
f.wish()
Student.disp()

208 | P a g e
Python Material Mr. Ratan

ex 4: The module contains three elements


a. variables
b. functions
c. classes
#operations.py
name1,name2 = "ratan","anu"
def add(x, y):
print(x + y)
def mul(x, y):
print(x * y)

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

To check the methods, present in particular class use below code.


import operations
print(dir(operations.Food))

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

ex 5: creating alias name for module.


#operations.py
def add(num1,num2):
print(num1+num2)
def mul(num1,num2):
print(num1*num2)

#client.py
#Access the data using complete name of the module
import operations
operations.add(10,20)
operations.mul(3,4)

#Access the data using alias name of module


import operations as op
op.add(10,20)
op.mul(3,4)

210 | P a g e
Python Material Mr. Ratan

ex 6: There are two types of import


1. global import :
2. local import

1. global import:Entire module can use this import

#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()

2. local import: specific function can access


#client.py
class Myclass:
def my_func1(self):
from operations import add,mul #local import
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)

from first import Emp


from second import Student
e = Emp(111,"ratan")
print(e)
s = 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 package modules


#operations.py
def add(num1,num2):
print(num1+num2)
def mul(num1,num2):
print(num1*num2)
#message.py
def wish(name):
print("Good Morning....",name)

model package modules


#first.py
def first_disp():
print("this is model package first file")
#second.py
def second_disp():
print("this is model package second file")

client package modules


#ratan.py #anu.py
import services.operations from services.operations import add, mul
import services.message from services.message import wish

import model.first from model.first import first_disp


import model.second from model.second import second_disp

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

ex -2: sub packages example.


services
|-->laptop
|-->hp.py
|-->dell.py
|-->mobile
|-->apple.py
|-->oneplus.py
|-->generalservice.py

client
|-->ratan.py : access the data using normal import
|-->anu.py : access the data using from import

Services is main package & Laptop sub package modules


#hp.py
def hp_info():
print("This is Hp Information")
#dell.py
def dell_info():
print("This is DELL Information")

services main package & mobile sub package modules


#apple.py
def apple_info():
print("This is Apple Information")
#oneplus.py
def oneplus_info():
print("This is ONEPLUS Information")

services main package module


#generalservice.py
def general_info():
print("This is General service Information")

client package modules


#ratan.py #anu.py
import services.laptop.hp from services.laptop.hp import hp_info
import services.laptop.dell from services.laptop.dell import dell_info
import services.mobile.apple from services.mobile.apple import apple_info
import services.mobile.oneplus from services.mobile.oneplus import oneplus_info
import services.generalservice from services.generalservice import general_info

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

ex-3 : packages : Assignment


services [main pcakage]
|--> veg.py
class Vegetables:
def disp(): instance method : print the veg name
|--> nonveg.py
class NonVeg:
def disp() : static method : print the nonveg names
models [main package]
|-->heroinfo.py
class Hero:
def info: instance method : print heroin names
|--> heroininfo.py
class Heroin:
def info(): static method :print the hero names

client [main package]


|-->ratan.py : access the data using normal import
|-->anu.py : access the data using from import
Ex 4: sub packages assignment.
offers [main package]
|-->home [sub package]
|---> homedata.py
class HomeInfo
def disp() : instance method :print message buy1 get 1
|--> hosteldata.py
class HostelInfo:
def disp(): static method : print message : hostel is sweet home
|-->medical [sub pkg]
|---> medicaldata.py
class MedicalInfo
def disp(): instance method : print the message

|-->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%")

client [main package]


|-->ratan.py : Access the data using normal import
|-->anu.py : Access the data using from import

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

case 3: getting information about module


print(names.__version__) # module version.
print(names.__name__) # module name.
print(names.__path__) # source code location.

E:\ >python first.py


0.3.0
names
['C:\\Users\\RATAN\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\names']

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)

msg = "hi ratan sir"


print(string.capwords(msg))

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

#both functions will give int data


print(random.randint(1,50))
print(random.randrange(5,25,5))

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))

choice : it will give only one element.

choices : it will give multiple elements


when we declare the number of choices "k" is mandatory otherwise we will get error.
print(random.choices(["rat","anu","aaa"],k=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

sample : it will give multiple elements


when we declare the number of sample "k" is optional.
print(random.choices(["rat","anu","aaa"],2))

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

if we pass the number of sample in negative value we will get ValueError.


print(random.choices(["rat","anu","aaa"],k=-2))
G:\>python first.py
ValueError: Sample larger than population or is negative

case 3: Write the output


import random
import string
print(random.choice(list("ratan")))
print(random.sample(string.ascii_uppercase,5))
print(random.choices(string.ascii_lowercase,k=5))

case 4: Generate 5-characters token by taking random characters from a-zA-z0-9


output : axDf2 , A1Xer

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)

print(math.exp(3)) # e to the power of x


#print(math.exp("25")) TypeError: must be real number, not str

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']

 All the command line arguments are stored in list if strings.


 In command line arguments the first argument is file-name.
 check the length of the command line arguments using len() function. here we have to ignore first
argument because it is file name.
ex: print(len(sys.argv)-1)

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.

the command line arguments are by default string format.


to get the command line arguments use sys module argv.
To get the first argument : sys.argv[1]
To get the second argument : sys.argv[2]
------------
To get the n argument : sys.argv[n]
The command line argument seprator is space

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

ex-3: giving space in command line argument.


import sys
print(sys.argv[1])
print(sys.argv[2])

G:\>python first.py corepython ratan


corepython
ratan

G:\>python first.py core python ratan


core
python

G:\>python first.py "core python" ratan


core python
ratan

Note: To take the space in command line arguments take that argument in double quotes.

case 4: to stop the application execution use exit()


import sys
print("ratan")
sys.exit(0)
print("ratan")

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.

eid , ename , esal , status = 111,"ran",10000.45,True


print(sys.getsizeof(eid)) #returns the memory size of the object in bytes
print(sys.getsizeof(ename))
print(sys.getsizeof(esal))
print(sys.getsizeof(status))

for x in sys.stdin: #is used for interactive input


if 'exit' == x.strip():
print('Terminating the program')
exit(0)
else:
print(x)

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)

res = datetime.datetime.now().strftime("%d/%m/%Y, %H:%M:%S")


print(res)

#conversion of string into data fromat


date_string = "1 April, 2020"
res = datetime.datetime.strptime(date_string, "%d %B, %Y")
print(res)

date_string = "1 07, 2020 10, 17, 55"


res = datetime.datetime.strptime(date_string, "%d %m, %Y %H, %M, %S")
print(res)

224 | P a g e
Python Material Mr. Ratan

ex: time module

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

ex: itertools module


case 1:
import itertools
# we will get factorial value 2! = 2 3!=6 4!=24
for p in itertools.permutations('AB'):
print(p)

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)))

case 2: chain function


from itertools import chain
#in this case chain() is not required because same type of data we can combine using + then we
can print it.
l1 = [12.3, 2.5, 34.13]
l2 = ['cpp', 'Python', 'Java']
for value in chain(l1,l2):
print(value)
for value in l1+l2:
print(value)

#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

 Thread is a light weight task or small task of the application.


 Every thread is separate independent part of the same application(process).
 Threads exists inside a process.Multiple threads can exist in a single process.
 Executing more than one thread simultaneously is called multithreading.
 Threads are usually contained in processes. More than one thread can exist within the same
process
 Threads allows a program to run multiple operations concurrently in the same process
space.

The major difference between threads and processes is


1. Threads share the address space of the process that created it; processes have their own
address.
2. Threads have direct access to the data segment of its process; processes have their own
copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use
interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent process.
6. Threads can exercise considerable control over threads of the same process; processes can
only exercise control over child processes.

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.

There are two types of programming models


1. single threaded model
2. multithreaded model

There are two modules support multithreading concept.


1. thread (Deprecated)
2. threading

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.

#Thread vs. process:


process is heavy weight created by os.
thread is light weight created by python virtual machine.

one process contains multiple threads every thread in independent.

multi tasking :There are two types of multi tasking


a. process based
b. thread based

#process based multi tasking :


a. Every request one process is created.
b. if number of request increased the processes are increased it effects on performance.

#Thread based multi tasking:


a. Every request one thread is created.
b. if number of request increased the threads are increased it improves performance because
thread is light weigh.

#There are two types of programming models


1. single threaded model
application contians only one thread(main)
2. multi threaded model
application contains multiple threads.

#Multithreading :
create the multiple threads run the threads parallel.

#There are two modules support multithreading concept.


1. thread (Deprecated)
2. threading

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,))

# starting thread 1,thread2


t1.start()
t2.start()

in above example t1-thread doing print_square.


in above example t2-thread doing print_cube.

target -----> Thread functionality


args -----> Functionality inputs
start() -----> To start the thread
Note : all user threads are started by main thread.

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())

ex 4 : Thread states : Every thread contains three states


a. initial state
b. started state
c. stopped state

from threading import Thread


import time
def add(num1,num2):
print("Addition:",num1+num2)

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)>

ex 5 : it is not possible start the same thread twice.


import threading
def disp():
print("Good Morning")

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

ex 6: To start the thread after some time use Timer class.


import threading
def disp():
print("Hi Students how are you....!")

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.

ex 8 : for loop creates multiple threads


import time
from threading import Thread

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 = print_table1, args=(4,))


t2 = threading.Thread(target = print_table2, args=(6,))
t1.start()
t1.join()
t2.start()
t2.join()
print("This is main Thread : process is completed....")
#t1.join() : other threads(t2,main) will wait until completion of t1 thread
#t2.join() : other threads(main) will wait until completion of t2 thread
ex 10:Thread names
The default name of the main thread : MainThread
the default name of user defined threads : Thread-1 Thread-2 ....Thread-n
case 1: default names of threads : Thread-1,Thread-2.......Thread-n
import threading
def disp(name):
print(f"Hi students {name} is Good This is..",threading.currentThread().getName())

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)

case 2: Application with threading


import threading
from threading import *
import time
def sqr(n):
for x in n:
x%2
time.sleep(1)

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

ex-12: thread with lock mechanism.


from threading import Thread
import threading
import time
def disp(name):
lock.acquire()
for x in range(10):
print("Good Morning......",name)
time.sleep(1)
lock.release()

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

ex-14: thread with logging module


import logging
import threading
import time

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")

logging.info("Main : before creating thread")


x = threading.Thread(target=thread_function, args=(1,))
logging.info("Main : before running thread")
x.start()
logging.info("Main : wait for the thread to finish")
logging.info("Main : all done")

ex-15: thread with logging module


import logging
import threading
import time

format = "%(asctime)s: %(message)s"


logging.basicConfig(filename="log.txt",format=format, level=logging.DEBUG,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()))

t = threading.Thread( target=my_service,name="my service")


w1 = threading.Thread(target=worker,name="worker-1")
w2 = threading.Thread(target=worker,name="worker-2") # use default name
t.start()
w1.start()
w2.start()

237 | P a g e
Python Material Mr. Ratan

Object based multi-threading

ex-1: steps to creation of thread in object based approach.


step 1: to create thread class our extends Thread
class MyThread(Thread):

step 2: write the logics using run() method


class MyThread(Thread):
def run(self):
print("logics")

step 3: instantiate thread class.


t = MyTrhead()

step 4: start the thread using start() method


t.start()

from threading import Thread


class MyThread(Thread):
def run(self):
print("Good Morning Threading")

t = MyThread()
t.start()

ex2: setting & getting name of the thread.

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

ex 3: Assignment : here we are taking default name of the threads.


Here all threads are printing same message(Good Morning) with same number of iterations(3)
t1:
Good morning ....Thread-1
Good morning ....Thread-1
Good morning ....Thread-1

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

Ans : multiple threads are performing same task.

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

ex 4: Assignment : here we are taking user defined name of the threads.


Here threads are printing different message(morning,evening,night)
with different number of iterations(2,3,4)

t1: Good morning ....ratan


Good morning ....ratan
t2: Good Evening ....Anu
Good Evening ....Anu
Good Evening ....Anu
t3 : Good Night ....sravya
Good Night ....sravya
Good Night ....sravya
Good Night ....sravya
Ans :
from threading import Thread
import threading
import time
class MyThread1(Thread):
def run(self):
for x in range(2):
print(f"GoodMorning :{threading.currentThread().getName()}")
time.sleep(1)
class MyThread2(Thread):
def run(self):
for x in range(3):
print(f"Good Evening :{threading.currentThread().getName()}")
time.sleep(1)
class MyThread3(Thread):
def run(self):
for x in range(4):
print(f"Good Night :{threading.currentThread().getName()}")
time.sleep(1)

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

ex 5: Daemon thread: the threads which are executing at background.


once the main threads completes its execution all daemon threads are automatically stopped.

from threading import Thread


import time
class MyThread1(Thread):
def run(self):
for x in range(10):
print("Daemon thread.......")
time.sleep(1)

t1 = MyThread1(daemon=True)
t1.start()
for x in range(5):
print("main thread")
time.sleep(1)

Material by Mr. Ratan...........

“Respect the class & teacher”

********* Topic Completed: Thank you ************

241 | P a g e
Python Material Mr. Ratan

Material by Mr. Ratan...........

242 | P a g e
Python Material Mr. Ratan

JSON (java script object notation)

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.

In any application there are four ways to represent your data,


1. string
2. xml
3. json
4. yaml

Example of json data:


a. Declare the json data using: { }
b. The json contains the data in key: value pair format.
c. In json the keys must be strings & values can be any type.

WhatsApp service: input data in the form of json


{
"mobileno":909090909,
"msg":"hi sir how are you"
}

example of JSON Data:


{
"first_name":"addanki",
"last_name":"ratan",
"hobbies":["cricket","teaching"],
"id":1234
}

install the json data using pip command


pip install json

Type conversion process,


a. python to json : dumps() : serialization/marshaling
b. json to python : loads() : deserialization / un-marshaling

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:

ex-1: conversion of python to json data using dumps().

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}

ex-2: conversion of json to python data using: loads()

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())

for k,v in y.items():


print(k,v)

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"])

print(f"pass:{total_marks}") if total_marks>150 else print(f"fail:{total_marks}")

print("Good Teachers are:",py_data["teachers"][0]["good"])

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.....")

ex 8: read the data from sample.json : print hobbies


#sample.json
{"mobile": 90909, "hobbies": ["cric", "music"],"email": null, "status": true}
#first.py
f = open("sample.json")
json_data = f.read()
py_data = json.loads(json_data)
print(py_data["hobbies"])

Material by Mr. Ratan...........

“Sharing the Knowledge is Good for Health”

********* Topic Completed : Thank you ************

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:

APIs are useful in the following cases:


The data is changing quickly.
An example of this is stock price data. It doesn’t really make sense to regenerate a
dataset and download it every minute — this will take a lot of bandwidth, and be pretty slow.

You want a small piece of a much larger set of data.


Reddit comments are one example. What if you want to just pull your own
comments on Reddit? It doesn’t make much sense to download the entire Reddit database, then filter
just your own comments.

There is repeated computation involved.


Spotify has an API that can tell you the genre of a piece of music. You could
theoretically create your own classifier, and use it to compute music categories, but you’ll never have as
much data as Spotify does.

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

Generally, there rest API calls are,


1. get request:
retrieve information (like search results). This is the most common type of request.
returns all emps, all students...etc
no need to give input data based on url just it returns the response
returns student where sid=111
2. post request:
adds new data to the server.
it will take the input & process the input data give the response
post is nothing but create
3. put request : used to update/replace the data.
4. delete request : deletes existing information.
5. patch request : used to update/modify the data.

248 | P a g e
Python Material Mr. Ratan

we can develop the rest api calls using differnt technologies....,


1. using Django
2. using flask

here we are developing rest API calls using flask.

install the flask using pip command


pip install flask

in Rest APIs we have two technical words


1. consuming API : already api available we have to use(consume)
2. producing API : developing API

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.

200 – OK. The request was successful.


204 – No Content. The server successfully processed the request and did not return any content.

301 – Moved Permanently.

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

500 – Internal Server Error.

To check complete information about http status code use below website.
https://httpstatuses.com/

249 | P a g e
Python Material Mr. Ratan

Example URLs of Api calls:

250 | P a g e
Python Material Mr. Ratan

#consuming API : GET call: http://api.open-notify.org/astros.json

we can access the REST Api calls in three ways


1. using browser
using browser we can call only get call but not other call because other calls needs input
but by using browser it is not possible to give input.
http://api.open-notify.org/astros.json

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

3. in python code we have to access the API


in python application to access the API we need requests module
install the requests module using pip command
pip install requests

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.

See the response of different GET api calls,


Get call: https://jsonplaceholder.typicode.com/todos
https://jsonplaceholder.typicode.com/todos/10

251 | P a g e
Python Material Mr. Ratan

#producing API :
ex-1: creating get service.

from flask import Flask,jsonify

# flask app initialization


app = Flask(__name__)

@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})

# running flask application


if __name__ == '__main__':
app.run()

the urls of above application is :


http://127.0.0.1:5000/gettest
Hello World!

http://127.0.0.1:5000/getjson
{"status":"Good Morning"}

http://127.0.0.1:5000/test/10
{"Result":100}

The flask default post number is : 5000

252 | P a g e
Python Material Mr. Ratan

ex-2 : creating post API call.

from flask import Flask,request,jsonify

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

ex 3: creating post API call.


Take the three inputs : ename,company,esal in json format

company=="tcs" or esal>100000 :
status:Eligible for mrg
else :
status : not eligible try after some time

Material by Mr. Ratan...........

"Be a Respectable person"

********* Topic Completed: Thank you ************

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.

__init__ : executed when we create teh obj


__str__ : executed when we print the obj
__del__ : executed when we delete the object

__dict__ : it will print cls data in dict format


__doc__ : it will print the doc string of the class.
__name__ : it will print the class name

__version__ : to return the version of the module


__name__ : to return the name of the module
__module__ : it will give the present working module name

Note: All magic functions will work for any type of data.

ex-1: magic functions


class MyClass:
def __init__(self):
print("constructor")

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

ex-3: magic functions.


class MyClass:
"""
this is class concept
this is magic function
"""
num1,num2 = 10,20
def disp(self):
pass
@staticmethod
def wish():
pass

if __name__=="__main__":
print(MyClass.__dict__)
print(MyClass.__doc__)
print(MyClass.__module__)
print(MyClass.__name__)

256 | P a g e
Python Material Mr. Ratan

ex-4: magic functions present in int data type.


print(dir(int))

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']

arithmeitc operations : __add__ ,__mul__ magic functions present in int type


num = 10
sum = num + 10
print(sum)

res1 = num.__add__(10)
print(res1)

res2 = num.__mul__(10)
print(res2)

E:\>python first.py
20
20
100

ex 5: __new__ : magic function executed during object creation.


__init__ , __new__ both are executed during object creation. But __new__ will be executed first.

__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

ex-6: conversion of immutable data to mutable data.


during object creation to do the custamization use __new__
in below example i am passing "addanki ratan" but i need to create the object for only "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

ex-9: __enter__ & __exit__


__enter__ : it will execute when the file is open
__exit__ : it will execute when the file is closed.

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()

with Closer(open("abc.txt","w")) as conn:


print("Checking the data")

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

 Django is a web development framework used to develop web applications.


 Django is a free, open source web framework written in the Python; it is maintained by the Django
Software Foundation.
 Initial release 21 July 2005 & Stable release 2.0.6

web application fallow 3-tier architecture:

client ---- server ----- database

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

Database: Used to store the data


oracle , MySQL .........

web application contains 3-layers


presentation layer : html css JS
business layer : Django flask pyramid...etc
persistence layer : pythonDB

260 | P a g e
Python Material Mr. Ratan

install the django module using pip command


pip install django

create the Django project using IDE will get three folders:
1. location folder : configuration
setting.py
urls.py

2. application folder: business logics


views.py

3. template: html code

261 | P a g e
Python Material Mr. Ratan

ex: First Application steps


step 1: write the logics in views.py
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from datetime import datetime

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")

Note: prepare success.html file in template folder.


<html>
<body>
This is Successful Django....
</body>
</html>
step 2: for the logics create the url using urls.py
from FirstApplication import views
urlpatterns = [
path('test/',views.disp),
path('wishtest/', views.wish),
path('statustest/',views.status),
path('htmltest/',views.htmltstatus)
]
step 3: configure the application in settings.py
INSTALLED_APPS = [
'FirstApplication'
]
step 4: start the project access the project using url in web browser.
once we run the project we will get url
http://127.0.0.1:8000/test
This is Django First Application....
http://127.0.0.1:8000/wishtest
Good Morning.......2020-04-16 10:17:28.783065
http://127.0.0.1:8000/statustest
it will open the facebook
http://127.0.0.1:8000/htmltest
This response coming from html file : This is Successfull Django.....

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

#it render the login.html file to client


def login_page(request):
return render(request, "login.html")

# this function checks the login status returns Success or Fail


def login_check(request):
username = request.POST['username']
password = request.POST['password']
if username=="ratan" and password=="anu":
return HttpResponse("Login <b>Success</b>")
else:
return HttpResponse("Login <b>Fail</b>")

#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

Observation: login_check Function Redirecting request to some other websites.

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")

Observation : login_check rendering request to HTML files.

def login_check(request):
username = request.POST["username"]
password = request.POST["password"]

if username=="ratan" and password=="anu":


return render(request,"success.html")
else:
return render(request,"fail.html")

prepare success.html file in template folder.


<html>
<body>
This is Successful Login....
</body>
</html>

prepare fail.html file in template folder.


<html>
<body>
This is Fail Login....
</body>
</html>

264 | P a g e
Python Material Mr. Ratan

ex-3: Checking employee states : Eligible to marriage or not.


emp.html
<html>
<body>
<form action="/employeecheck/" method="post">
{% csrf_token %}
Emp name :<input type="text" name="empname"><br>
Company :<input type="text" name="company"><br>
Salary :<input type="number" name="salary"><br>
<input type = "submit" value="submit">
</form>
</body>
</html>

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']

if salary > "10000" or company=='tcs':


return HttpResponse("Eligible for Marriage..")
else:
return HttpResponse("Not Eligible for Marriage..")

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

Observation: employeecheck Function Redirecting request to some other websites.


def employeecheck(request):
empname = request.POST['empname']
company = request.POST['company']
salary = request.POST['salary']

if salary > "10000" or company=='tcs':


return HttpResponseRedirect("http://shadi.com")
else:
return HttpResponseRedirect("http://facebook.com")
Observation : employeecheck rendering request to HTML files.
def employeecheck(request):
empname = request.POST['empname']
company = request.POST['company']
salary = request.POST['salary']

if salary > "10000" or company=='tcs':


return render(request,"marraige.html")
else:
return render(request,"NoMarriage.html")
create marriage.html under template folder
<html>
<body>
Happy Married life...
</body>
</html>
create nomarriage.html under template folder
<html>
<body>
Try after sometime..
</body>
</html>

Material by Mr. Ratan...........

"Postponing the work is not Good for Health"

********* Topic Completed: Thank you ************

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.

install the pandas:


pip install pandas

import the pandas with alias name:


import pandas as pd

We can analyze data in pandas with:


a. Series
b. DataFrames

Day-1 : process to fallow :


we have python data
based on python data create the series
based on series create the DataFrame
write the DataFrame to csv files

Day-2 : Read the data from csv file Apply operations.

Series Creation

ex-1: Creating series of int,float data : with default indexes(integer)


A series object can contain any type of data.

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)

#series of float data


data = [3,2,5,7.5,9,3,2]
s1 = pd.Series(data)
print(s1)
print(s1.dtype)

267 | P a g e
Python Material Mr. Ratan

ex 2: series of data with user defined index.


import pandas as pd
data = [3,2,5,7,9]
index = ['a','b','c','d','e']
s1 = pd.Series(data,index)
print(s1)

s= pd.Series(["ramu","anu","raju","ramu"],['i','ii','iii','iv'])
print(s)

ex 3: if we are passing dict to Series


The dict keys becomes indexes.
The dict values becomes data series.

import pandas as pd
dict = {1:"a",2:'b',3:'c',4:'d'}
s = pd.Series(dict)
print(s)

ex 4: combining multple series making one Series


import pandas as pd
s = pd.Series((1,2,3)) + pd.Series([10,20,30])
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)

ex 5: creating user defined series using range()


import pandas as pd
even = pd.Series(range(2,101,2))
print(even)

odd = pd.Series(range(1,101,2))
print(odd)

result = even + odd


print(result)

268 | P a g e
Python Material Mr. Ratan

DataFrame

ex-1: DataFrame with default index.


when we make the dict as a DataFrame
The keys become column names[headers].
The values become the data.

import pandas as pd
dict = {'names':['ratan','ramu','raju'],
'numbers':[1,2,3],
'fruits':['apple','mango',"orange"]}

df = pd.DataFrame(dict)
print(df)

ex-2: DataFrame with user defined index.


import pandas as pd
data = {
'A': [1,4,7],
'B': [2,5,8],
'C': [3,6,9]
}
df = pd.DataFrame(data,index=['i','ii','iii'])
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)

purchases = pd.DataFrame(data,index=['ratan', 'ramu', 'rani', 'David'])


print(purchases)

269 | P a g e
Python Material Mr. Ratan

ex 4: creating DataFrame writing to csv file.

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")

ex-5: creating DataFrame writing to csv file.

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.....")

ex-6: creating DataFrame writing to csv file.

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

Ex-7: appending one data frame to another data frame.


import pandas as pd
df1 = pd.DataFrame({
"Company Name":["Google", "Microsoft", "SpaceX","Amazon","Samsung"],
"Founders":['Larry Page','Bill Gates','Elon Musk','Jeff Bezos', 'Lee Byungchul'],
"Founded": [1998, 1975, 2002, 1994, 1938],
"Number of Employees": [103459, 144106, 6500647,50320,67145]})

df2 = pd.DataFrame({
'Company Name':['WhatsApp'],
'Founders':['Jan Koum, Brian Acton'],
'Founded': [2009],
'Number of Employees': [5000]}, index=['i'])

res = df1.append(df2,ignore_index = True)


print(res)

ex-8: creating data frame with random data.


import pandas as pd
import numpy as np

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)

ex-9: creating DataFrame Reading the data from json file.


#sample.json
{"mobile": [80808,90909], "hobbies": ["cric", "music"],
"email": null, "status": true}

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

ex-10 : creating data frame writing to CSV file.

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

Reading the data from csv file

ex-1:
import pandas as pd
data = pd.read_csv("sample.csv")
#printing number of columns
print(data.columns)
print(data.columns[0:2])

#printing colums in list format


print(list(data.columns))
print(list(data.columns[0:2]))

#printing data types


print(data.dtypes)
print(data['eid'].dtypes)

print(data.shape) # printing rows & columns


print(data.shape[0]) # to print rows
print(data.shape[1]) # to print column

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])

ex 3: Reading the data from csv file : applying some conditions.

import pandas as pd
data = pd.read_csv("sample.csv")

#both lines are same : getting specefic colums


print(data.head()[['eid', 'ename']])
print(data[['eid', 'ename']].head())

#applying conditions on csv file data


print(data[data.status == 'Medium'][['eid','status', 'ename']])
print(data[data.esal >= 15000][['eid','ename', 'esal']])

print(data['status'].unique())
print(len(data['status'].unique()))

print(data['height'].isnull().sum())

274 | P a g e
Python Material Mr. Ratan

ex 4: read the data from csv perform delete operations


import pandas as pd
data = pd.read_csv('sample.csv')
data = data.drop([data.index[9]])

data = data[data.ename != 'Don']


print(data)

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())

ex 5: Reading the data from csv file


import pandas as pd
data = pd.read_csv('sample.csv')

#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)

#reading the data colum by cloum


for k,v in df.iteritems():
print(k,v)

#reading the data row by row


for row_index,row in df.iterrows():
print(row_index,row)

#reading the data in tuple format


for row in df.itertuples():
print(row)

276 | P a g e
Python Material Mr. Ratan

Numpy : numerical python

NumPy is a python library used for working with arrays.


NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it
freely.
NumPy stands for Numerical Python.

NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access
and manipulate them very efficiently.

install the numpy using pip command


pip install numpy

import the numpy with alias name


import numpy as np

ex-1: Data with list check the size


from sys import getsizeof as size

lst = [24, 12, 57]

size_of_list_object = size(lst) # only green box


size_of_elements = len(lst) * size(lst[0]) # 24, 12, 57

total_list_size = size_of_list_object + size_of_elements


print("Size without the size of the elements: ", size_of_list_object)
print("Size of all the elements: ", size_of_elements)
print("Total size of list, including elements: ", total_list_size)

277 | P a g e
Python Material Mr. Ratan

ex-2: numpy array data storing.


import numpy as np
from sys import getsizeof as size
a = np.array([24, 12, 57])
print(size(a))

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

ex-3: different types of int data.


from sys import getsizeof as size
import numpy as np

a = np.array([24, 12, 57], np.int8)


print(size(a) - 96)
a = np.array([24, 12, 57], np.int16)
print(size(a) - 96)

a = np.array([24, 12, 57], np.int32)


print(size(a) - 96)
a = np.array([24, 12, 57], np.int64)
print(size(a) - 96)

int8 Byte (-128 to 127)


int16 Integer (-32768 to 32767)
int32 Integer (-2147483648 to 2147483647)
int64 Integer (-9223372036854775808 to 9223372036854775807)

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("Type of F: ", F.dtype)


print("Type of V: ", V.dtype)

print("Dimension of F: ", np.ndim(F))


print("Dimension of V: ", np.ndim(V))

ex-5: two dimensional array.


import numpy as np
b = np.array([[1,2,3],
[4,5,6]])
print(b)
print(b.dtype)
print(b.shape)

print(b[0, 0], b[0, 2], b[1, 1]) # 1 3 5


b[0, 0] = 10
b[1, 1] = 20

print(b)

279 | P a g e
Python Material Mr. Ratan

ex 6: creating array in different formats.

np.zeros() : Create an array of all zeros.


np.ones() : Create an array of all ones.
np.full() : Create a constant array.
np.eye() : Create a 2x2 identity matrix.

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)

ex-7: creating array in different formats.

280 | P a g e
Python Material Mr. Ratan

arange( start_value, end_value, step_value)


linspace(start_value,end-Value,number_of_values)

import numpy as np
data1 = np.arange( 10, 30, 5 )
print(data1)
print(type(data1))

data2 = np.arange( 0, 2, 0.3 )


print(data2)
print(type(data2))

data3 = np.linspace( 0, 2, 9)
print(data3)
data3 = np.linspace( 1, 10, 4)
print(data3)

ex 8: Array with slicing


import numpy as np
a = np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
#[rows_info , col_info]
row_r1 = a[1, :]
print(row_r1)
row_r2 = a[1:2, :]
print(row_r2)

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

ex-9: adding & multiplying & subtracting arrays.


import numpy as np

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))

x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])


v = np.array([1, 0, 1])
print(x + v)
E:\>python first.py
[[ 6 8]
[10 12]]
[[ 6 8]
[10 12]]
[[-4 -4]
[-4 -4]]
[[-4 -4]
[-4 -4]]
[[ 5 12]
[21 32]]
[[ 5 12]
[21 32]]
[[0.2 0.33333333]
[0.42857143 0.5 ]]
[[0.2 0.33333333]
[0.42857143 0.5 ]]
[[1. 1.41421356]
[1.73205081 2. ]]
[[ 2 2 4]
[ 5 5 7]
[ 8 8 10]
[11 11 13]]

282 | P a g e
Python Material Mr. Ratan

ex-10: Array reshaping & Flatten arrays


import numpy as np
arr = np.array([[1, 2, 3, 4],
[5, 2, 4, 2],
[1, 2, 0, 1]])

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()

print ("\nOriginal array:\n", arr)


print ("Fattened array:\n", flarr)

ex-11: addition & subtraction & Transpose of array.


import numpy as np

a = np.array([1, 2, 5, 3])

# add 1 to every element


print ("Adding 1 to every element:", a+1)
# subtract 3 from each element
print ("Subtracting 3 from each element:", a-3)

# multiply each element by 10


print ("Multiplying each element by 10:", a*10)
# square each element
print ("Squaring each element:", a**2)

# modify existing array


a *= 2
print ("Doubled each element of original array:", a)

# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])

print ("\nOriginal array:\n", a)


print ("Transpose of array:\n", a.T)

283 | P a g e
Python Material Mr. Ratan

ex-12: finding minimum & maximum in elements.


import numpy as np

arr = np.array([[1, 5, 6],


[4, 7, 2],
[3, 1, 9]])

# maximum element of array


print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:",
arr.max(axis = 1))

# minimum element of array


print ("Column-wise minimum elements:",
arr.min(axis = 0))

# sum of array elements


print ("Sum of all array elements:",
arr.sum())

# cumulative sum along each row


print ("Cumulative sum along each row:\n",
arr.cumsum(axis = 1))

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)

# Plot the points using matplotlib


plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
plt.show()

286 | P a g e
Python Material Mr. Ratan

Ex-4: creating pie chart: This pie-chart based on reviews of students.


import matplotlib.pyplot as plt

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"]

plt.pie(values, labels=institutes, explode=explode, colors=colors, autopct="%0.1f%%")


plt.show()

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

 It is highly recommended to store complete application flow and exceptions information to a


file. This process is called logging.
 The log files will track the error messages.

Depending on type of information, logging data is divided according to the following 5 levels.

1. CRITICAL : 50 : Represents a very serious problem that needs high attention


2. ERROR : 40 : Represents a serious error
3. WARNING : 30 : Represents a warning message,some caution needed.it is an alert
4. INFO : 20 : Represents a message with some important information
5. DEBUG : 10 : Represents a message with debugging

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)

ex-1: import logging


logging.basicConfig(filename='log.txt',level=logging.WARNING)
logging.debug("This is debug message")
logging.info("This is info message")
logging.warning("This is warning message")
logging.error("This is error message")
logging.critical("This is critical message")
Note:
In the above program only WARNING and higher-level messages will be written to log file.
If we set level as DEBUG then all messages will be written to log file.
ex-2:
import logging
logging.basicConfig(filename=log.txt',level=logging.INFO)
logging.info("Request processing started:")
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ZeroDivisionError as msg:
print("ZeroDivisionError occurred")
logging.exception(msg)
except ValueError as msg:
print("Enter only integer values")
logging.exception(msg)
logging.info("Request processing completed:")

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

INFO:root:Request processing completed:


INFO:root:Request processing started:
ERROR:root:invalid literal for int() with base 10: 'ratan'
Traceback (most recent call last):
File "first.py", line 5, in <module>
x=int(input("Enter First Number: "))
ValueError: invalid literal for int() with base 10: 'ratan'
INFO:root:Request processing completed:

Ex: logging with threading.


import logging
import threading
import time

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()}')

t = threading.Thread( target=my_service,name="my service")

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

install the pillow using pip command


E:\>pip install pillow

ex-1: loading the image : finding format,size,mode

from PIL import Image


try:
original = Image.open("Desert.JPG")
print(original.format, original.size, original.mode)
original.show()
except:
print ("Unable to load image")

ex-2: making image BLUR

from PIL import Image, ImageFilter


import sys
try:
img = Image.open("Desert.jpg")
except IOError:
print("Unable to load image")
sys.exit(1)

blurred = img.filter(ImageFilter.BLUR)
blurred.save("blurred.png")
print("operations are completed....")

ex-3: converting one image format into another image. [JPG --- PNG]

from PIL import Image


import sys
try:
tatras = Image.open("Desert.jpg")
except IOError:
print("Unable to load image")
sys.exit(1)
tatras.save('ratan.png', 'png')
print("operations are completed....")

291 | P a g e
Python Material Mr. Ratan

ex-4: showing the image in light color.

from PIL import Image


import sys
try:
tatras = Image.open("Desert.jpg")
except IOError:
print("Unable to load image")
sys.exit(1)
grayscale = tatras.convert('L')
grayscale.show()

ex-5: cropping image.

from PIL import Image


import sys
try:
tatras = Image.open("Desert.jpg")
except IOError:
print("Unable to load image")
sys.exit(1)

cropped = tatras.crop((100, 100, 350, 350))


cropped.save('ramu.jpg')

ex-6: image drawing

from PIL import Image, ImageDraw

img = Image.new('RGBA', (200, 200), 'white')


idraw = ImageDraw.Draw(img)

idraw.rectangle((10, 10, 100, 100), fill='blue')

img.save('rectangle.png')

292 | P a g e
Python Material Mr. Ratan

ex-7: creating water mark on the image.


from PIL import Image, ImageDraw, ImageFont
import sys
try:
tatras = Image.open("Desert.jpg")
except:
print("Unable to load image")
sys.exit(1)

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')

ex-8: Rotating image


from PIL import Image, ImageDraw, ImageFont
import sys
try:
img = Image.open("Desert.jpg")
rotated = img.rotate(180)
rotated.save('tatras_rotated.jpg')
except IOError:
print("Unable to load image")
sys.exit(1)

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’.

install the tkinter using pip command


pip install tkinter

import the tkinter using alias name.


import tkinter as tk

ex-1: creating window


import tkinter as tk
window = tk.Tk()
window.title("GUI")
# write the logics here
window.mainloop()

ex-2: creating Label & botton creation with pack.


import tkinter as tk
window = tk.Tk()
window.title("First app")
window.geometry("400x200")

tk.Label(window, text = "HI students Good Morning!").pack()


tk.Button(window, text = "tkinter module", fg="red",bg="green").pack()

window.mainloop()

We can do the alignment on the frame in three ways.


a. Pack() : Auto adjustment
b. grid() : Rows & column
c. place() : x & y axis location.

294 | P a g e
Python Material Mr. Ratan

ex-3: Login Page : alignment is done using grid[rows & column]


import tkinter as tk
window = tk.Tk()
window.title("GUI")
window.geometry("400x200")

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)

tk.Button(window,text="Login", fg="red", bg="yellow").grid(row=3,column=1)


window.mainloop()

ex-4: Login Page : alignment is done using place[x & y]


from tkinter import *
window = Tk()
window.geometry("400x200")

name = Label(window, text = "Name").place(x = 30,y = 50)


email = Label(window, text = "Email").place(x = 30, y = 90)
password = Label(window, text = "Password").place(x = 30, y = 130)

Entry(window).place(x = 80, y = 50)


Entry(window).place(x = 80, y = 90)
Entry(window).place(x = 95, y = 130)

Button(window, text="Login",fg = "red").place(x = 120, y = 160)


window.mainloop()

295 | P a g e
Python Material Mr. Ratan

ex-5: creating dynamic button using command


import tkinter
window = tkinter.Tk()
window.title("GUI Appliation")

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()

tkinter.Button(window, text = "Wish ratan!", command = wish_ratan).pack()


tkinter.Button(window, text = "Wish anu!", command = wish_anu).pack()
tkinter.Button(window, text = "Wish students!", command = wish_students).pack()
window.mainloop()

ex-6: creating dynamic login page perform login success or fail.


from tkinter import *
from functools import partial
window = Tk()
window.geometry("400x200")
window.title("Login Application")

def validateLogin(username, password):


if username.get()=="ratan" and password.get()=="anu":
Label(window, text = "Login Successfull",fg="red").place(x = 90,y = 100)
else:
Label(window, text = "Login Failed...Please try again",fg="red").place(x = 90,y = 100)

Label(window, text="User Name").grid(row=0, column=0)


username = StringVar()
Entry(window, textvariable=username).grid(row=0, column=1)

Label(window,text="Password").grid(row=1, column=0)
password = StringVar()
Entry(window, textvariable=password, show='*').grid(row=1, column=1)

loginButton = Button(window, text="Login", command=partial(validateLogin, username,


password)).grid(row=4, column=0)

window.mainloop()

296 | P a g e
Python Material Mr. Ratan

ex-7: checkbox creation.


import tkinter
from tkinter import *
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
CheckVar3 = IntVar()
tkinter.Checkbutton(top, text = "Python",variable = CheckVar1,onvalue = 1,
offvalue=0).grid(row=0,column=0)
tkinter.Checkbutton(top, text = "Django", variable = CheckVar2, onvalue = 1, offvalue
=0).grid(row=0,column=1)
tkinter.Checkbutton(top, text = "Flask", variable = CheckVar3, onvalue = 1, offvalue
=0).grid(row=0,column=2)
top.mainloop()

ex-8: combo box creation.


from tkinter.ttk import *
import tkinter as tk
window = tk.Tk()

combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, "Text")
combo.current(3)
combo.grid(column=0, row=0)

window.mainloop()

ex-9: radio button creation.


from tkinter.ttk import *
import tkinter as tk
window = tk.Tk()

rad1 = Radiobutton(window, text='Python', value=1)


rad2 = Radiobutton(window, text='Django', value=2)
rad3 = Radiobutton(window, text='Flask', value=3)
rad1.grid(column=0, row=0)
rad2.grid(column=1, row=0)
rad3.grid(column=2, row=0)

window.mainloop()

297 | P a g e
Python Material Mr. Ratan

ex-10: Registration application.

from tkinter import *


from tkinter.ttk import *
from functools import partial
window = Tk()
window.geometry("600x500")
window.title("Registration")

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)

firstLabel = Label(window, text="Firstname").grid(row=0, column=0)

firstname = StringVar()
firstEntry = Entry(window, textvariable=firstname).grid(row=0, column=1)

lastLabel = Label(window,text="Lastname").grid(row=1, column=0)


lastname = StringVar()

lastEntry = Entry(window, textvariable=lastname).grid(row=1, column=1)

genderLabel = Label(window,text="Gender").grid(row=2, column=0)

rad1 = Radiobutton(window, text='Male',variable=var, value=1).grid(row=2, column=1)


rad2 = Radiobutton(window, text='Female',variable=var, value=2).grid(row=2, column=2)

298 | P a g e
Python Material Mr. Ratan

CheckVar1 = IntVar()
CheckVar2 = IntVar()
CheckVar3 = IntVar()

courseLabel = Label(window,text="Course").grid(row=3, column=0)


Checkbutton(window, text = "Python",variable = CheckVar1,onvalue = 1, offvalue=0).grid(row=3,
column=1)
Checkbutton(window, text = "Django", variable = CheckVar2, onvalue = 2, offvalue
=0).grid(row=3, column=2)
Checkbutton(window, text = "Flask", variable = CheckVar3, onvalue = 3, offvalue =0).grid(row=3,
column=3)

selectLabel = Label(window,text="Experience(years)").grid(row=4, column=0)


combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, "More than 5")
combo.current(0)
combo.grid(row=4, column=1)

register = partial(register, firstname, lastname,var,CheckVar1,CheckVar2,CheckVar3)

loginButton = Button(window, text="Register", command=register).place(x=100, y=150)

window.mainloop()

299 | P a g e
Python Material Mr. Ratan

ex-11: calculator example.


from tkinter import *

# Let's create the Tkinter window


window = Tk()
# Then, you will define the size of the window in width(312) and height(324) using the 'geometry'
method
window.geometry("312x324")
# In order to prevent the window from getting resized you will call 'resizable' method on the window
window.resizable(0, 0)
#Finally, define the title of the window
window.title("Calcualtor")

# 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.

# The first thing is to create a frame for the input field


input_frame = Frame(window, width = 312, height = 50, bd = 0, highlightbackground = "black",
highlightcolor = "black", highlightthickness = 1)
input_frame.pack(side = TOP)

# 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

Working with jupyter:


Step 1 : in google search bar type try jupyter.

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

Step 3: select the python 3 note book

Step 4: write the code in notebook.

304 | P a g e
Python Material Mr. Ratan

Step 5 : Run the application by clicking run button.

305 | P a g e
Python Material Mr. Ratan

Material by Mr. Ratan...........

306 | P a g e

You might also like