You are on page 1of 449

Course : Python (Core & Adv Python) and Project

Course Content : https://nareshit.in/python-training/

Duration : 50 sessions

session time : 11:00am to 12:45pm

contact person(non technical):

rambabu

: 9866545966

support@nareshit.com

pythonbrains ==> facebook group

pythonbygupta@gmail.com

mon-sat ==>

Q: What is python?

Q: Features Python

Q: Who developed python?

Q: Why developed python?

Q: When developed python?

Q: Applications of python

Q: Who uses python

Demo-1:

Q: What is python?

==> python is a programming language.

==> language is a mediator between user and computer.

==> language is a tool which provide set of instructions to perform operations.

==> language is a software which provide set of instructions to develop softwares or applications.

==> python is general purpose programming language.

==> a programming language which can be used for developing

any type of application or software is called general purpose programming

language.

1
==> python is a high level programming language. all high level language are simple english. all high level
languages are portable language. portability allows to develop and run python programs on different
platforms.

==> python is a multiparadigm programming language. A programming paradigm define set of rules and
regulations to write programs.

1. Monolithic Porgramming

2. POP==> Procedural Oriented Programming

3. OOP==> Object Orineted Programming

Q: What is python?

1. Programming Language

2. General Purpose

3. High Level and Portable

4. Multiparadigm

Python is a general purpose,high level,portable multiparadimg

programming alngauge.

Demo-2:

Python Features

=============

1. Easy

a. easy to understand

b. easy to code

==> python is easy to understand becoz it is high level language and high level language are english like.

==> easy to code or less coding.

2. dynamically typed language

==> python uses dynamic memory allocation.

==> in python does not requied datatypes to create variables.

==> variables are created by just assigning values.

==> in python memory management is done by python.

2
3. Free and OpenSource

==> Python software is free.

==> It can downloaded from www.python.org

==> Python is available for all operating systems or platforms.

Q: What is Open Source?

==> python source code is open to public. which allows to develop new technologies using python.

==> Python is managed by an orgnization called PSF.

==> PSF (Python Software Foundation).

==> PSF community name.

Demo-3:

=======

4. Large Standard Library

==> Library is a set predefined programs.

==> Python comes with huge number of libraries.

==> Library is a set of predefined programs(functions).

==> Using these libraries we develop different types of

applications.

5. Extensible and Embeddable

==> Python provide different implementations(softwares)

1. Cpython

2. Jython

3. IronPython

4. Pypy

C ==> Turboc

Python ==> Python Software(CPython)

Jython ==> Python Software(Java+Python)

IronPython ==> Python Software(.Net+Python)

PyPy ==> Python Software(Python+R)

Anaconda Python ==> Python Software(Python+DataScience+AI)

3
Demo-4:

6. Interpreted

=============

Python is high level langauge(English).

Q: What is Translator?

Translator is a software which translates the instructions written in one language to another
language.(Source Language==>Translator==>Dest Language)

1. Interpreter

2. Compiler

==> Python is compiled and interpreted.

Q: What is interpreter?

==> interpreter is a translator, which translates and execute execute instructions line by line.

Q: What is compiler?

==> compiler is a translator, which translate complete program and start execution.

Q: What is bytecode?

==> compiled code of python source program is called bytecode.

==> bytecode is a collection of mnemonics, which understand by pvm(python virtual machine).

==> bytecode is a platform independent code.

==> bytecode is a python virtual machine code. this code understand by

PVM.

Q: What is PVM?

==> PVM stands for Python Virtual Machine.

==> PVM provide runtime environment for python programs.

==> PVM is platform in which python programs run.

Applications of Python

==================

==> Applications or softwares which can be deveoped using

python.

==> Python is a programming language, developed by

4
Guideo Van Rossum in the year 1980.

==> Python name is derived/taken from comedy series which is telecasted in BBC in 1980. "Monty
python flying Circus'

==> Python is a language derived from ABC.

Python Versions

=============

Python software comes in two versions.

1. Python 2.x ==> 2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7

2. Python 3.x ==> 3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8

Python 2.x Python 3.x

int,long int

raw_input input

print statement print()

xrange range

www.python.org

Python Software

==============

1. Standard Python Software(www.python.org)

1. Windows

2. Linux

3. Solaries

4. MacOS

2. Jython ==> Java+Python

3. IronPython ==> .Net+Python

4. Anconda Python ==> Python+DataScience tools/lib

6. Pypy ==> Python+R

7. Qpython ==> Python+Android

8. Pythonnista ==> Python +IOS

5
Python Software Consist of,

1. IDE ==> Integrated Development Environment/Editor ==>

IDLE(Integrated Development Learning Evnironement)

2. Lib

3. development tools(pip)

4. Python compiler

5. Python Interprter(PVM)

Python working modes:

1. Interactive mode

2. Scripting mode/programming mode

Python IDE's(Editors)

==================

1. PyCharm

2. Jupiter

3. Spyder

4. Microsoft Visual studio

REPL ==> Read Eval Print Loop

Character set of python

===================

==> a set of characters used in python to write a program.

==> character set also define encoding and deconding standards.

encoding ==> character==> decimal number ==> binary

decoding ==> binary ==> decimal ==> character

encoding ==> A ==> 65 ==> 1000001

decoding ==> 1000001 ==> 65 ==> A

==> there are two encoding and decoding standards or characters

1. ASCII ==> American Standard Code for Information Interchange

2. UNICODE ==> Universal Codes

ASCII support alphabets in english(A-Z,a-z),digits(0-9) and special characters.

6
UNICODE support alphabets in all languages,digits(0-9) and special characters.

There are different types of unicode character sets.

unicode 8bits ==> ascii(256)

unicode 16bits ==> 65536

unicode 32bits ==> more than 65536 characters

Tokens

======

==> A smallest individual unit with in program is called token.

1. keywords

2. identifiers

3. datatypes

4. operators

5. literals

keywords

========

==> keywords are predefined word or reserved words.

==> these words cannot used as userdefined words/identifiers.

==> python support 35 keywords.

==> these are case sensitive.

1. keywords belongs to operators

and,or,not,del,in,as,is

2. keywords belongs to values

True,False,None

3. keywords belongs to control statements

if,else,elif,for,while,break,continue,return

4. keywords belongs to functions

def,global,nonlocal,lambda,yield,pass

5. keywords belongs to modules

import,from,with

7
6. keywords belongs execption handling

try,except,finally,raise,assert

7. keywords belongs to class

class

8. keywords belongs to threads

async,await

Identifiers

=========

==> Identifiers are userdefined words

==> Identifiers are used to identify programming elements.

==> Identifier is a collection of alphabets(A-Z/a-z),digits(0-9)

and allows one special character _

1. variables

2. functions

3. classes

4. modules

5. packages

Identifier rules

=============

1. identifier should not be a keyword

2. there should not be any space between identifier

3. identifier name should start with alphabet or _ but should not

start with digit.

4. there is no limit of identifier length.

5. identifier can be in uppercase or lowercase.

Quiz:

Q: Which of the following are valid identifiers?

A. True

B. False

8
C. true

D. false

Ans: C,D

Q: Which of the following are true according to python language.

A. All identifiers should be given in lowercase

B. All keyword in python in lowercase

C. Keywords can be used as identifiers

D. Python is case sensitive language

Q: Which of the following are invalid identifiers?

A. $amt

B. amt$

C. student_name

D. amt_

Q: Which of the following are keywords in python

A. int

B. float

C. class

D. False

Q: How many keywords are in python?

35

pythonbygupta@gmail.com ==> python 11am

Datatypes

=========

==> Datatypes are required to allocate memory for data.

==> Python datatypes are classified into 3 categories.

1. Standard Datatypes

2. Sequences

3. Collections

==> every datatype in python is a class and data is represented as objects.

9
==> python is an object oriented programming language.

==> in object oriented programming languages data is represented as objects.

==> object oriented is not a language, it is programming approch.

Q: What is object?

==> object is a real world entity.

eg: car,mobile,keyboard,monitor,customer,account,employee,product,...

==> every object is having 3 characterstrics.

1. properties : define state of the object/data

2. behaviour : define the functionality of the object

3. identity : it is name given to object

Q: What is class?

==> class is a datatype.

==> class is encapsulated with properties and behaviour of object.

==> class is blueprint of object.

==> class is used to create object or to allocate memory for object.

==> class define the structure of object.

SBI of an object?

SBI stands,

S ==> State

B ==> Behaviour

I ==> Identity

Q: What is variable?

==> variable is a named memory location.

==> variable is an identifier.

==> variable is name given object.

==> in python variables are reference types.

==> these variables hold address of object.

==> in python variables are created by assigning value.

10
int

==

==> int predefined class in python.

==> int datatype allocates memory for integer value(whole numbers).

==> int datatype allocates memory of unlimited length.

==> in python memory allocated based on value size.

==> int immutable datatype.

==> once integer object is created we cannot modify value.

==> integers are constants, which cannot modified.

==> becoz of immutability these objects can be shared.

pythonbygupta@gmail.com ==> 11am

pythonbrains

26/5/2020
=========

id(object)

Return the “identity” of an object. This is an integer which is guaranteed to be unique

and constant for this object during its lifetime

This is the address of the object in memory.

eg:

>>> a=10

>>> b=20

>>> id(a)

1720186944

>>> id(b)

1720187104

>>> c=10

>>> id(c)

1720186944

11
==> whenever we modify value, it will create new int object.

QUIZ:

1.How many objects are created?

a=100

b=200

c=300

d=400

Ans: 4 objects

Ans: 4 variable

2. How many variables and objects are created?

a=100

b=200

c=100

d=200

Ans: 2 objects

4 variables

3. How many objects are created?

a=5

b=5

c=10

d=a+b

Ans: 2 objects

4 variables

4. How many objects are created?

a=10

b=20

c=a+b

Ans: 3 objects

12
5. How many objects are garbage collected?

a=100

b=200

c=100

a=300

Ans: 0

==================================

x=257

y=257

print(id(x))

print(id(y))

========================================

27/5/2020
=========

integer literals: literal is syntactical representation of value.

==> integer values are represented in different formats.

1. decimal format

2. octal format

3. hexa decimal format

4. binary format

decimal number: an number value with base 10 is called decimal number. this number

consist of digits from 0-9. this number is prefix with + or -. the defualt number system

is decimal. it allows one special character _. _ character is used in numbers for grouping digits. this _
cannot used as prefix or sufix.decimal number should not start with 0.

binary number : an numeric value with base 2 is called binary number. this number of consist of two
digits 0,1. this number is prefix with 0b or 0B.

eg:

>> > x=0b101

>>> y=0b10101

13
>>>x

>>>y

10

hexa decimal format : a numeric value with base 16 is called hexa decimal numer. this number consist of
digits from 0-9 and a-f/A-F. this number is prefix 0x or 0X. this number is system is used to represent
larger values(address,colors,...)

eg:

>>>x=0xa

>>>y=0xb

>>>x

10

>>>y

11

octal number : a numeric value with base 8 is called octal number. this number consist of digits from 0-
7. this number is prefix with 0o or 0O.

>>>x=0o12

>>>y=0o13

>>>x

10

>>>y

11

Q: How to create integer variable?

python : a=0

c : int a;

==> integer variables are created by assigning integer value.

type(variable-name/value):

==> return type of value hold by variable.

==> type is predefined function in python.

>>>a=10

14
>>>type(a)

<class 'int'>

float

====

==> float is standard datatype.

==> float is predefined class in python.

==> float datatype reserve memory for real numbers or floating point numbers or

fractional numbers. a numeric value which contain decimal part.

==>python allows to represent float values in two formats.

1. fixed

2. expo

28/5/2020
=========

float

====

==> float is standard datatype.

==> float is predefined class in python.

==> float datatype reserve memory for real numbers or floating point numbers or

fractional numbers. a numeric value which contain decimal part.

==>python allows to represent float values in two formats.

1. fixed

2. expo

==> float is a constant or immutable object. the value of this

object cannot modified.

==> becoz of immutable they can be shared.

fixed ==> 1.5

exp ==> 15e-1 ==> 15x10 pow -1 ==> 1.5

where the value of e is 10

15
==> whenever there is a change it will create new object.

==> float reserve memory of unlimited length.

c ==> float =4 bytes

double == 8bytes

python float ==> unilimited (dynamic)

eg:

x=1.5

y=1.5e0

print(id(x))

print(id(y))

print(x)

print(y)

print(type(x))

print(type(y))

QUIZ:

Q: Find output?

x=1.0

y=1.

print(x)

print(y)

output: 1.0

1.0

Q: Find output?

x=123e-2

print(x)

Output:

1.23

16
Q: Find Output?

x=123e2

print(x)

Output: 12300.0

Q: How many objects are created?

x=0.5

y=0.5

Ans: 1

complex

=======

==> this datatype is used to create complex number.

==> complex number is having two properties.

1. real 2. img

syntax:

real+imagj

imag value must suffix with j

eg:

>>> comp1=1+2j

>>> comp1

(1+2j)

>>> comp1.real

1.0

>>> comp1.imag

2.0

>>> type(comp1)

<class 'complex'>

>>> type(comp1.real)

<class 'float'>

>>> type(comp1.imag)

17
<class 'float'>

==> complex number is immutable, after creating complex number we cannot modify

real and imag values.

>>> comp1.real=1.2

Traceback (most recent call last):

File "<pyshell#13>", line 1, in <module>

comp1.real=1.2

AttributeError: readonly attribute

>>> comp1.imag=2.0

Traceback (most recent call last):

File "<pyshell#14>", line 1, in <module>

comp1.imag=2.0

AttributeError: readonly attribute

eg: write a the following script

comp1=1+2j

comp2=1+2j

print(comp1)

print(comp2)

print(type(comp1))

print(type(comp2))

print(id(comp1))

print(id(comp2))

print(comp1.real)

print(comp1.imag)

print(comp2.real)

print(comp2.imag)

comp1.real=1.4 ==> error

comp1.imag=1.5 ==> error

18
QUIZ:

Q: Find the output?

comp1=1+2j

comp2=2j

comp3=1

print(type(comp1)) ==> complex

print(type(comp2)) ==> complex

print(type(comp3)) ==> int

Q: Find the output?

comp1=1+2j

comp2=2j

print(comp1) ==> (1+2j)

print(comp2) ==> (0+2j)

bool

====

==> boolean is a constant or immutable type.

==> boolean variables are created by assigning boolean values.

==> in python boolean values are represented using two

keywords.

1. True

2. False

>>> a=True

>>> b=False

>>> a

True

>>> b

False

>>> type(a)

<class 'bool'>

19
>>> type(b)

<class 'bool'>

name=

age=90

seats=5

seatsreserved=True

string

=====

==> string is a collection of characters and these characters can be alphabets,digits or special characters.

==> the string which contain only alphabets is called alphabetic string.

==> the string which contain alphabets,digits and special characters is called alphanumeric string.

==> string is immutable.

==> python allows to represent string value in three ways.

1. within single quotes ' '

2. within double quotes " "

3. within three single quotes ''' ''' or three double quotes """ """

eg:

>>> name='naresh'

>>> name

'naresh'

>>> type(name)

<class 'str'>

>>>

>>> name1="suresh"

>>> name2='''ramesh'''

>>> name3="""rajesh"""

>>> type(name1)

<class 'str'>

20
>>> type(name2)

<class 'str'>

>>> type(name3)

<class 'str'>

>>> name

'naresh'

>>> name1

'suresh'

>>> name2

'ramesh'

>>> name3

'rajesh'

>>>

29/5/2020
=========

==> with single quotes we can embed double quotes

==> with double quotes we can embed single quotes

==> using three signle quotes or double quotes we can represent multiline string.

three single quotes allows to embed double quotes

three double quotes allows to embed single quotes

Q: write a script to print the following message?

Python is "PURE" object oriented language

print('Python is "PURE" object oriented language')

Q: write a script to print the following message?

Python is a 'General Purpose' programming language

21
print("python is a 'General Purpose' programming language")

Q: Write a script to print the following message?

python is a high level langauge

python is a general purpose language

python is multiparadigm langauge

print(''' Python is high level langauge

python is general purpose language

python is multiparadigm language''')

print(""" Python is high level langauge

python is general purpose language

python is multiparadigm language""")

print(''' "python is a high level language"

"python is a general purpose language" ''')

print('python\njava\noracle')

escape sequences

================

\n ==> newline

\t ==> horizontal tab space

\v ==> vertical tab space

\b ==> backspace

\\ ==> backslash

\' ==> single quotes '

\" ==> double quotes "

print('python is \'HIGH LEVEL \' langauge')

print("python is \"HIGH LEVEL \" langauge")

==> single and double quotes are used to represent singleline string

==> triple quotes is used to represen multiline string

====================================================================

22
eg:

name="naresh"

address='''Ameerpet,

Hyderabad'''

print(name)

print(address)

===================================================================

eg:

s1="java"

s2="java"

s3="python"

s4="python"

print(id(s1))

print(id(s2))

print(id(s3))

print(id(s4))

print(s1)

print(s2)

print(s3)

print(s4)

# how many objects : 2

# how many variables : 4

==================================================================

Indent

=====

==> indent indicate a block.

==> indent is a column number.

==> every statement in python must start at column number 1.

==> indent is changed when required a block.

23
==> if working with ide's indent is set automatically.

==> indent is a space.

comments in python

=================

==> comment are ignored by python translator.

==> comment is information about programming elements.

==> comment is defined using #

==> it used to define singleline comment.

==> these comments can be written in any where within program.

================================================================

eg:

# program to add two numbers

num1=10 # num1 is a variable which hold 10

num2=20 # num2 is a variable which hold 20

num3=num1+num2 # num3 is variable which hold sum of num1 and num2

print(num1)

print(num2)

print(num3)

==================================================================

multiline comment is define using ''' ''' or """ """

eg:

'''this is program to find

area of circle '''

r=1.5

area=3.147*r*r

print(area)

===================================================================

24
print()

=====

==>print is a predefined function provided by python.

C: python

stdio.h builtins.py ==> module

conio.h os.py ==> module

io.py ==> module

==> default module imported by python program is builtins module.

==>python lib is called module(a module is python program). these modules are

grouped within a pckage. module is a collection of variables,functions and classes.

==> print is a predefined exists in builtins module.

==> this function print values to output stream/console/monitor.

syntax:

print(value,...,sep=' ',end='\n',file=sys.stdout,flush=False)

sep: string inserted between values, default a space.

end: string appended after the last value, default a newline.

eg:

print()

print("Hello World")

print(100,200,300)

print("python",3.8,"lanauge")

QUIZ:

Find output?

print("Python")

print("Python",3.8)

print("Python",3.8,sep='$')

Output:

Python

Python 3.8

25
Python,3.8

Find output?

print(10,20,30,40,50)

print(10,20,30,40,50,sep='$')

10 20 30 40 50

10$20$30$30$50

Find output?

print(10,20,30,40,50,sep='\n')

10

20

30

40

50

We are starting New Online Batch for

CRT@4.00PM

from 28th May

by

Mr. Hari Krishna

Demo Link:

www.zoom.us/j/98394372651

NareshIT

9000994007 / 08

Rambabu

9866545966

1/06/2020
=========

eg:

print("Hello")

26
print(10,20,30,40,50)

print(10,20,30,40,50,sep=':')

print(10,20,30,40,50,sep=',')

print(10)

print(20,end=' ')

print(30)

print(40)

output:

Hello

10 20 30 40 50

10:20:30:40:50

10,20,30,40,50

10

20 30

40

input()

======

==> input() predefined function exists in builtins module.

==> input() function read the value at runtime or from keyboard.

==> input() function read the value and return that value as string.

syntax:

input([prompt])

eg:

a=input()

b=input()

print(a)

print(b)

x=input("X Value")

27
y=input("Y Value")

print(x)

print(y)

eg:

# write a script/program to input rollno,name and display

rollno=input("Enter Rollno")

name=input("Enter name")

print(rollno)

print(name)

output:

Enter Rollno101

Enter namenaresh

101

naresh

===============================================================

n1=input("Enter the value n1")

n2=input("Enter the value n2")

n3=n1+n2

print(n1,n2,n3)

print(type(n1))

print(type(n2))

print(type(n3))

x=100 # x is a variable of type int

y="100" # y is variable of type str

n4=input("Enter the value n4")

print(n4)

print(type(n4))

28
=====================================================================

Conversion functions

==> python provide the following conversion functions to convert one tye of object to

another type.

1. int() function

==> this function is used to convert string to int (OR)

this function is used to create integer object using different types of values.

int(int value) ==> create integer object using integer value

int(float value) ==> create integer object using float value/float to int

int(string value,base=10) ==> create integer object using string value/string to int

eg:

x=100 # creating integer object

y=int(200) # creating integer object

z=int(1.5) # creating integer object using float value or converting float to int

n1=int("100") # converting string to int

n2=int("0o14",base=8) # converting string rep of octal to int

n3=int("0xab",base=16) # converting string rep of hexa to integer

n4=int("0b1010",base=2) # converting string rep of binary to integer

n5=int("456") # integer repreting as string to integer

print(x,y,z)

print(n1,n2,n3,n4,n5)

QUIZ:

Find Error:

x=int("abc") # ValueError

print(x)

Find output?

x=int("1.5") # ValueError becoz the value must be int type

29
print(x)

Find output?

x=int("-10")

print(x)

Find output?

x=int(1.5)

print(x) ==> 1

Find output?

x=int("0o189",base=8) # error

print(x)

Find output?

x=int(0x123) # no error

print(x)

Find output?

x=int("0x123",base=16)

print(x)

# write a script to add two integers

x=input("Enter first number")

y=input("Enter second number")

n1=int(x)

n2=int(y)

n3=n1+n2

print("sum of ",n1,n2,"is",n3)

x=int(input("Enter first number"))

y=int(input("Enter second number"))

z=x+y

print("sum of ",x,y,"is ",z)

float()

30
=====

==> this function is used to create float object.

==> it allows to creating float object using float,int and string value.

x=float(1.5) # creating float object using float value

y=float(15e-1) # creating float object using float value

z=float(15) # creating float object using integer value ==> int to float

p=float("15") # creatinf float object using string value ==> str rep int to float

q=float("1.5") # converting str == float

eg:

n1=float("1.5")

n2=float(1.5)

n3=float(10)

n4=float("10")

n5=float("1.5e2")

print(n1,n2,n3,n4,n5)

eg:

# write a script or program to find area of triangle

base=float(input("Enter base of triangle"))

height=float(input("Enter height of triangle"))

area=0.5*base*height

print("area of triangle is",area)

output:

Enter base of triangle1.5

Enter height of triangle2.5

area of triangle is 1.875

H.W:

1. write a program to find area of circle

31
2. write a program to find simple intrest

3. write a program to find area of rectangle

complex()

========

==> this function is used to create complex number.

==> it allows to create complex number in two ways.

complex(real=0,imag=0) ==> creating complex number using complex

complex(string) ==> creating complex number using string.

eg:

>>> c1=complex(1.5,2.5)

>>> c1

(1.5+2.5j)

>>> c2=complex(real=1.2)

>>> c2

(1.2+0j)

>>> c3=complex(imag=2.5)

>>> c3

2.5j

>>> c4=complex(1+2j)

>>> c4

(1+2j)

>>> c5=complex("1+2j")

>>> c5

(1+2j)

32
02-06-2020
2/06/2020

=========

complex()

========

==> this function is used to create complex number.

==> it allows to create complex number in two ways.

complex(real=0,imag=0) ==> creating complex number using complex

complex(string) ==> creating complex number using string.

eg:

>>> c1=complex(1.5,2.5)

>>> c1

(1.5+2.5j)

>>> c2=complex(real=1.2)

>>> c2

(1.2+0j)

>>> c3=complex(imag=2.5)

>>> c3

2.5j

>>> c4=complex(1+2j)

>>> c4

(1+2j)

>>> c5=complex("1+2j")

>>> c5

(1+2j)

#write a program or script to add two complex numbers

comp1=complex(input("Enter first complex number"))

comp2=complex(input("Enter second complex number"))

33
comp3=comp1+comp2

print(comp1,comp2,comp3)

bool()

=====

==> this function is used to create boolean object.

b1=bool(True)

b2=bool(False)

b3=bool("True")

b4=bool("False")

print(b1,b2)

print(b3,b4)

print(type(b1),type(b2),type(b3),type(b4))

# write a script or program to read rollno,name,fee,feepaid

rollno=int(input("Enter rollno"))

name=input("Enter name")

fee=float(input("Enter Fee"))

feepaid=bool(input("Enter FeePaid"))

print(rollno)

print(name)

print(fee)

print(feepaid)

output:

Enter rollno101

Enter namenaresh

Enter Fee4000

Enter FeePaidTrue

101

naresh

4000.0

34
True

formatting output

===============

==> python allows to format output using string formatting.

==> python provide 3 ways of string formatting.

1. % formatting string or old style formatting

2. format function

3. f-string (new style formatting)

old style string formatting using % operator

===================================

==> this formatting similer to printf in "C" language.

==> in this style of formatting a string is defined with replacement fields. these

replacements fields are also called formatting specifiers.

conversion characters:

%d ==> decimal integer

%o ==> octal integer

%x ==>hexdecimal integer in lowecase

%X ==>hexdecimal integer in uppercase

%b ==>binary integer

%f ==> float value in fixed

%e ==> float value in expo

%c ==> single character

%s ==> string

%% ==>% character

# write a program to add two numbers

n1=int(input("enter first number"))

n2=int(input("enter second number"))

print("sum of %d and %d is %d"%(n1,n2,n1+n2))

35
eg:

a=65

b=0o12

c=0xab

print(a,b,c)

print("a=%d,b=%o,c=%x"%(a,b,c))

# write a program to find area of circle

r=float(input("Enter r"))

area=3.147*r*r

print("Area of circle is %f"%area)

print("Area of circle is %.2f"%area)

eg:

a=1.234567

print("%f"%a)

print("%.3f"%a)

print("%.2f"%a)

eg:

a=1.0

print("%f"%a) # default number of precisions are 6

print("%.2f"%a)

print("%.1f"%a)

eg:

a=12e1

print(a)

print("%e"%a)

eg:

x='A'

y='Python'

print("x=%s,y=%s"%(x,y))

36
n1=65

print("n1=%c"%n1) # use ascii value

print("n1=%s"%n1) # 65 is converted string

eg:

# write a program to read rollno,name,3 subject marks and display total,avg

rollno=int(input("Enter rollno"))

name=input("Enter name")

sub1=int(input("Enter sub1"))

sub2=int(input("Enter sub2"))

sub3=int(input("Enter sub3"))

total=sub1+sub2+sub3

avg=total/3

print("Rollno %d"%rollno)

print("Name %s"%name)

print("Sub1=%d,Sub2=%d,Sub3=%d"%(sub1,sub2,sub3))

print("Total %d"%total)

print("Avg %.2f"%avg)

new style string formatting using format function

=======================================

==> python 3 introduce format function.

==> in python3 formatting is done by calling format function.

04-06-2020
4/06/2020

new style string formatting using format function

=======================================

==> python 3 introduce format function.

37
==> in python3 formatting is done by calling format function.

syntax:

<string>.format(<positional arguments>/<keyword arguments>)

==> string contain replacement fields, these replacement fileds

are represented using {}. these fields are identified with its position or name.

eg:

a=10

b=20

c=a+b

print("sum of {} and {} is {}".format(a,b,c))

output:

sum of 10 and 20 is 30

eg: field identified with name

n1=10

n2=20

print("sum of {x},{y} is {z}".format(x=n1,y=n2,z=n1+n2))

output: sum of 10,20 is 30

eg: field identified with index. index/pos start with 0

n1=10

n2=20

print("sum of {},{} is {}".format(n2,n1,n1+n2))

print("sum of {1},{0} is {2}".format(n1,n2,n1+n2))

print("{2} is sum of {0},{1}".format(n1,n2,n1+n2))

eg:

# find output

print("{}{}{}{}{}{}".format(10,20,30,40,50,60))

print("{3}{0}{1}{2}".format(10,20,30,40))

print("{a}{b}{c}".format(b=100,a=200,c=300))

eg: # write a program to find are of rectangle

38
dim1=float(input("Enter dim1"))

dim2=float(input("Enter dim2"))

area=dim1*dim2

print("{area} is area rectangle with {dim1} and {dim2} dim".format

(dim1=dim1,dim2=dim2,area=area))

eg:

# using type characters with format

n=65

print("{:d},{:o},{:x},{:b}".format(n,n,n,n))

a=65

b=0o45

c=0xab

d=0b101

print("{:d},{:o},{:x},{:b}".format(a,b,c,d))

print("{1:d},{0:o},{2:b},{3:x}".format(b,a,d,c))

print("{p:d},{q:o},{r:x},{s:b}".format(p=a,q=b,r=c,s=d))

'''

d => decimal

o => octal

x => hexa decimal

b => binary

'''

# the type character is defined after :

# field is having format {<field-name>/pos:format}

# using type characters

# write a program to temp from celsius to fahernheit

# f=(c*9/5)+32

c=float(input("Enter temp is celsius"))

39
f=(c*9/5)+32

print("{} celsius= {} Fahernheit".format(c,f))

print("{:f} celsius ={:f} fahernheit".format(c,f))

print("{:.2f} celsius={:.2f} fahernheit".format(c,f))

print("{x:.2f} celsius={y:.2f} fahernherit".format(x=c,y=f))

#using f-fixed e-expo

x=1.5

y=1.5e-1

print("{}{}".format(x,y))

print("{:f},{:e}".format(x,y))

print("{:e},{:f}".format(x,y))

n1=10

n2=100

n3=1000

n4=10000

n5=100000

print(n1)

print(n2)

print(n3)

print(n4)

print(n5)

print("{:6d}".format(n1)) # default fill character is space

print("{:6d}".format(n2))

print("{:6d}".format(n3))

print("{:6d}".format(n4))

print("{:6d}".format(n5))

print("{:06d}".format(n1)) # 0 is fill character

print("{:06d}".format(n2))

print("{:06d}".format(n3))

40
print("{:06d}".format(n4))

print("{:06d}".format(n5))

==============================================

name1="Anshu"

name2="Prakash"

name3="Dell Inspiron"

name4="Nilesh"

print("{:12s}".format(name1))

print("{:12s}".format(name2))

print("{:12s}".format(name3))

print("{:12s}".format(name4))

print("{:>12s}".format(name1))

print("{:>12s}".format(name2))

print("{:>12s}".format(name3))

print("{:>12s}".format(name4))

print("{:^20s}".format(name1))

print("{:^20s}".format(name2))

print("{:^20s}".format(name3))

print("{:^20s}".format(name4))

# numbers are righ aligment

# string are left aligment

# aligment characters >,<,^

====================================================================

==> write a program/script to read length in cent and convert into

meters and kilometer

==> write a program to convert to days into years and weeks

==> write a program to find sqrt of given number

==> write a program to f-c

41
==> write a program to input to angles of triangle and find third angle

==> write a program find perimeter of rectangle

05-06-2020
5/06/2020

=========

f-string (OR) formatted string

========================

in python 3.6 version introduced format string. it is also called f-string.

f-string or formatted string is prefix with f.

print('python')

print(f'python')

==> each replacement field is reprepsented within {}

==> within {} we need to define variablename or expression.

eg:

a=100

b=200

print(f'{a},{b}')

x=1.5

y=2.5

print(f'{x},{y},{x+y}')

print(f'sum of {a} and {b} is {a+b}')

eg:

base=float(input("enter base"))

height=float(input("enter height"))

area=0.5*base*height

print(f'base={base},height={height},area={area}')

eg:

42
# f-string with type characters

a=65

b=0o16

c=0xab

d=0b1010

print(f'{a},{b},{c},{d}')

print(f'{a:d},{b:o},{c:x},{d:b}')

#---------------------------------------------------------------------

n1=1.5

n2=1.5e0

print(f'{n1},{n2}')

print(f'{n1:f},{n2:e}')

print(f'{n1:.2f},{n2:.2e}')

#----------------------------------------------------------------------

c1=1+2j

c2=3+4j

print(f'{c1},{c2}')

print(f'{c1.real},{c1.imag},{c2.real},{c2.imag}')

#-----------------------------------------------------------------------

s1="python"

s2="java"

print(f'{s1},{s2}')

print(f'{s1:10s}{s2:10s}')

#------------------------------------------------------------------------

a=40

b=450

c=5600

d=65000

print(f'{a:>10d}\n{b:>10d}\n{c:>10d}\n{d:>10d}')

43
#--------------------------------------------------------------------------

Operators

========

Q: What is operator?

==>operator is a special symbol which is used to perform some operations.

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

5. Bitwise Operators

6. Identity Operators

7. Membership Operators

8. Conditional Operators

Binary Operators ==> required two operands

Unary Operators ==> required one operand

Ternary Operators ==> required 3 operands

Arithmetic Operators

=================

==> arithmetic operators are binary operators, which required two operands.

+ ==> binary addition

- ==> binary subtraction

* ==> binary multiplication

/ ==> binary float division

// ==> binary floor division

% ==>binary modulas

** ==>binary expo or power of operator

=============================================================

# in python + operator is used to add two numbers and

# concat two sequences(string,list,tuple,...)

44
r1=10+20

r2=1.5+1.2

r3=(1+2j)+(1+3j)

r4="python"+"language"

r5=True+True # True ==>1 False==>0

r6=False+False

r7=True+False

r8=False+True

print(r1,r2,r3,r4,r5,r6,r7,r8)

# implict(automatic) type casting or conversion

# always result is converted into broader type

# int,float,complex

# complex>float>int

r9=10+1.5

r10=5+(2+4j)

print(r9,r10)

r11=1+2.5+(1+2j)

print(r11)

# explicit(done by programmer) using conversion functions

r12=int(10+1.5)

print(r12)

r13=float(10+20)

print(r13)

r14=int(1+2j) # error

print(r14)

=====================================================================

# Find Output

x=10+"python" # error

45
print(x)

===========================================================

x=str(10)+"python"

print(x)

# str() is used to convert into string

=============================================================

# binary - operator is used for subtracting numbers

r1=20-10

r2=1.5-0.05

r3=(3+2j)-(2+1j)

print(r1,r2,r3)

''' s1="java"

s2="python"

s3=s1-s2 ''' # this is not allowed

=============================================================

# binary * operator is used to multiply two numbers and

# to repeate a sequence(string,list,..) number of times

r1=5*2

r2=1.5*2.5

r3=(1+2j)*(2+3j)

print(r1,r2,r3)

s1="python"*2

print(s1)

line="*"*50

print(line)

06-06-2020
6/6/2020

========

46
python provide 3 division operators:

/ ==> binary float division

// ==> binary floor division

% ==>binary modulas

eg:

r1=10/2

r2=5/2

print(r1,r2)

print(type(r1),type(r2))

# / return result as float type

r3=10.0/2.0

r4=5.0/2.0

print(r3,r4)

'''

int/int ==> float

float/float ==> float

int/float ==> float

float/int ==> float

'''

===============================================================

# % modulas operator, this operator return remainder

47
num1=int(input("Enter numerator"))

num2=int(input("Enter denominator"))

rem=num1%num2

print(f'num1={num1},num2={num2},rem={rem}')

===================================================================

start=int(input("start reading"))

end=int(input("end reading"))

units=end-start

day=units//30

print(start,end,units,day)

'''

int//int ==> int

float//int ==> int ==> float

int//float ==> int ==> float

float//float ==> int ==> float

5//2 ==> 2

5//2.0 ==> 2 ==> 2.0

'''

===============================================================

# // integer division or floor division

r1=10//2

r2=5//2

print(r1,r2)

48
print(type(r1),type(r2))

r3=10.0//2 # return result into integer type, convert that integer result into float

r4=5//2.0

print(r3,r4)

print(type(r3),type(r4))

r5=10.0//2.0

print(r5)

r6=5.0//2.0

print(r6)

====================================================================

# ** expo operator or power of operator

res=10**2

print(res)

n=int(input("enter n value"))

p=int(input("enter p value"))

print(f'{n},{p},{n**p}')

==================================================================

Relational Operators

==> Relational operators are used to find relationship between to operands or values.

==> Relational operators are binary operators, it required two operands.

==> Relational operators are used for comparing values.

==> These operators return boolean value(True/False)

> ==> greater than

< ==> less than

49
>= ==> greaterthan or equal

<= ==> lessthan or equal

!= ==> not equal

== ==> equality operator

================================================================

# relational operators are used to compare strings also

str1="a" #97

str2="A" #65

b1=str1>str2 # True

print(b1)

str3="ab" # 97 98

str4="ba" # 98

b2=str3>str4

print(b2)

str5="abc" # 97 98 99

str6="abd" # 97 98 100

b3=str5>str6

print(b3)

str7="ab" # 97 98

str8="abc" # 97 98 100

b4=str7>str8

print(b4)

str9="ab"

str10="ab"

b5=str9==str10

print(b5)

str11="abc" # 97 98 99

str12="ab" # 97 98

50
b6=str11>str12

print(b6)

=====================================================================

r1=100>50 # True

r2=50>100 # False

r3=100<50 # False

r4=50<100 # True

print(r1,r2,r3,r4)

r5=100>=50 # True

r6=50>=50 # True

r7=50>50 # False

r8=49<=50 # True

r9=49<50 # True

print(r5,r6,r7,r8,r9)

r10=10==10

print(r10) # True

r11=10==11 # False

print(r11)

r12=10!=10 # False

print(r12)

r13=10!=11 # True

print(r13)

====================================================================

Logical operators

===============

==> logical operators are used to combine two boolean expressions.

==> An expression which return boolean value, is called boolean expression.

1. and

2. or

51
3. not

Truth table of and operator

======================

opr1 opr2 opr1 and opr2

True False False

False True False

True True True

False False False

Truth table of or operator

====================

opr1 opr2 opr1 or opr2

True False True

False True True

True True True

False False False

Truth table of not operator

=====================

orp1 not opr1

True False

False True

08-06-2020
08/06/2020

==========

eg:

res1=True and True

res2=True and False

res3=False and True

res4=False and False

52
print(res1,res2,res3,res4)

res5=True or True

res6=True or False

res7=False or True

res8=False or False

print(res5,res6,res7,res8)

res9=10>5 and 10>7

print(res9)

res10=10>5 and 10>20

print(res10)

assignment operators or updation operators

====================================

+= ==> a=5 ==> a=a+5 (OR) a+=5

-= ==> a=10 ==> a=a-2 (OR) a-=2

*= ==> a=20 ==> a=a*2 (OR) a*=2

/= ==> a=10 ==> a=a/2 (OR) a/=2

//= ==> a=5 ==> a=a//2 (OR) a//=2

%= ==> a=30 ==> a=a%5 (OR) a%=5

>>=

<<=

**= ==> a=5 ==> a=a**2 (OR) a**=2

==> compound assignment, this assignment operator allows arithmetic and

assignment.

num1=5

num1+=10

print(num1)

num2=15

num2-=5

print(num2)

53
num3=20

num3*=2

print(num3)

num4=30

num4/=3

print(num4)

num5=40

num5//=4

print(num4)

num6=5

num6**=2

print(num6)

=========================================================

# find output

n1=5

n2=6

n1+=n2 # n1=n1+n2

print(n1) # 11

print(n2) #

#======================================

x=5

y=3

x**=y

print(x)

print(y)

#========================================

bitwise operators

==============

==> bitwise operators are used to perform operations in the form of bits.

54
1. >> : Rightshift operator

2. << : Leftshift operator

3. & : Bitwise and operator

4. | : Bitwise or operator

5. ^ : Bitwise XOR operator

6. ~ : Bitwise not operator

1. bitwise rightshift operator >>

==> this operator is used to shift number of bits towards rightside.

==> It is binary operator it required two operands.

value>>n

==> shift n bits towards rightside.

n1=10

n1=n1+2 ==> 12

x=20

x=x-5 ==> 15

5 ==> 0101 ==> 5>>1

0010 ==> 2

==> >> operator is used to decrement value by removing n bits.

eg:

n=20

print(n)

print(bin(n)) # bin() function return binary value of 20

n=n>>2

print(bin(n))

print(n)

x=456

print(x)

print(bin(x))

x=x>>3

55
print(x)

print(bin(x))

# formula ==> value//2 pow n

'''

value=20

value>>2 ==> 20//4 ==> 5

'''

Leftshift operator <<

=================

==>Leftshift operator is used to move number bits towards leftside.

==>This operator allow to add bits. By adding bits the value get incremented.

value<<n

eg:

value=10 # 1010

print(value)

value=value<<2 # 101000

print(value)

formula ==> value*2 pow n

10*2 pow 2 ==> 10*4=40

Bitwise & operator

===============

==> truth table of bitwise & operator

opr1 opr2 opr1&opr2

0 1 0

1 0 0

1 1 1

0 0 0

Bitwise | operators

==================

56
==> truth table of bitwise | operator

opr1 opr2 opr1 | opr2

0 1 1

1 0 1

1 1 1

0 0 0

Bitwise ^ operator

===============

==> tuth table of bitwise ^ operator

opr1 opr2 opr1^opr2

0 0 0

0 1 1

1 0 1

1 1 0

# swapping two numbers

num1=100

num2=200

# swapping tw0 number using third variable

num3=num1

num1=num2

num2=num3

print(num1,num2)

# swapping two numbers without using third variable

x=100

y=200

x,y=y,x

print(x,y)

# swapping two numbers without using thrid variable

m=100

57
n=200

m=m+n

n=m-n

m=m-n

print(m,n)

# swapping two numbers without using third variable

a=100

b=200

a=a^b

b=a^b

a=a^b

print(a,b)

conditional operator

=================

==> this operator required 3 operands.

==> It is a ternary operator.

<opr2> if <opr1> else <opr3>

==> if opr1 return True, it eval opr2

==> if opr1 return Flase, it eval opr3

==> it is used to evel simple logical expressions or conditions.

# write a program/script to find max of two numbers

n1=int(input("eneter first number"))

n2=int(input("enter second number"))

n3=n1 if n1>n2 else n2

print(n1,n2,n3)

# write a program/script to find input character is vowel or not

ch=input("enter any character")

print("vowel") if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' else print("not

vowel")

58
print("vowel") if ch in "aeiouAEIOU" else print("not vowel")

==============================================================

# login application

print("*******Login Application **********")

user=input("****UserName :")

pwd=input("**** Password :")

print("**WELCOME ****") if user=='nit' and pwd=='nit123' else print("Invalid username

or password")

============================================================

membership operators

===================

==> membership operators are used to to compare one value with group of values.

1.in

2.not in

'a' in 'abcdefg' ==> True

==> membership operators return boolean value True/False.

"charan" in ("rama","vamsee","anshu","charan") ==> True

Identity operators

===============

==> identity operators are used to compare identity/id, which is called address

is

is not

a=100

b=100

c=a is b

print(a,b,c) ==> 100 100 True

09-06-2020
09/06/2020

59
=========

Operator precedence:

==================

from lowest precedence (least binding) to highest precedence (most binding).

Operators in the same box have the same precedence. Unless the syntax is explicitly

given, operators are binary. Operators in the same box group left to right (except for

exponentiation, which groups from right to left).

lambda Lambda expression

if – else Conditional expression

or Boolean OR

and Boolean AND

not x Boolean NOT

in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests

and identity tests

| Bitwise OR

^ Bitwise XOR

& Bitwise AND

<<, >> Shifts

+, - Addition and subtraction

*, @, /, //, % Multiplication, matrix multiplication, division, floor

division, remainder

+x, -x, ~x Positive, negative, bitwise NOT

** Exponentiation

await x Await expression

x[index], x[index:index], x(arguments...), x.attribute

Subscription, slicing, call, attribute reference

(expressions...), [expressions...], {key: value...}, {expressions...}

60
Binding or tuple display, list display, dictionary display,

set display.

control structures

===============

==> control structures are used to control the flow of execution of program.

==> control structures are two types.

1. conditional statements

2. looping statement/iterative statement

condtional statement

=================

==> python support only one conditional statement.

==> it support if statement.

==>if is a conditional statement, which is used to execute

block of statements based on given condition.

1. simple if

2. if..else

3. if..elif..else (if..else ladder)

4. nested if

simple if

=======

==> if without else is called simple if.

syntax:

if <condition>:

statement-1

statement-2

statement-3

==> if condition is True,it execute statement-1,statement-2 and statement-3

==> if condition is False, it execute statement-3

==> a block cannot defined without any statements.

61
eg:

if True:

error becoz there are statements within if block

eg:

if True:

print("Java")

print("Python")

Eror: required indeneted block

eg:

if False:

print("Hello")

print("Bye")

if..else

======

==> this syntax provide two blocks 1. if block 2.else

syntax:

if <condition>:

statement-1

statement-2

else:

statement-3

statement-4

statement-5

==> if condition is True,it execute statement-1,statement2 and statement-5

==> if conidtion is False,it execute statement-3,statement4 and statement5

==> if condition is True, it execute if block

==> if condition is False, it execute else block

# write a program to find given input number is even or odd

num=int(input("Enter any number"))

62
r=num%2

if r==0:

print(f'{num} is even')

else:

print(f'{num} is odd')

# write a program to input name,3 subjects marks and find result

name=input("Enter name")

s1=int(input("Enter subject1 marks"))

s2=int(input("Enter subject2 marks"))

s3=int(input("Enter subject3 marks"))

print(f'Name is {name}')

if s1<40 or s2<40 or s3<40:

print("Fail")

else:

print("Pass")

# write a program to find given year is leap or not

year=int(input("enter year"))

if year%4==0 or year%400==0:

print(f'{year} is leap')

else:

print(f'{year} is not leap')

# write a program to find input character is vowel or not

ch=input("Enter any character")

if ch in "aeiouAEIOU":

print(f'{ch} is vowel')

else:

print(f'{ch} is not vowel')

if..elif..else (if..else..ladder)

=======================

63
==> This syntax allows check multiple conditions.

if <condition1>:

statement-1

elif <condition2>:

statement-2

elif <condition3>:

statement-3

..

else:

statement-4

statement-5

10-06-2020
10/06/2020

===========

if..elif..else (if..else..ladder)

=======================

==> This syntax allows check multiple conditions.

if <condition1>:

statement-1

elif <condition2>:

statement-2

elif <condition3>:

statement-3

..

else:

statement-4

statement-5

==> if condition1 is True, it execute statement-1 and statement-5

64
==> if condition1 is False and condition2 True, it execute statement-2 and statement-5

==> if condition1,condition2 are False and condition3 is True, it execute statement-3

and statement-5.

==> if condition1,condition2,condition3 are false, it execute statement-4 and

statement-5.

# write a program to find max of three numbers

n1=int(input("enter first number"))

n2=int(input("enter second number"))

n3=int(input("enter third number"))

if n1>n2 and n1>n3:

print(f'{n1} is max')

elif n2>n1 and n2>n3:

print(f'{n2} is max')

elif n3>n1 and n3>n2:

print(f'{n3} is max')

else:

print(f'{n1},{n2},{n3} are equal')

========================================================

# write a program or script to find input character is alphabet,digit or special

character

ch=input("enter any character") # a ==> 97 # 1 ==>47

if (ch>='A'and ch<='Z') or (ch>='a' and ch<='z'):

print(f'{ch} is alphabet')

elif ch>='0' and ch<='9':

print(f'{ch} is digit')

else:

print(f'{ch} is special character')

===================================================================

ord

65
===

ord(c, /)

Return the Unicode code point for a one-character string.

This function is exists in builtins module

ord('A') ==> 65

ord('B') ==> 66

ord('a') ==> 97

# write a script to find ascii value of given character

ch=input("enter any character")

value=ord(ch)

print(f'{ch}={value}')

=================================================================

chr

===

chr(i, /)

Return a Unicode string of one character with ordinal i

chr(65) ==> A

chr(66) ==> B

chr(97) ==> a

# write a script/program to find character of given ascii value

value=int(input("enter ascii value"))

ch=chr(value)

print(f'{value}={ch}')

=================================================================

# write a program to convert input alphabet into uppercase or lowercase

ch=input("enter any character") # A ==> 65 +32 ==> 97 ==> a

if ch>='A' and ch<='Z':

value=ord(ch)

value=value+32

66
ch=chr(value)

print(f'{ch}')

elif ch>='a' and ch<='z': # a==> 97 -32 ==> 65 ==> A

value=ord(ch)

value=value-32

ch=chr(value)

print(f'{ch}')

else:

print("invalid input (OR) input must be alphabets")

================================================================

# write a program to find input number is +ve or -ve or zero

num=int(input("enter any number"))

if num>0:

print(f'{num} is +ve')

elif num<0:

print(f'{num} is -ve')

else:

print("zero")

===============================================================

nested if

=======

if within if (OR) if inside if is called nested if.

syntax:

if condition1:

if condition2:

statement-1

else:

statement-2

else:

67
statement-3

statement-4

==> if condition-1 is True,condition2 is True it execute statement-1 and statement-4

==> if condition1 is True, condition2 is False it execute statement-2 and statement-4

==> if condition1 is false, it execute statement-3 and statement-4

=====================================================================

# login program

user=input("UserName :")

pwd=input("Password :")

if user=='nit':

if pwd=='nit123':

print("Welcome to My Application")

else:

print("Invalid password")

else:

print("Invalid username")

====================================================================

# banking logic/transactions

accno=int(input("enter accno"))

cname=input("enter customer name")

balance=float(input("enter balance"))

ttype=input("enter transaction type(d/w)")

if ttype=='d':

amt=float(input("enter amount"))

balance=balance+amt

print("Deposit done")

elif ttype=='w':

amt=float(input("enter amount"))

if amt>balance:

68
print("Insuff balance")

else:

balance=balance-amt

print("Withdraw done")

else:

print("invalid transaction type")

print(f'AccountNo {accno}')

print(f'CustomerName {cname}')

print(f'Balance {balance}')

====================================================================

1. write a program to input 3 numbers and find 2 maximum numbers.

2. write a program to input 3 numbers and find 2 minimum numbers

3. write a program to input rno,name 3 subject marks and find grade.

4. write a program to find comm of a sales person

saleamount>10000 ==> 10%

saleamount>5000<10000 == > 5%

salesamount<=5000 ==> 2%

looping statements (OR) iterative statements

=====================================

==> iterative statements or looping statements are used repeate one or more than one

statement number of times or until given condition.

==> python support 2 types of loop statements.

1. while

2. for

11-06-2020

11/06/2020

69
==========

looping statements (OR) iterative statements

=====================================

==> iterative statements or looping statements are used repeat one or more than one

statement number of times or until given condition.

==> python support 2 types of loop statements.

1. while

2. for

while loop

====

==> while is a keyword or is looping statement.

==> it allows to repeat one or more than one statement number of times or until given

condition.

syntax-1:

while <condition>:

statement-1

statement-2

==> statement-1 and statement-2 is repeated until condition is True, if condition is

False stop executing loop.

syntax-2:

while <condition>:

statement-1

statement-2

else:

statement-3

statement-4

70
==> statement-1 and statement-2 is repeated until condition is True, if condition is

False it execute else block and stop.

==> in order to work while we required 3 statements.

1. init statement

2. condition

3. updating

==> init statement, which init value of condition.

==> condition, it is a boolean expression which define how many times loop has to

executed.

==> Updation statement, it is statement which update condition.

*************************************************************************************
****

i=1

while i<=5:

print("naresh")

i=i+1

*************************************************************************************
****

while False:

print("NIT")

# no output

*************************************************************************************
***

while True:

print("NARESH")

print("PYTHON")

=================================================================

while 100: # other than 0 any value is True

print("PYTHON")

==================================================================

71
# write a program/script to print alphabets from A-Z,a-z

n=65

while n<=90:

print(chr(n),end=' ')

n=n+1

print()

n=97

while n<=122:

print(chr(n),end=' ')

n=n+1

=================================================================

# write a program/script to print 65-90 without using number

ch='A'

while ch<='Z':

print(ord(ch),end=' ')

n=ord(ch)+1

ch=chr(n)

==============================================================

# write a program/script to print math table of input number

num=int(input("Enter any number")) # 5

i=1

while i<=10:

print(f'{num}x{i}={num*i}')

i=i+1

=====================================================================

# write a program to find given number is prime or not

num=int(input("enter any number"))

i=1

c=0

72
while i<=num:

r=num%i

if r==0:

c=c+1

i=i+1

if c==2:

print(f'{num} is prime')

else:

print(f'{num} is not prime')

====================================================================

# write a program to count how many digits exist in number

num=int(input("enter any number"))

c=0

if num==0:

c=1

else:

num=abs(num)

while num!=0:

num=num//10

c=c+1

print("count of digits",c)

==============================================================

1. write a program to print 1 to n numbers

2. write a program to print n even numbers

3. write a program to print n odd numbers

4. write a program to print sum of the following series

1+2+3+4+.......+n

5. write a program to print sum of the following series

1**2+2**2+3**2+..... +n**2

73
12-06-2020
12/6/2020

=========================================================

# 1. write a program to print 1 to n numbers

num=1

n=int(input("enter n value"))

while num<=n:

print(num)

num+=1

===========================================================

# 2. write a program to print n even numbers

num=1

n=int(input("enter the value of n")) # 5

while num<=n:

if num%2==0: # 1%2 2%2 3%2 4%2 5%2

print(num) # 2 4

num+=1 # 2 3 4 5 6

=======================================================

# 3. write a program to print n ODD numbers

num=1

n=int(input("enter the value of n")) # 5

while num<=n:

if num%2!=0: # 1%2 2%2 3%2 4%2 5%2

print(num) # 1 3 5

num+=1 # 2 3 4 5 6

===========================================================

# 4. write a program to print sum of the following series

# 1+2+3+4+.......+n

74
num=1

n=int(input("enter n value"))

s=0

while num<=n:

s=s+num

num=num+1

print(f'sum of 1 to {n} value is {s}')

========================================================

#5.

num=1

n=int(input("enter n value"))

s=0

while num<=n:

s=s+(num**2)

num=num+1

print(f'sum of 1 to {n} value is {s}')

=============================================================

# write a program to print sum of digits

num=123 ==> 1+2+3==> 6

num=476 ==> 4+7+6 ==> 17

// ==> floor division/integer division

% ==> modulas

476%10=6==>

476//10=>47

47%10 ==> 7

47//10 ==> 4

4%10 ==> 4

4//10 ==> 0

num=int(input("Enter any number"))

75
sum=0

while num!=0:

r=num%10

sum=sum+r

num=num//10

print(f'sum of digits {sum}')

==============================================================

# write a program to reverse number

123 ==> 321

//

rev=0

r=123%10=3

rev=(rev*10)+r==> 3

123//10 ==> 12

r=12%10 ==> 2

rev=(rev*10)+r ==> 32

12//10 ==> 1

r=1%10 ==> 1

rev=(rev*10)+r ==>321

num=int(input("enter any number"))

rev=0

while num!=0:

r=num%10

rev=(rev*10)+r

num=num//10

print(rev)

==================================================================

# write a program to find input number is palindrome or not

76
121 ==> 121 ==> pal

123 ==> 321 ==> not pal

num=int(input("enter any number"))

num1=num

rev=0

while num!=0:

r=num%10

rev=(rev*10)+r

num=num//10

if rev==num1:

print(f'{num1} is pal')

else:

print(f'{num1} is not pal')

=================================================================

for loop

=======

==> The for statement in Python differs a bit from what you may be used to in C or

Pascal.

==> Rather than always iterating over an arithmetic progression of numbers (like in

Pascal), or giving the user the ability to define both the iteration step and halting

condition (as C), Python’s for statement iterates over the items of any sequence (a list

or a string), in the order that they appear in the sequence.

syntax-1:

for variable in iterable/sequence:

statement-1

statement-2

==> for loop/statement it read each one value/object from iterable/collection/sequence

and execute statement-1,statement-2

==> it repeate this until all the objects read from collection/sequence.

77
syntax-2:

for variable in iterable/sequence:

statement-1

statement-2

else:

statement-3

statement-4

===================================================================

str1="PYTHON" # string is a collection of characters or sequence

for ch in str1:

print(ch)

=====================================================================

# write a program to count how many vowel are their in string

str1=input("Enter any string")

count=0

for ch in str1:

if ch in "aeiouAEIOU":

count+=1

print("count of vowels ",count)

==============================================================

#write a program to convert string into uppercase

str1=input("enter any string")

str2=''

for ch in str1:

if ch>='a' and ch<='z':

o=ord(ch)-32

str2=str2+chr(o)

else:

str2=str2+ch

78
print(str1)

print(str2)

================================================================

# write a program to find how many alphabets,digits and special characters exists

within input string.

abc123 ==> 3 3

ab123* ==> 2 3 1

str1=input("enter any string")

acount=0

dcount=0

scount=0

for ch in str1:

if ch>='a' and ch<='z' or ch>='A' and ch<='Z':

acount+=1

elif ch>='0' and ch<='9':

dcount+=1

else:

scount+=1

print("alphabets count ",acount)

print("digit count ",dcount)

print("special character count ",scount)

====================================================================

# write a program to convert string into lowercase

# write a program to count number words in a given string

# write a program to convert first character of string in uppercase

# write a program to count a given character is repeated how many times in given string

79
13-06-2020
13/06/2020

===========

# write a script to print u r name 5 times using for loop

i=1

while i<=5:

print("Prakash")

i+=1

range()

======

==> range is a sequence datatype.

==> The range type represents an immutable sequence of numbers and is commonly

used for looping a specific number of times in for loops.

1. range(stop)

2. range(start,stop,step)

==> start,stop,step values must be integer type.

==> step is increment or decrement value, the default step is +1

==> step should should not be zero,it raises ValueError.

r=range(5) # ==> range object

print(r)

for value in r: # 0 1 2 3 4

print(value)

==========================

# find output

r=range(-5)

for value in r:

print(value)

# No output

80
# if step is +ve, the start value must be less than stop value

# if step is -ve, the start value must be greater than stop value

# default step +1

=============================================

r1=range(1,5) # start=1 stop=5 step=1 ==> 1 2 3 4

r2=range(-5,-1) # start=-5 stop=-1 step=1 ==> -5 -4 -3 -2

r3=range(5,1,-1) # start=5 stop=1 step=-1 ==> 5 4 3 2

r4=range(-1,-5,-1) # start=-1 stop=-5 step=-1 ==> -1 -2 -3 -4

for value in r1:

print(value)

print("*******************")

for value in r2:

print(value)

print("*******************")

for value in r3:

print(value)

print("*******************")

for value in r4:

print(value)

================================================

# script to generate even and odd numbers

for value in range(0,21,2): # start=0 stop=21 step=+2

print(value,end=" ")

print()

for value in range(1,21,2): # start=1 stop=21 step=+2

print(value,end=" ")

print()

===================================================

# write script/program to generate alphabets from A-Z and a-z

81
for value in range(65,91):

print(value,"=",chr(value))

for value in range(97,123):

print(value,"=",chr(value))

===============================================

# write a program to find given number is prime or not

num=int(input("enter any number"))

c=0

for i in range(1,num+1):

if num%i==0:

c+=1

if c==2:

print(f'{num} is prime')

else:

print(f'{num} is not prime')

================================================

# write a program to find factorial of given number

# num=4 ==> 1*2*3*4 => 24

num=int(input("enter any number")) # 4

fact=1

for value in range(1,num+1):

fact=fact*value

print("Factorial is ",fact)

# strong number ==> sum of factorail of digits == num

# 145 ==> 1!+4!+5! == 145

=================================================

15-06-2020
15/06/2020

82
----------

nested loops

==========

==> loop within a loop is called nested loop.

==> this nested loop can be,

1.nested for

2.nested while

nested for loop

============

==> for loop inside for loop is called nested for.

syntax:

for variable in iterable:

for variable in iterable:

statement-1

statement-2

statement-3

=====================================================

for x in range(5):

for y in range(1,6): # 1 2 3 4 5

print(y,end=' ')

print()

=====================================================

# write a program to print math tables from 1-10

for num in range(1,11): # 1 2 3 4 5 6 7 8 9 10

for i in range(1,11): # 1 2 3 4 5 6 7 8 9 10

print(f'{num}*{i}={num*i}')

======================================================

# write a program to print prime numbers between 1-n

n=int(input("enter the value of n"))

83
for num in range(1,n+1): # 5 6

count=0

for i in range(1,num+1): # 1 2 3 4 5 6

if num%i==0:

count+=1

if count==2:

print(num,end=' ')

=========================================================

for i in range(1,6): #1 2 3 4 5

for j in range(1,6):

print(i,end=' ')

print()

=========================================================

for i in range(1,6): # 1 2 3 4 5

for j in range(1,i+1):

print(i,end=' ')

print()

=========================================================

for i in range(5,0,-1): #5 4 3 2 1

for j in range(1,6):

print(i,end=' ')

print()

==========================================================

for i in range(5,0,-1): #5 4 3 2 1

for j in range(1,i+1):

print(i,end=' ')

print()

=========================================================

for i in range(5,0,-1):

84
for j in range(1,i+1):

print(j,end=' ')

print()

==========================================================

for i in range(1,6):

for j in range(1,i+1):

print(j,end=' ')

print()

==========================================================

for i in range(1,6):

for j in range(5,0,-1):

if i>=j:

print(j,end=' ')

else:

print(' ',end=' ')

print()

=====================================================

16-06-2020
16/06/2020

=========

======================================================

for i in range(1,6):

for j in range(1,6):

if i<=j:

print(j,end=' ')

else:

print(" ",end=" ")

print()

85
===========================================================

for i in range(1,6):

for j in range(1,6):

if i<=j:

print(j,end=' ')

else:

print(" ",end=" ")

print()

=========================================================

for i in range(5,0,-1):

for j in range(5,0,-1):

if i>=j:

print(j,end=' ')

else:

print(' ',end=' ')

print()

=========================================================

for i in range(5,0,-1):

for j in range(1,6):

if i<=j:

print(j,end=' ')

else:

print(' ',end=' ')

print()

============================================================

k=1

for i in range(1,6):

for j in range(1,6):

if j<=i:

86
print(k,end=' ')

k+=1

print()

=============================================================

for row in range(7):

for col in range(5):

if ((col==0 or col==4) and row!=0) or (row==0 or row==3) and (col<4 and col>0):

print("*",end=' ')

else:

print(" ",end=' ')

print()

==================================================================

for row in range(7):

for col in range(5):

if (col==0) or (row==0 or row==3 or row==6)and (col>0 and col<4)or (col==4) and

(row>0 and row<6) and row!=3 :

print("*",end=' ')

else:

print(" ",end=' ')

print()

==================================================================

nested while

===========

==> while loop inside while loop is called nested while.

syntax:

while <condition>: # outer loop

statement-1

statement-2

while <condition>: # inner loop

87
statement-3

statement-4

17-06-2020
17/06/2020

==========

nested while

===========

==> while loop inside while loop is called nested while.

syntax:

while <condition>: # outer loop

statement-1

statement-2

while <condition>: # inner loop

statement-3

statement-4

=================================================================

# this program or script is used to print tables from 1 to 10

num=1

while num<=10:

i=1

while i<=10:

print(f'{num*i:4d}',end='')

i+=1

print()

num+=1

=================================================================

# write a program to find given number is strong number or not

88
# 145

# 1!+4!+5!=145

num=int(input("enter any number")) # 12

org=num #12

sum_fact=0

while num!=0:

d=num%10 # 12%10 ==> 2 ==> 1%10 ==> 1

fact=1

while d>0:

fact=fact*d #2*1=2 # 1*1 ==>1

d=d-1

sum_fact=sum_fact+fact # 2+1=3

num=num//10 # 12//10 ==> 1//10 ==>0

if sum_fact==org:

print("Strong Number")

else:

print("Not Strong Number")

==================================================================

break statement

==============

==> break is called as passes control statement.

==> this statement or keyword is used to terminate execution of current loop.

==> break statement is used inside for or while loop.

pass statement

=============

==> pass is a keyword.

==> this keyword represent null operation.

==> according to python syntax a block required one statement.

==> inorder to write a block without doing any operation we include pass statement.

89
eg:

i=1

while i>10:

print(i)

Note: empty blocks are not allowed.

eg:

i=1

while i<=10:

pass

eg:

i=1

while i<=10:

break

===========================================================

# find output

i=1

while i<=10:

pass

print("Hello")

i=i+1

=========================================================

# wap to find given number is prime or not

#8

# 8%1 8%2 8%3 8%4 ....... 8%8

num=int(input("enter any number"))

i=1

c=0

while i<=num:

if num%i==0:

90
c+=1

if c>2:

break

i+=1

if c>2:

print(f'{num} is not prime')

else:

print(f'{num} is prime')

===============================================================

while True:

print("1. Python")

print("2. Java")

print("3. C")

print("4. C++")

print("5. Exit")

opt=int(input("Enter your option"))

if opt==1:

print("Python Fee :4000")

elif opt==2:

print("Java Fee :3000")

elif opt==3:

print("C Fee :2000")

elif opt==4:

print("c++ Fee : 2500")

elif opt==5:

break

==================================================================

continue

=======

91
==> continue is a passes control statement.

==> the statement moves to begining of the loop (OR) continue current loop

19-06-2020
18&19/06/2020

=============

continue

=======

==> continue is a passes control statement.

==> the statement moves to begining of the loop (OR) continue current loop.

==============================================================

How to Debug in IDLE?

===================

==> IDLE is a default ide provided by python.

Q: what is bug?

==> A bug is an unexpected problem with in program.

==> debug is finding problem.

Inorder to make debug mode on

goto debug==> Debugger

==> in this you inspect values of variables.

==> Go : Press this option advace execution to the next break point.

==> Step : press this option to execute the current line and goto nextline

==> Over : If the current line is having function call, then press this option to step over

the function(execute the function and goto next line)

==> Out: I thr current line having function call continue execution of this function until

it return some value.

Break point

=========

==> Breakpoint is a line of code that you want to identify/verify .

92
==> when break point is set, the interpreter pause on this line

==> to set the breakpoint click right mouse button select breakpoint.

=====================================================================

# using continue inside for loop

for num in range(1,11): # 1 2 3 4 5 6 7 8 9 10

if num%2==0:

continue

print(num) # 1 3 5 7 9

num=1

while num<=10:

if num%2!=0:

num+=1

continue

print(num)

num+=1

==================================================================

Python Collections (OR) Data Structures

=================================

Q: Why we required collection types?

==> we required collections for storing data or objects.

==> collections are container which contain more than one value.

==> collection it self is an object which is grouping with more than one object.

==> by grouping the data we can perform some aggreate operations.

==> every collection is one data structure.

==> data sturucture define set of rules and reg for organizing data.

==> collection can hold data of similer type of different types.

==> python collections are classified into types.

1. Sequence types

2. NonSequence types

93
==> sequence types are : list,tuple,str,range,bytes,byte_array

==> non sequence types are : set,frozenset,dict

==> all collections types are iterables.

==> iterables which contain more than one value or item.

==> iterables which allows to iterate/read more than one value or item.

==> iterables which allows to read data using iteration protocol.

==> iterables which allows to read data using iterator object.

sequence type

============

Q: What is sequence?

==> sequence types are ordered collections.

==> in ordered collections preserve insertion order.

==> sequences are index based collections, where reading and

writing is done using index.

==> index based allows to read and write in seq or random order.

list

===

==> list is used to store hetrogenious data(different types of data).

==> list is a index based collection or data structure.

==> list allows duplicate objects or elements or items.

==> in application development if program wants to store hetrogenious,homogenious

data where duplicate are allowed then we use list collection.

==> list is dynamic in size.(all data structure are dynamic in size).

==> list is a iterable.

==> list is datatype/class.

==> list is a mutable collection(after creating list we can do changes)

How to create list?

1. without type.

==> list object can be created using,

94
[] ==> empty list

[item,item,item,item,..] ==>list with values/items

2. with type

==>list object can be created using list(), this is used to

convert other iterables types to list.

list() ==> empty list

list(iterable) ==> creating list using existing iterable

eg:

===

l1=[]

l2=list()

print(type(l1))

print(type(l2))

eg:

===

l1=[10,20,30,40,50] # homogenious

l2=[10,1.5,1+2j,True,'python'] # hetrogenious

print(l1)

print(l2)

l3=[]

l4=list()

print(l3)

print(l4)

==> each item/value in list is identified with index.

==> this index can be +ve or -ve. +ve index start 0 and -ve index start at -1.

==> this index is used to read data from left to right or right to left.

20-06-2020
20/06/2020

95
==========

How to read data or items from list?

1. using index

2. iterator

3. for loop

4. slicing

5. using methods of list

Using index

==========

Q: What is index?

==> index is an integer value which is used to identify each value or location within list.

==> this is a logical value.

==> index allows to read data in seq and random order.

==> index can be +ve or -ve.

==> +ve index starts at 0 and -ve index starts at -1

==> +ve index is used to read valueseg from left to right.

==> -ve index is used to read values from right to left

syntax:

list-name[index]

==> if index is invalid python raises IndexError.

eg :

# index==> 0 1 2 3

student_info=[101,'naresh','python',5000.0]

# index=> -4 -3 -2 -1

print(student_info[0])

print(student_info[1])

print(student_info[2])

print(student_info[3])

print(student_info[-1])

96
print(student_info[-2])

print(student_info[-3])

print(student_info[-4])

Eg:

# reading values using index

# 0 1 2 3 45 6 7 8 9

list1=[10,20,30,40,50,60,70,80,90,100]

# -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

# reading values from left to right using +ve index

for index in range(0,len(list1)): # 0 1 2 3 4 5 6 7 8 9

print(list1[index],end=' ')

# reading value from right to left using -ve index

print()

for index in range(-1,-(len(list1)+1),-1):

print(list1[index],end=' ')

print()

# reading values from right to left using +ve

for index in range(len(list1)-1,-1,-1):

print(list1[index],end=' ')

print()

# reading values from left to right using -ve

for index in range(-len(list1),0):

print(list1[index],end=' ')

======================================================================

product_list=['keyboard','mouse','monitor','disk']

print(product_list)

index=int(input("Enter product index(0-3)"))

if index<4:

if index==0:

97
print("Keyboard price 1000")

elif index==1:

print("Mouse price 200")

elif index==2:

print("Monitor price 5000")

elif index==3:

print("Disk Price 4000")

else:

print("invalid index")

===================================================================

course_list=['python','java','oracle','c']

price_list=[3000,2000,1000,500]

print(course_list)

index=int(input("enter index"))

if (index>=0 and index<len(course_list)) or (index>=-len(course_list) and index<=-1):

print(course_list[index],price_list[index])

else:

print("invalid index")

============================================================

iterator

======

==>iterator object is used to read values from iterables(list,range,...).

==>iter() is a function or type which return iterator object.

syntax:

iter(iterable)

==> iterator is used to read values in seq order.

==> one iterator object is used to read only time.

next()

====

98
==> it is a predefined function, which is used read value return by iterator.

syntax:

next(iterator)

list1=[10,20,30,40,50,60,70,80,90,100]

it=iter(list1)

value1=next(it)

value2=next(it)

value3=next(it)

print(value1,value2,value3)

for value in it: # for loop calls next function of iterator

print(value,end=' ')

=================================================================

for loop

======

==> for loop is used to read values from collections or sequences.

==> it allows to read each time one value.

syntax:

for variable in list-name:

statement-1

statement-2

list1=[10,20,30,40,50,60]

for value in list1:

print(value,end=' ')

total=0

for value in list1:

total=total+value

print()

print("Total is ",total)

print("Avg is ",total/len(list1))

99
22-06-2020
22/6/2020

=========

slicing

=====

==> slicing allows to read more than one value.

==> index allows to read only one value.

==> slicing is done in two ways.

1. slice operator

2. slice type

==> slicing return a new list.

slice operator:

syntax:

list-name[startindex:endindex:step]

list-name[startindex::]

list-name[:endindex:]

list-name[::step]

list-name[::]

list-name[:]

eg:

list1=[10,20,30,40,50,60,70,80,90,100]

print(list1)

list2=list1[0:5] # startindex=0 endindex=5 step=1

print(list2)

list3=list1[5:] # startindex=5 endindex=end of list step=1

print(list3)

list4=list1[::] # startindex=0 endindex=end of list step=1

print(list4)

100
list5=list1[:] # startindex=0 endinex=endoflist step=1

print(list5)

list6=list1[::1] # startindex=0 endindex=endoflist step=1

print(list6)

list7=list1[::2] # startindex=0 endindex=endiflist step=2

print(list7)

list8=list1[3:8:2] # startindex=3 endindex=8 step=2

print(list8)

eg:

list1=[10,20,30,40,50,60,70,80,90,100]

print(list1)

list2=list1[::-1] # if step=-ve default start=-1 end=endoflist

print(list2) # if step=+ve default start=0 end=endoflist

list3=list1[::1]

print(list3)

eg:

list1=[10,20,30,40,50,60,70,80,90,100]

print(list1)

list2=list1[-10::] # startindex=-10 endindex=endoflist step=+1

print(list2)

list3=list1[len(list1)-1::-1] # start=9 stop=endoflist step=-1

print(list3)

list4=list1[-1::-1] # start=-1 stop=endoflist step=-1

print(list4)

eg:

# find output

list1=[10,20,30,40,50,60,70,80,90,100]

print(list1)

list2=list1[::-1]

101
print(list2) # 100 90 80 ...10

list3=list1[::1] # 10...100

print(list3)

list4=list1[-1::-1]

print(list4) # 100 to 10

list5=list1[5:]

print(list5) # 60 to 100

list6=list1[5::-1]

print(list6) # 60 to 10

list7=list1[9:5] # step=1

print(list7) # [] empty list

list8=list1[-5:-1] # step= 1

print(list8)

list9=list1[-5:-1:-1] # step=-1

print(list9) # emptylist

eg:

sales_2019=

[4000,7000,8000,9000,10000,12000,30000,6000,10000,56000,12000,40000]

q_sales=sales_2019[0:3]

h_sales=sales_2019[0:6]

print(sales_2019)

print(q_sales)

print(h_sales)

l3_sales=sales_2019[9:]

print(l3_sales)

l6_sales=sales_2019[6:]

print(l6_sales)

eg:

sales_2019=

102
[4000,7000,8000,9000,10000,12000,30000,6000,10000,56000,12000,40000]

q_sales=sales_2019[-len(sales_2019):-(len(sales_2019)-3)]

h_sales=sales_2019[-len(sales_2019):-(len(sales_2019)-6)]

print(sales_2019)

print(q_sales)

print(h_sales)

l3_sales=sales_2019[-1:-4:-1]

print(l3_sales)

l6_sales=sales_2019[-1:-7:-1]

print(l6_sales)

slice() type

=========

==> slice() type allows to save slice values into object.

==> this object can be applied to more than one sequence or list.

==> changes in list is applied all the list or sequences.

syntax:

slice(stop) ==> start=0,step=1

slice(start,stop,[step]) == > step=1

==> it is same as ragne type.

l1=[1,2,3,4,5]

l2=['a','b','c','d','e']

l3=[1+2j,1+3j,4+5j,2+3j,3+1j]

l4=[1.5,2.5,3.5,5.5,6.5]

s=slice(0,2)

print(l1)

print(l2)

print(l3)

print(l4)

l5=l1[s]

103
l6=l2[s]

l7=l3[s]

l8=l4[s]

print(l5)

print(l6)

print(l7)

print(l8)

23/06/2020
==========

methods or functions of list

======================

1. append(item) ==> append or add value in the list.

it will at the end of list.

eg:

list1=[10,20,30]

print(list1)

list1.append(40)

list1.append(50)

list1.append(60)

print(list1)

eg:

list1=list()

list1.append(10)

list1.append(20)

list1.append(30)

print(list1)

eg:

# write a program to read the scores of n plyers and calculate total score

104
scores_list=[]

n=int(input("Enter the scores of how many players")) # 3

for i in range(n): # 0 1 2

score=int(input("enter score")) # 50 60 70

scores_list.append(score) # [50 60 70]

total=0 # 180

for score in scores_list: # [50,60,70]

total+=score

print(scores_list)

print(total)

eg:

# write program to read name,n subject marks and find total,avg,min,max,grade

name=input("Enter name")

marks_list=[]

n=int(input("enter how many subjects"))

for i in range(n):

sub=int(input("enter marks"))

marks_list.append(sub)

total=sum(marks_list)

avg=total/n

min_marks=min(marks_list)

max_marks=max(marks_list)

print(f'Name {name}')

print(f'Marks {marks_list}')

print(f'Total {total}')

print(f'Avg {avg}')

print(f'Min Marks {min_marks}')

print(f'Max Marks {max_marks}')

if avg>=90:

105
print("Grade A")

elif avg>=80 and avg<90:

print("Grade B")

elif avg>=60 and avg<80:

print("Grade C")

elif avg<60:

print("Grade D")

extend() ==> appending more than one value

syntax: extend(iterable)

eg:

list1=[10,20,30,40,50]

print(list1)

list2=[60,70,80]

print(list2)

list1.extend(list2)

print(list1)

list1.extend(range(90,150,10)) # 90 100 110 120 130 140

print(list1)

insert(index,item) ==> inserting value at given index/position

==> if index is invalid it raises IndexError

list1=[10,20,30,40,50]

print(list1)

list1.insert(0,60) # [60,10,20,30,40,50]

print(list1)

list1.insert(3,100)

print(list1)

list1.insert(-1,200)

print(list1) # [60,10,20,100,30,40,200,50]

list1.insert(10,400) # append at the endof the list

106
print(list1)

exntending and inserting using slice operator:

list-name[len(list-name):len(list-name)]=[list of values]

list1=[10,20,30,40,50]

list1[len(list1):len(list1)]=[60,70,80]

print(list1) # [10,20,30,40,50,60,70,80]

list-name[startindex:endindex]=[list-of values]

list1=[10,20,30,40,50]

list1[0:0]=[60,70,80]

print(list1) ==> [60,70,80,10,20,30,40,50]

list1[1:1]=[100,200]

print(list1) ==> [60,100,200,70,80,10,20,30,40,50]

eg:

list1=list(range(10,110,10))

print(list1)

list1[len(list1):len(list1)]=[110,120,130]

print(list1)

list1[0:0]=[1,2]

print(list1)

list1[5:5]=[3,4,5,6] # slicing allows to insert multiple values

print(list1)

replacing value:

list-name[index]=value # replace one value

list-name[startindex:endindex]=[value,value,value] # replace more tha one value

eg:

list1=[10,20,30,40,50]

print(list1)

list1[0]=100

print(list1)

107
list1[1:4]=[200,300,400]

print(list1)

eg:

list1=list(range(1,21))

print(list1)

list1[1:len(list1)+1:2]=[0,0,0,0,0,0,0,0,0,0]

print(list1)

Q: How to add one value into list? ==> append

Q: How to add more than one value into list? ==> extend,slicing

Q: How to insert one value into list ? ==> insert

Q: How to insert more than one value into list? ==> slicing

Q: How to replace one value of list ? ==> index

Q: How to replace more than one of list ? ==> slicing

deleting value from list

===================

1. del with index

2. del with slicing

3. remove(value)

4. pop()

5. clear()

del is a keyword used to delete object.

list1=[10,20,30,40,50]

list1=[10,20,30,40,50]

print(list1)

del list1[1] # delete value at index 1

print(list1) # [10,30,40,50]

del list1[-2]

print(list1) # [10,30,50]

list2=list(range(10,110,10))

108
print(list2)

del list2[0:2]

print(list2)

del list2[0:5]

print(list2)

del list2[:]

print(list2)

list3=list(range(10,110,10))

print(list3)

del list3[0::2]

print(list3)

list4=list(range(10,110,10))

print(list4)

del list4[-1:-4:-1]

print(list4)

remove method

=============

==> it remove based on value but not index.

==> this allows to remove only one value.

remove(value)

list_strings=['java','python','oracle','ML','DS']

print(list_strings)

list_strings.remove('java')

print(list_strings)

list_strings.remove('oracle')

print(list_strings)

list_strings.remove('oracle') # Value Error

109
24/06/2020
using list as a stack

================

==> stack is data structure, which follows LIFO (Last In First Out), the element which is

inserted last is removed first.

==> stack allows the following operations.

1. push ==> adding element/item

2. pop ==> removing element

==> append method can be used to push item within stack.

==> pop method can be used to remove item from stack.

applications of stack:

1. evaluation of expressions

2. converting expression from one form to another.

3. compiler designing

4. memory management

Ex:

Stack Operations

1. Push

2. Pop

3. Display

4. Exit

Enter your option:

stack=[]

while True:

print("****Stack Operations****")

print("1. Push")

print("2. Pop")

print("3. Display")

110
print("4. Exit")

opt=int(input("Enter your option"))

if opt==1:

ele=int(input("Enter element to push"))

stack.append(ele)

print("value pushed inside stack")

elif opt==2:

if len(stack)==0:

print("Stack Empty")

else:

ele=stack.pop()

print(f'{ele} is poped from stack')

elif opt==3:

if len(stack)==0:

print("stack is empty")

else:

print(stack)

elif opt==4:

break

using list as a Queue

==================

==> Queue data structure followed FIFO (First in First Out). The element or item

inserted first is removed first.

Application of Queue:

1. CPU Scheduling

2. BFS alg in Graph(Breadth First Search)

3. Call Center Application where tickets are ogranized in queue

**** Queue Operations****

1. Adding

111
2. Removing

3. Displaying

4. Exit

Enter your option:

queue=list()

while True:

print("****Queue Operations****")

print("1. Adding")

print("2. Removing")

print("3. View")

print("4. Exit")

opt=int(input("enter your option"))

if opt==1:

ele=int(input("enter element"))

queue.append(ele)

print("element added in queue")

elif opt==2:

if len(queue)==0:

print("Queue is empty")

else:

del queue[0]

print("Element deleted from Queue")

elif opt==3:

print(queue)

elif opt==4:

break

clear() ==> remove all elements from list

list1=[10,20,30,40,50]

print(list1)

112
list1.clear()

print(list1)

list2=[10,20,30,40,50]

print(list2)

list2[:]=[]

print(list2)

==> len(s) length of s

==> min(s) smallest item of s

==> max(s) largest item of s

==> s.index(x[, i[, j]]) index of the first occurrence of x in s (at or after index i and

before index j)

==> s.count(x) total number of occurrences of x in s

==> s.copy() creates a shallow copy of s

there are two types of copies:

1. shallow copy

2. deep copy

==> shallow copy is a reference copy or address copy.

==> deep copy is object copy, it will create copy of objects.

import copy # copy is a module which contain deepcopy function.

list1=[[10,20,30]]

list2=list1.copy()

print(list1)

print(list2)

list1[0][0]=100

print(list1)

print(list2)

list2[0][0]=200

print(list1)

print(list2)

113
# ************* Deep Copy *************

list3=[[10,20,30]]

list4=copy.deepcopy(list3)

print(list3)

print(list4)

list3[0][0]=100

print(list3)

print(list4)

26&27/06/2020
=============

Searching element

================

1. in

2. not in

==> these both operators are return boolean value.

==> membership testing operator.

eg:

list1=[10,20,30,40,50,60,70,80,90,100]

b=20 in list1

print(b) ==> True

b=200 in list1:

print(b) ==> False

b=20 not in list1

print(b) ==> False

b=200 not in list1

print(b) ==> True

eg:

114
# write a program to read n names and search given name exists or not

names_list=[]

n=int(input("enter how many names"))

for i in range(n):

name=input("enter name")

names_list.append(name)

print(names_list)

name=input("enter name to search")

b=name in names_list

if b==True:

print(name,"exists")

else:

print(name,"not exists")

eg:

list1=list(range(10,110,10))

print(list1)

max_value=max(list1)

min_value=min(list1)

total_value=len(list1)

print("max value",max_value)

print("min value",min_value)

print("total values",total_value)

list2=[1,1,2,2,3,3,4,5,6,7,8]

print(list2)

c1=list2.count(1)

c2=list2.count(3)

c3=list2.count(5)

print(c1,c2,c3)

sorting

115
=======

sort(*, key=None, reverse=False)

This method sorts the list in place, using only < comparisons between items.

eg:

list1=[5,2,1,6,3,4]

print(list1)

list1.sort()

print(list1)

list1.sort(reverse=True)

print(list1)

list_names=['aaa','bbb','ccc','AAA','BBB','CCC']

print(list_names)

list_names.sort()

print(list_names)

list_names.sort(reverse=True)

print(list_names)

list2=['c','a','b','A','C','B']

print(list2)

list2.sort()

print(list2)

list2.sort(key=str.upper)

print(list2)

list_names=['RAMA','rama','AMAR','amar','vamsee','VAMSEE']

print(list_names)

list_names.sort()

print(list_names)

list_names.sort(key=str.upper)

print(list_names)

list_names.sort(key=str.lower)

116
print(list_names)

================================================================

# write a program to read n numbers and find first n maximum numbers

# [10,20,30,40,50,60,70,80]

# 60,70,80

list1=list()

n=int(input("enter how many numbers"))

for i in range(n):

num=int(input("enter any number"))

list1.append(num)

print(list1)

list1.sort(reverse=True)

print(list1)

n=int(input("how many maximum values"))

max_list=list1[:n]

print(max_list)

==================================================================

Operators used on list:

+ operator is used to concat two list.

list1=[10,20,30]

list2=[10,20,30]

list3=list1+list2

print(list1)

print(list2)

print(list3)

python_list=['rajesh','suresh','kishore']

java_list=['naresh','ramesh','kiran']

python_java_list=python_list+java_list

print(python_list)

117
print(java_list)

print(python_java_list)

* sequence repeate operator

list1=[1,2,3,4,5]

list2=list1*2

print(list1)

print(list2)

== operator is used to compare elements two list

list1=[1,2,3,4,5]

list2=[1,2,3,4,5]

list3=[1,2,3,4,6]

b1=list1==list2

b2=list1==list3

print(b1,b2)

list4=[2,1,4,5,3]

b3=list1==list4

print(b3)

compare lists using index

first value in list1 is compared with first value in list2....

==,>,<,>=,<=

list1=[10,20,30,40,50]

list2=[1,2,3,4,5]

b1=list1>list2

print(b1)

b2=list2<list1

print(b2)

b3=list1<list2

print(b3)

b4=list2>list1

118
print(b4)

l1=[10,20,30]

l2=[5,10,40]

b5=l1>l2

print(b5)

l3=[40,10,20]

b6=l1>l3

print(b6)

nested list

=========

==> defining list inside list is called nested list.

==> nested list can be used as matrix.

==> in nested list the items/elements are accessed using row and column index.

scores=[40,50,60,70,80]

scores=[[10,20,30,40,50],[60,70,80,90,10 ]]

marks=[30,40,50,60,70]

marks=[[1,2,3,4,5 ],[10,20,30,40,50 ],[100,50,60,70,80 ],[ ],[ ]]

eg:

matrix1=[[10,20,30],[40,50,60]]

# using index

for i in range(0,2): # 0 1

for j in range(0,3): # 0 1 2

print(matrix1[i][j],end=' ')

print()

# without using index

for row in matrix1: # [[10,20,30],[40,50,60]]

for col in row: # [10,20,30] [40,50,60]

print(col,end=' ')

print()

119
list1=matrix1[0]

list2=matrix1[1]

print(list1)

print(list2)

print(list1[0],list1[1],list1[2])

print(list2[0],list2[1],list2[2])

======================================================================

matrix1=[]

row1=[10,20,30]

row2=[40,50,60]

matrix1.append(row1)

matrix1.append(row2)

print(matrix1)

for row in matrix1:

for col in row:

print(col,end=' ')

print()

row=[1,2,3]

matrix1.insert(0,row)

print(matrix1)

matrix1.insert(2,row)

print(matrix1)

matrix1[0].append(4)

print(matrix1)

matrix1[0].insert(0,100)

print(matrix1)

del matrix1[0]

print(matrix1)

del matrix1[0][0]

120
print(matrix1)

matrix1[0][0]=50

print(matrix1)

=====================================================================

# write a program to read MxN matrix and display

m=int(input("enter how many rows"))

n=int(input("enter how many columns"))

matrix=[]

for i in range(m):

row=[]

for j in range(n):

value=int(input("enter value"))

row.append(value)

matrix.append(row)

print("Matrix is")

for row in matrix:

for value in row:

print(value,end=' ')

print()

=================================================================

# write a program to read 2x2 matrix and display

matrix1=[]

for i in range(2):

row=[]

for j in range(2):

ele=int(input("enter element"))

row.append(ele)

matrix1.append(row)

for row in matrix1:

121
for col in row:

print(col,end=' ')

print()

for i in range(2):

for j in range(2):

print(matrix1[i][j],end=' ')

print()

===================================================================

# adding two matrices

matrix1=[[1,2],[3,4]]

matrix2=[[3,4],[5,6]]

matrix3=[]

for i in range(2):

row=[]

for j in range(2):

value=matrix1[i][j]+matrix2[i][j]

row.append(value)

matrix3.append(row)

print(matrix1)

print(matrix2)

print(matrix3)

==================================================================

1. write a program to sub two matrices

2. write a program to muliply two matrices

3. write a program to read 3 students 3 subject marks and display

4. write a program to read 3x3 matrix and display upper triangle and lower triangle

5. write a program to print transpose of 3x3 matrix

122
29/06/2020
============

list comprehension

================

Q: What is comprehension or displays?

For constructing a list, a set or a dictionary Python provides special syntax called

“displays”, each of them in two flavors:

•either the container contents are listed explicitly, or

•they are computed via a set of looping and filtering instructions, called a

comprehension

==> list1=[10,20,30,40,50,"naresh","python",1+2j] ==> explicitly

==> list1=[1**2,2**2,3**2,4**2,5**2,.....10**2]

==> list1=[1**2,2**2,3**2,4**2,.......... 100**2]

list1=[]

for n in range(1,101): 1 2 3 4 5 6 7 8 9 10 ...... 100

list1.append(n**2)

list1=[n**2 for n in range(1,101)]

==> comprehension is elegant way of creating collections

(list,set,dictionary) using expression and filters.

1. list comprehension

2. set comprehension

3. dictionary comprehension

4. generator comprehension

list comprehension

================

syntax-1: for loop with expression

[expression for variable in iterable]

syntax-2: Filtering

123
[expression for variable in iterable if test]

syntax-3: Nested for loop

[expression for variable in iterable for variable in iterable]

syntax-4: Nested for loop with filter

[expression for variable in iterable for variable in iterable if test]

eg:

# create list by storing all the numbers from 1 to 100

list1=[n for n in range(1,101)]

print(list1)

# create list by storing all the alphabets from A-Z

list2=[chr(n) for n in range(65,91)]

print(list2)

# create list by storing all the alphabets from a-z

list3=[chr(n) for n in range(97,123)]

print(list3)

# create list by storing sqr of the numbers between 1-10

list4=[n**2 for n in range(1,11)]

print(list4)

# create list by storing n pow n from number between 1-10

list5=[n**n for n in range(1,11)]

print(list5)

===========================================================

# create a list storing random numbers from 1 to 100

import random

list1=[random.randint(1,100)for i in range(100)]

print(list1)

r=random.randrange(1,101,2)

print(r)

=================================================

124
import random

otplist=[str(random.randint(0,9))+str(random.randint(0,9))+str(random.randint

(0,9))+str(random.randint(0,9)) for i in range(5)]

print(otplist)

# random is predefined module in python

# randint is a predefined function exists in random module

list1=[chr(random.randint(65,91))+str(random.randint(0,9)) for i in range(5)]

print(list1)

=====================================================

# creating copy of the list

list1=[1,2,3,4,5,6,7,8,9,10]

list2=[value for value in list1]

print(list1)

print(list2)

list3=[[10,20],[30,40],[50,60]]

list4=[row for row in list3]

print(list3)

print(list4)

============================================================

30/06/2020
==========

syntax-2: Filtering

[expression for variable in iterable if test]

==> for loop each time it read one value from iterable and test condition, if

condition/test is True it eval expression and return the result of eval expression into

list.

without list comprehension:

125
list1=[1,2,3,4,5,6,7,8,9,10]

list2=[]

for value in list1:

if value%3==0:

list2.append(value)

print(list1) ==> [1,2,3,4,5,6,7,8,9,10]

print(list2) ==> [3,6,9]

with list comprhension:

list1=[1,2,3,4,5,6,7,8,9,10]

list2=[x for x in list1 if x%3==0]

print(list1) ==> [1,2,3,4,5,6,7,8,9,10]

print(list2) ==> [3,6,9]

===================================================================

list1=[n for n in range(1,100) if n%2==0]

print(list1)

list2=[n for n in range(1,100) if n%2!=0]

print(list2)

str1="python"

list3=[c for c in str1 if c in "aeiouAEIOU"]

print(list3)

list4=['naresh','suresh','rajesh','kishore','amar']

list5=[name for name in list4 if name.startswith(('a','r','k'))]

print(list4)

print(list5)

list6=[name for name in list4 if name.endswith(('e','r'))]

print(list6)

list7=['naresh','NARESH','suresh','SURESH','kishore','KISHORE']

list8=[name for name in list7 if name.isupper()]

126
list9=[name for name in list7 if name.islower()]

print(list7)

print(list8)

print(list9)

list10=['65','abc','a123','89','xyz']

list11=[value for value in list10 if value.isalpha()]

print(list10)

print(list11)

list12=["ramesh","kishore","rajesh","raja","rama","naresh"]

list13=[name for name in list12 if len(name)<5]

print(list12)

print(list13)

===================================================================

# write a program to add two matrices using list comprehension

matrix1=[[1,2],[3,4]]

matrix2=[[4,5],[6,7]]

without comprehension

matrix3=[]

for i in range(2): 0 1

row=[]

for j in range(2): 0 1

row.append(matrix1[i][j]+matrix2[i][j])

matrix3.append(row)

with list comprehension

matrix3=[[matrix1[i][j]+matrix2[i][j] for j in range(2)] for i in range(2)]

list1=[10,20,30,40,50]

list2=[[value] for value in list1]

127
print(list1)

print(list2)

list3=[[x+y for y in list1] for x in list1]

print(list3)

# expression can be one more list comprehesnon

list1=['a','b','c']

list2=['x','y','z']

list3=[[m+n for n in list2] for m in list1]

print(list1)

print(list2)

print(list3)

==================================================================

students_list=[[101,'naresh','A'],[102,'ramesh','A'],[103,'kishore','B'],[104,'raja','C']]

students_listA=[stud for stud in students_list if stud[2]=='A']

print(students_list)

print(students_listA)

students_listB=[stud for stud in students_list if stud[2]=='B']

students_listC=[stud for stud in students_list if stud[2]=='C']

print(students_listB)

print(students_listC)

===================================================================

product_list=[[1,'orange','fruits'],[2,'mango','fruits'],[3,'mouse','ele'],

[4,'keyboard','ele']]

print("**** online shoping ****")

print("1. Fruits")

print("2. Electronics")

opt=int(input("Enter option"))

if opt==1:

fruits_list=[prod for prod in product_list if prod[2]=='fruits']

128
print(fruits_list)

elif opt==2:

ele_list=[prod for prod in product_list if prod[2]=='ele']

print(ele_list)

====================================================================

syntax-3: Nested for loop

[expression for variable in iterable for variable in iterable]

01-07-2020
1/7/2020

========

syntax-3: Nested for loop

[expression for variable in iterable for variable in iterable]

eg:

list1=[1,2,3]

list2=[4,5,6]

list3=[x+y for x in list1 for y in list2]

print(list1)

print(list2)

print(list3)

eg:

# write a program to flatten a given 2-Dim list

list1=[[1,2,3],[4,5,6],[7,8,9]]

print(list1)

# without using list comprehension

list2=[]

for row in list1:

for value in row:

129
list2.append(value)

print(list2)

# with list comprehension

list3=[value for row in list1 for value in row]

print(list3)

syntax-4: Nested for loop with filter

[expression for variable in iterable for variable in iterable if test]

eg:

list1=[[1,2,3],[4,5,6],[7,8,9]]

list2=[value for row in list1 for value in row if value%2==0]

list3=[value for row in list1 for value in row if value%2!=0]

print(list1)

print(list2)

print(list3)

eg:

students_list=[['naresh','suresh'],['kishore','rajesh'],['amar','rama']]

students=[name for row in students_list for name in row]

print(students_list)

print(students)

students_length=[name for row in students_list for name in row if len(name)>5]

print(students_length)

students_list1=[name for row in students_list for name in row if name.endswith('a')]

print(students_list1)

tuple

====

==> tuple is a sequence or iterable.

==> tuple is an immutable sequence or iterable.

==> after creating tuple we cannot do any changes(adding,updating or deleting).

Q: what is difference between list and tuple?

130
list tuple

==> list is a mutable type,which allows to add,update and delete

after creation.

==> tuple is a immutable type, which does not allows to

add,update and delete after creation.

Where tuples are used?

==> tuples are used to represent key and values in dictionaries.

==> tuples are used with variable length arguments(functions)

==> tuples are used to create immutable list.

How create tuple?

==> empty tuple is created using ()

==> empty tuple is created using tuple()

==> singleton tuple is created using (value,) ==> a tuple which contain one value

x=(10) ==>expression

y=(10,) ==> tuple object

==>creating tuple with multiple values or objects (value,value,value,...)

==> creating tuple with existing iterables tuple(iterable)

eg:

t1=(10,20,30,40)

t2=100,200,300

print(t1)

print(t2)

print(type(t1))

print(type(t2))

t3=1000,

print(t3)

t4=(2000,)

print(t4)

print(type(t3))

131
print(type(t4))

eg:

# creation of tuple is called packing

courses=('c','c++','java','python') # packing

print(type(courses))

print(courses)

c1,c2,c3,c4=courses # unpacking

print(c1,c2,c3,c4)

eg:

# packing and unpacking tuple

# unpacking is process of reading values from tuple assign to individual variables

x,y,z=100,200,300 # unpacking the tuple

print(x,y,z)

t1=(10,20,30,40,50)

a,b,c,d,e=t1

print(a,b,c,d,e) # unpacking the tuple

a,b,c=100,200,300,400,500 # error

print(a,b,c)

eg:

# tuple allows hetrogenious objects

# tuple allows homogenious objects

t1=(10,'java',5000.0,1+2j,True)

print(t1)

t2=(10,20,30,40,50)

print(t2)

eg:

list1=[10,20,30,40,50]

print(list1)

list1[0]=100

132
print(list1)

t1=(10,20,30,40,50)

t1[0]=100 # cannot modify the content of tuple

print(t1)

eg:

list1=[10,20,30]

print(list1)

list1.append(40)

print(list1)

t1=(10,20,30)

print(t1)

t1.append(40) # error becoz tuple is immutable

print(t1)

eg:

# indxing and slicing can be done on tuples

t1=(10,20,30,40,50)

print(t1[0],t1[1],t1[2],t1[3],t1[4])

for i in range(5): # 0 1 2 3 4

print(t1[i])

for value in t1: # (10,20,30,40,50)

print(value)

i=iter(t1)

print(next(i))

print(next(i))

print(next(i))

t2=t1[:]

print(t2)

t3=t1[::-1]

print(t3)

133
02&03-07-2020

2&3/07/2020
===========

syntax-3: Nested for loop

[expression for variable in iterable for variable in iterable]

eg:

list1=[1,2,3]

list2=[4,5,6]

list3=[x+y for x in list1 for y in list2]

print(list1)

print(list2)

print(list3)

eg:

# write a program to flatten a given 2-Dim list

list1=[[1,2,3],[4,5,6],[7,8,9]]

print(list1)

# without using list comprehension

list2=[]

for row in list1:

for value in row:

list2.append(value)

print(list2)

# with list comprehension

list3=[value for row in list1 for value in row]

print(list3)

syntax-4: Nested for loop with filter

[expression for variable in iterable for variable in iterable if test]

eg:

134
list1=[[1,2,3],[4,5,6],[7,8,9]]

list2=[value for row in list1 for value in row if value%2==0]

list3=[value for row in list1 for value in row if value%2!=0]

print(list1)

print(list2)

print(list3)

eg:

students_list=[['naresh','suresh'],['kishore','rajesh'],['amar','rama']]

students=[name for row in students_list for name in row]

print(students_list)

print(students)

students_length=[name for row in students_list for name in row if len(name)>5]

print(students_length)

students_list1=[name for row in students_list for name in row if name.endswith('a')]

print(students_list1)

tuple

====

==> tuple is a sequence or iterable.

==> tuple is an immutable sequence or iterable.

==> after creating tuple we cannot do any changes(adding,updating or deleting).

Q: what is difference between list and tuple?

list tuple

==> list is a mutable type,which allows to add,update and delete

after creation.

==> tuple is a immutable type, which does not allows to

add,update and delete after creation.

Where tuples are used?

==> tuples are used to represent key and values in dictionaries.

==> tuples are used with variable length arguments(functions)

135
==> tuples are used to create immutable list.

How create tuple?

==> empty tuple is created using ()

==> empty tuple is created using tuple()

==> singleton tuple is created using (value,) ==> a tuple which contain one value

x=(10) ==>expression

y=(10,) ==> tuple object

==>creating tuple with multiple values or objects (value,value,value,...)

==> creating tuple with existing iterables tuple(iterable)

eg:

t1=(10,20,30,40)

t2=100,200,300

print(t1)

print(t2)

print(type(t1))

print(type(t2))

t3=1000,

print(t3)

t4=(2000,)

print(t4)

print(type(t3))

print(type(t4))

eg:

# creation of tuple is called packing

courses=('c','c++','java','python') # packing

print(type(courses))

print(courses)

c1,c2,c3,c4=courses # unpacking

print(c1,c2,c3,c4)

136
eg:

# packing and unpacking tuple

# unpacking is process of reading values from tuple assign to individual variables

x,y,z=100,200,300 # unpacking the tuple

print(x,y,z)

t1=(10,20,30,40,50)

a,b,c,d,e=t1

print(a,b,c,d,e) # unpacking the tuple

a,b,c=100,200,300,400,500 # error

print(a,b,c)

eg:

# tuple allows hetrogenious objects

# tuple allows homogenious objects

t1=(10,'java',5000.0,1+2j,True)

print(t1)

t2=(10,20,30,40,50)

print(t2)

eg:

list1=[10,20,30,40,50]

print(list1)

list1[0]=100

print(list1)

t1=(10,20,30,40,50)

t1[0]=100 # cannot modify the content of tuple

print(t1)

eg:

list1=[10,20,30]

print(list1)

list1.append(40)

137
print(list1)

t1=(10,20,30)

print(t1)

t1.append(40) # error becoz tuple is immutable

print(t1)

eg:

# indxing and slicing can be done on tuples

t1=(10,20,30,40,50)

print(t1[0],t1[1],t1[2],t1[3],t1[4])

for i in range(5): # 0 1 2 3 4

print(t1[i])

for value in t1: # (10,20,30,40,50)

print(value)

i=iter(t1)

print(next(i))

print(next(i))

print(next(i))

t2=t1[:]

print(t2)

t3=t1[::-1]

print(t3)

tuples inside list

=============

eg:

list1=[(10,20,30),(30,40,50)]

print(list1) ==> [(10,20,30),(30,40,50)]

list1.append((60,70,80))

print(list1) ==> [(10,20,30),(30,40,50),(60,70,80)]

print(list1[0]) ==> (10,20,30)

138
print(list1[1]) ==> (30,40,50)

print(list1[2]) ==> (60,70,80)

list1[0].append(90) # error

list1[0][0]=100 # error

del list1[0][0] # error

Note: list,set,dictionary,generator comprehension is allowed but tuple,frozenset

comprehension is not available.

Q: how to convert immutable tuple into mutable?

==> tuple should be converted to list.

t1=(10,20,30,40,50)

l1=list(t1) # convert tuple into list

l1.append(60) # append value

t1=tuple(l1) # convert list into tuple

Q: how to multable list into immutable?

list1=[10,20,30,40,50]

t1=tuple(list1) # converting list into tuple

set

===

==> A set object is an unordered collection of distinct hashable objects.

==> Set is unordered collection, where insertion order is not preserved.

==> Set collection does not allow duplicate objects.

==> Set allows only hashable objects.

==> In set, data is organized by using hashing data structure.

==> Set is an iterable.

Q: What is hashable object?

==> an object which is having hashcode or which generate hashcode

is called hashable object.

==> hashcode is an integer value which is used in organizing objects in hash based

data structures.

139
==> if two objects are equal according two eqaul operator, those objects hashcode

must be same.

how to find hashcode of object?

hash() ==> it is predefined function which is used to find hashcode of object.

==> the value which is used in comparing, the same is used as hash value.

==> set is non index based collection or set is not a sequence.

==> sequences allows indexing and slicing. set is not sequence it does not allows

indexing and slicing.

==> set is mutable collection.

==> set allows math set operations(union,intersection,difference,...)

How to create set?

1. creating empty set : set()

2. creating set with objects or elements : {ele,ele,ele,ele,ele}

Note: empty set cannot created using {}

3. creating using existing iterables : set(iterable)

eg:

set1={10,20,30,40,50} # set with similer type object

set2=set() # empty set

set3={1,'xyz',15.5,True}

print(set1)

print(set2)

print(set3)

eg:

integer_set={10,10,10,10,20,20,20,30,30,30,40,40,40}

print(integer_set)

string_set={'java','python','java','python','oracle'}

print(string_set)

bool_set={True,False,0,1}

print(bool_set)

140
bool_set={True,False,100,200,0,1}

print(bool_set)

How to read objects from set?

1. using for loop

2. using iterator

# reading values from set using for loop

set1={10,20,30,40,50}

for value in set1:

print(value)

# reading values frm set using iterator

set1={10,20,30,40,50}

i=iter(set1)

value1=next(i)

value2=next(i)

value3=next(i)

print(value1,value2,value3)

# value4=set1[0] # error bcoz set is non index based

eg:

# write a program to count how many times each element exists in the list

list1=[10,10,20,30,40,20,30] # 210220230140

str1=''

set1=set(list1)

for value in set1:

c=list1.count(value)

str1=str1+str(c)+str(value)

print(str1)

str2=''

list2=list(set1)

list2.sort()

141
for value in list2:

c=list1.count(value)

str2=str2+str(c)+str(value)

print(str2)

eg:

# abcabcxyz

# 2a2b2c1x1y1z

str1="abcabcxyz"

set1=set(str1)

print(set1)

list1=list(set1)

list1.sort()

str2=""

for ch in list1:

c=str1.count(ch)

str2=str2+str(c)+ch

print(str1)

print(str2)

mutable operations

================

add() ==> add(elem)

Add element elem to the set

eg:

# write a script/program to add 5 integers into set

set1=set()

for i in range(5):

ele=int(input("enter element"))

set1.add(ele)

for ele in set1:

142
print(ele)

update(*others)

set |= other | ...

Update the set, adding elements from all others

eg:

set1=set()

set1.add(10)

print(set1)

set1.update((20,30))

print(set1)

set1.update([40,50,60])

print(set1)

eg:

set1=set()

set1.update([10,20],[40,50])

print(set1)

list1=[100,200]

list2=[300,400,500,100]

set1.update(list1,list2)

print(set1)

set1.update(range(1,5),range(5,10))

print(set1)

set operations

============

1. union

union(*others)

set | other | ...

Return a new set with elements from the set and all others.

eg:

143
set1={10,20,30}

set2={40,50,60}

set3=set1.union(set2)

set4=set1|set2

print(set1)

print(set2)

print(set3)

print(set4)

s1={1,2}

s2={3,4}

s3={5,6}

s4={7,8}

s5=s1|s2|s3|s4

print(s1)

print(s2)

print(s3)

print(s4)

print(s5)

s6=(((s1.union(s2)).union(s3)).union(s4))

print(s6)

eg:

set_dept10={'ramesh','suresh','kishore'}

set_dept20={'rajesh','naresh'}

set_dept1020=set_dept10|set_dept20

print(set_dept10)

print(set_dept20)

print(set_dept1020)

intersection(*others)

set & other & ...

144
Return a new set with elements common to the set and all others.

eg:

set1={10,20,30,40,50}

set2={10,20,30,60,70}

set3=set1.intersection(set2)

print(set1)

print(set2)

print(set3)

set3=set1&set2

print(set3)

set4={1,2,3}&{3,4,5}&{3,6,7}

print(set4)

set5={'a','b','c'}&{'a','b','d'}&{'x','y','z'}

print(set5)

4-7-2020
========

intersection(*others)

set & other & ...

Return a new set with elements common to the set and all others.

eg:

set1={10,20,30,40,50}

set2={10,20,30,60,70}

set3=set1.intersection(set2)

print(set1)

print(set2)

print(set3)

set3=set1&set2

print(set3)

145
set4={1,2,3}&{3,4,5}&{3,6,7}

print(set4)

set5={'a','b','c'}&{'a','b','d'}&{'x','y','z'}

print(set5)

difference(*others)

set - other - ...

Return a new set with elements in the set that are not in the others.

eg:

set1={10,20,30,40,50}

set2={10,20,30,60,70}

set3=set1.difference(set2)

print(set1)

print(set2)

print(set3)

s1={'a','b','c','d','e'}

s2={'a','b','c','f','g'}

s3=s1-s2

print(s1)

print(s2)

print(s3)

s4={1,2,3}-{1,2,4}-{5,6}

print(s4)

s5={'ramesh','naresh'}-{'suresh','naresh'}-{'kishore','suresh'}

print(s5)

eg:

java_stud={'naresh','suresh','kishore'}

python_stud={'naresh','kishore','rajesh'}

only_java=java_stud-python_stud

print(java_stud)

146
print(python_stud)

print(only_java)

only_python=python_stud-java_stud

print(only_python)

java_python_stud=java_stud&python_stud

print(java_python_stud)

psymmetric_difference(other)

set ^ other

Return a new set with elements in either the set or other but not both

eg:

set1={10,20,30,40,50}

set2={10,20,30,60,70}

set3=set1.symmetric_difference(set2)

print(set1)

print(set2)

print(set3)

s1={'a','b','c','d','e'}

s2={'a','b','x','y','z'}

s3=s1^s2

print(s1)

print(s2)

print(s3)

s4={1,2,3,4,5}^{1,2,5,6}^{6,7,8,9}

print(s4)

intersection_update(*others)

set &= other & ...

Update the set, keeping only elements found in it and all others

set1={1,2,3,4,5}

set2={1,2,3,6,7}

147
print(set1)

print(set2)

set1.intersection_update(set2)

print(set1)

s1={1,2,3,4,5}

s2={1,2,3,6,7}

s3=s1.intersection(s2)

print(s1)

print(s2)

print(s3)

==> difference_update(*others)

set -= other | ...

Update the set, removing elements found in others.

==> symmetric_difference_update(other)

set ^= other

Update the set, keeping only elements found in either set, but not in both.

set1={1,2,3,4,5}

set2={1,2,3,6,7}

print(set1)

print(set2)

set1.difference_update(set2)

print(set1)

s1={1,2,3,4,5}

s2={1,2,3,6,7}

s1=s1.difference(s2)

isdisjoint(other)

Return True if the set has no elements in common with other. Sets are disjoint if and

only if their intersection is the empty set.

set1={1,2,3,4,5}

148
set2={1,2,3,6,7}

b=set1.isdisjoint(set2)

print(set1)

print(set2)

print(b)

s1={1,2,3}

s2={5,6,7}

print(s1)

print(s2)

b=s1.isdisjoint(s2)

print(b)

java_students={'naresh','suresh','kishore'}

python_students={'ramesh','rajesh'}

b=java_students.isdisjoint(python_students)

print(b)

if b==True:

print("no java student is doing python course")

else:

print("some java students are doing python course")

issubset(other)

set <= other

Test whether every element in the set is in other.

issuperset(other)

set >= other

Test whether every element in other is in the set.

set < other

Test whether the set is a proper subset of other, that is, set <= other and set != other.

set > other

Test whether the set is a proper superset of other, that is, set >= other and set != other

149
eg:

set1={1,2,3,4,5,6,7}

set2={1,2,3,4,5}

b=set1.issuperset(set2)

print(b)

set3={1,2,3,7,8}

b=set1.issuperset(set3)

print(b)

eg:

set1={'a','b','c','d','e'}

set2={'a','b','c'}

b1=set1<set2

print(b1)

set3={'a','b'}

b2=set3<set2

print(b2)

Removing element from set:

1. remove(elem)

Remove element elem from the set. Raises KeyError if elem is not contained in the set.

2. discard(elem)

Remove element elem from the set if it is present.

3. pop()

Remove and return an arbitrary element from the set. Raises KeyError if the set is

empty.

4. clear()

Remove all elements from the set.

set1={10,20,30,40,50}

set1.remove(10)

print(set1)

150
b=80 in set1

if b==True:

set1.remove(80)

else:

print("element not exist")

set1={1,2,3,4,5}

set1.discard(2)

print(set1)

set1.discard(10)

set1={10,20,30,40,50}

print(set1)

set1.pop()

print(set1)

set1.pop()

print(set1)

set1={10,20,30,40,50}

set1.clear()

print(set1)

nested sets

==========

6/7/2020
========

frozenset

========

Return a new set or frozenset object whose elements are taken from iterable. The elements of a set
must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not
specified, a new empty set is returned.

frozenset is immutable.

frozenset([iterable])

151
eg:

frozenset1=frozenset() # empty frozenset

print(frozenset1)

print(type(frozenset1))

frozenset2=frozenset(range(10,110,10))

print(frozenset2)

frozenset3=frozenset([10,20,30,40,50])

frozenset4=frozenset("PYTHON")

print(frozenset3)

print(frozenset4)

#frozenset1.add(10) # error becoz it is immutable

frozenset2.remove(10) # error

eg: nested sets

set1={frozenset([1,2,3]),frozenset([10,20,30]),frozenset(['a','b','c'])}

print(set1)

for s in set1:

print(s)

for value in s:

print(value)

eg:

emp_set={frozenset({101,'naresh',6000}),frozenset({102,'suresh',7000})}

print(emp_set)

for emp in emp_set:

print(emp)

for value in emp:

print(value)

dict or dictionary

==============

==> dictionary is a map collection.

152
==> in map data is organized as key and value pair.

==> A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is
currently only one standard mapping type, the dictionary.

==> map does not allow duplicate keys.

==> map allows duplicate values.

==> the key must be hashable object.

==> A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values
containing lists, dictionaries or other mutable types may not be used as keys.

==> dictionary is mutable.

how to create dictionary:

1. empty dictionary can be created using {}

2. empty dictionary can be created using dict()

3. dictionary can be created using items within {key:value,key:value,key:value,..}

4. dictionary using existing iterable => dict([(key,value),(key,value),(key,value),..])

5. dictionary can be created using zip ==> dict(zip(iterables))

eg:

d1={}

print(d1)

print(type(d1))

d2={100} # not dict

print(d2)

print(type(d2))

d3={1:100,2:200}

print(d3)

print(type(d3))

d4=dict() #Empty dictionary

print(d4)

print(type(d4))

d5=dict([(1,10),(2,20),(3,30),(4,40),(5,50)])

153
print(type(d5))

print(d5)

zip()

====

zip(*iterables)

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument
sequences or iterables.

z=zip(range(1,5),range(10,50,10))

print(z)

list1=list(z)

print(list1)

z=zip(range(1,5),range(10,50,10),range(50,100,10))

list1=list(z)

print(list1)

eg:

dict1=dict(zip(range(1,5),range(10,50,10)))

print(dict1)

list1=['a','b','c','d']

list2=[10,20,30,40]

dict2=dict(zip(list1,list2))

print(dict2)

list3=['a','b']

list4=[10,20,30,40,50]

dict4=dict(zip(list3,list4))

print(dict4)

list5=['a','b','c','d']

list6=[1,2]

dict5=dict(zip(list5,list6))

154
print(dict5)

eg:

# dictionary does not allow duplicate keys

dict1={1:10,2:20,3:30}

print(dict1)

dict1={1:10,1:20,1:30,1:40,1:50}

print(dict1)

# dictionary key can be mapped with more than one value

dict1={1:[10,20,30],2:[40,50,60],3:[60,70,80]}

print(dict1)

dict2={1:{10,20,30},2:{40,50,60},3:{60,70,80}}

print(dict2)

# is dictionary contain more than one key

dict1={(1,2):10}

print(dict1)

print(type(dict1))

dict2={(1,2):[10,20]}

print(dict2)

7/7/2020
How to read content of dictionary?

1. using key

2. using for loop

3. using iterator

4. using methods of dictionary

a. items

b. keys

c. values

using key:

155
syntax: dict-name[key]

==> this syntax return the value of the given key.

eg:

courses={'java':2000,'python':4000,'C':2000}

print(courses)

fee1=courses['java']

fee2=courses['python']

fee3=courses['C']

print(fee1,fee2,fee3)

fee4=courses['oracle'] # If key not exists raises KeyError

eg: in operator is used to verify/find/search given key exists in dictionary.

dict1={1:'one',2:'two',3:'three'}

print(dict1)

key=int(input("Enter key to read value"))

b=key in dict1

if b==True:

print(dict1[key])

else:

print("invalid key or key not exists")

eg:

student={1:['naresh','MCA'],2:['suresh','BCA'],3:['kishore','BTECH']}

print(student)

rno=int(input("Enter rollno"))

b=rno in student

if b==True:

l=student[rno]

print(rno,l)

else:

print("rollno not exists")

156
2. using for loop

eg: key and values can be any type:

dict1={1:'one'}

dict2={'one':1}

dict3={True:1}

print(dict1)

print(dict2)

print(dict3)

dict4={1.5:'base'}

print(dict4)

==> for loop is used to read only keys from dictionary.

for variable in dictionary:

statements

eg:

dict1={'a':'apple','b':'ball','c':'cat','d':'dog'}

for key in dict1:

print(key,dict1[key])

sales_dict1={2005:10000,2006:20000,2007:15000}

for year in sales_dict1:

print(year,sales_dict1[year])

3. using iterator

iter(dict) ==> this create iterator on dictionary.

==> to iterate or read we need call next() fuction on iterator object.

==> iterator read each time one key from dictionary.

players_dict={'dhoni':200,'rahul':100,'virat':50}

print(players_dict)

i=iter(players_dict)

p1=next(i)

print(p1,players_dict[p1])

157
p2=next(i)

print(p2,players_dict[p2])

p3=next(i)

print(p3,players_dict[p3])

4. using dictionary methods

a. keys()

Return a new view of the dictionary’s keys

b. values()

Return a new view of the dictionary’s values

c. items()

Return a new view of the dictionary’s items ((key, value) pairs).

Eg:

dict1={1:10,2:20,3:30,4:40,5:50}

print(dict1)

keyview=dict1.keys()

valueview=dict1.values()

itemsview=dict1.items()

print(keyview)

print(valueview)

print(itemsview)

key_list=list(keyview)

value_list=list(valueview)

items_list=list(itemsview)

print(key_list)

print(value_list)

print(items_list)

eg:

dict1={1:10,2:20,3:30,4:40,5:50}

for key,value in dict1.items(): # dict_items([(1,10),(2,20),(3,30),(4,40),..])

158
print(key,value)

mutable operations:

how to add item in dictionary :

1. dictionary[key]=value

this syntax perform two operations.

1. add item inside dictionary if given key is not exists

2. update value of given key if key is exists

eg:

dict1={}

dict1[1]=100

dict1[2]=200

dict1[3]=300

dict1[4]=400

dict1[5]=500

print(dict1)

dict1[1]=10

print(dict1) # update value of given key 1

eg:

# write a program/script to read sales of n sales persons and store in dictionary

# according to sales person name

sales={}

n=int(input("enter how many sales persons"))

for i in range(n):

name=input("enter sales person name")

amt=float(input("enter sale amount"))

sales[name]=amt

for name,amt in sales.items():

print(name,amt)

2. update

159
update([other])

Update the dictionary with the key/value pairs from other, overwriting existing keys.

dict1={}

dict1.update([(1,10),(2,20),(3,30)])

print(dict1)

dict1.update([(1,100)])

print(dict1)

dict1.update({1:'one',2:'two',3:'three',4:'four',5:'five'})

print(dict1)

dict2={}

dict2.update(zip([1,2,3,4,5],[10,20,30,40,50]))

print(dict2)

3. deleting items from dictionary

del dictionary-name[key]

eg:

cart={}

while True:

print("****Shoping Cart*****")

print("1. Add Produt")

print("2. Update Product")

print("3. Delete Product")

print("4. View Products")

print("5. Exit")

opt=int(input("Enter your option"))

if opt==1:

pname=input("ProductName :")

qty=int(input("Qty:"))

cart[pname]=qty

print("Product Added..")

160
elif opt==2:

pname=input("ProductName :")

b=pname in cart

if b==True:

qty=int(input("Qty: "))

cart[pname]=qty

print("Product updated...")

else:

print("Invalid ProductName")

elif opt==3:

pname=input("Product Name :")

b=pname in cart

if b==True:

del cart[pname]

print("Product Deleted...")

else:

print("Invalid product name")

elif opt==4:

for pname,qty in cart.items():

print(pname,qty)

elif opt==5:

break

8&9/7/2020
==========

dict1={1:10,2:20,3:30,4:40,5:50}

print(dict1)

l=list(dict1)

print(l)

161
for key in dict1:

print(key)

===============================================================

stud={101:['naresh','python'],102:['suresh','java']}

print(stud)

c=len(stud)

print(c)

==============================================================

# write a script to sort items in dictionary using key

dict1={4:40,2:20,5:50,1:10,3:30}

print(dict1)

l=sorted(dict1) # 1 2 3 4 5

dict2={}

for key in l:

print(key,dict1[key])

dict2[key]=dict1[key] # adding key value into dictionary2

print(dict2)

=====================================================================================
======

# write a script sort dictionary using values

dict1={1:200,2:100,3:50,4:250,5:90}

list1=list(dict1.items())

for i in range(len(list1)):

for j in range(len(list1)-1):

if list1[j][1]>list1[j+1][1]:

t=list1[j]

list1[j]=list1[j+1]

list1[j+1]=t

dict2=dict(list1)

162
print(dict1)

print(dict2)

=====================================================================================
===========

# sort dictionary using qty in ascending order

dict1={1:['abc',4],2:['xyz',2],3:['pqr',5],4:['mno',1]}

list1=list(dict1.items())

for i in range(len(dict1)):

for j in range(len(dict1)-1):

if list1[j][1][1]>list1[j+1][1][1]:

t=list1[j]

list1[j]=list1[j+1]

list1[j+1]=t

dict2=dict(list1)

print(dict1)

print(dict2)

=====================================================================================
============

dict1={1:10,2:20,3:30,4:40,5:50}

print(dict1)

value=dict1.pop(4)

print(value)

print(dict1)

key,value=dict1.popitem()

print(key,value)

print(dict1)

=====================================================================================
=============

list1=['a','b','c','d']

list2=['apple','ball','cat','dog']

163
dict1={key:value for key,value in zip(list1,list2)}

print(dict1)

=====================================================================================
=============

dict1={1:10,2:20,3:30,4:40,5:50}

dict2={key:value for key,value in dict1.items()}

print(dict1)

print(dict2)

=====================================================================================
============

list(d)

Return a list of all the keys used in the dictionary d.

eg:

dict1={1:10,2:20,3:30,4:40,5:50}

print(dict1)

l=list(dict1)

print(l)

for key in dict1:

print(key)

len(d)

Return the number of items in the dictionary d.

sorted(iterable)

Return a new sorted list from the items in iterable.

# write a script to sort items in dictionary using key

dict1={4:40,2:20,5:50,1:10,3:30}

print(dict1)

l=sorted(dict1) # 1 2 3 4 5

dict2={}

for key in l:

164
print(key,dict1[key])

dict2[key]=dict1[key] # adding key value into dictionary2

print(dict2)

dictionary comprhension

====================

==> dictionary comprehension allows to create new dictioanry in elegant way.

syntax-1==> {key:value for variable in iterable}

syntax-2==> {key:value for variable in iterable test}

syntax-3==> {key:value for variable in iterable for variable in iterable}

syntax-4==> {key:value for variable in iterable for variable in iterable if test}

eg:

list1=['a','b','c','d']

list2=['apple','ball','cat','dog']

dict1={key:value for key,value in zip(list1,list2)}

print(dict1)

eg:

dict1={1:10,2:20,3:30,4:40,5:50}

dict2={key:value for key,value in dict1.items()}

print(dict1)

print(dict2)

eg:

sales={2015:40000,2016:30000,2017:50000,2018:80000,2019:40000}

sales1={key:value for key,value in sales.items() if value>=50000}

sales2={key:value for key,value in sales.items() if value<50000}

print(sales)

print(sales1)

print(sales2)

eg: nested for loop dictionary comprhension

dict1={(k,v):k+v for k in range(2) for v in range(2)}

165
print(dict1)

eg:

# without using list comprehension

dict1={1:[1,2,3,4,5],2:[4,5,6,7,8],3:[8,9,3,7]}

dict2={}

for key,value in dict1.items():

l=[]

for n in value:

if n%2==0:

l.append(n)

dict2[key]=l

print(dict1)

print(dict2)

# using dictionary comprehension

dict3={key:[n for n in value if n%2==0] for key,value in dict1.items()}

print(dict3)

eg:

dict1={key:value for key in range(3) for value in range(3)}

print(dict1)

nested dictionaries

================

==> dictionary within dictionary is called nested dictioanry.

==> within dictionary, dictionary is added as value.

syntax:

{key:{dictionary},key:{dictionary},key:{dictionary},..}

emp_records={'emp1':{'id':101,'name':'naresh','sal':5000},

'emp2':{'id':102,'name':'suresh','sal':6000}}

sales={2019:{'jan':40000,'feb':50000,'mar':60000},

2020:{'jan':20000,'feb':30000}}

166
print(emp_records)

print(sales)

print(emp_records['emp1'])

for e in emp_records:

print(emp_records[e])

for year in sales:

print(sales[year])

# how to read 2019 jan sales

print(sales[2019]['jan'])

# how to read naresh salary

print(emp_records['emp1']['sal'])

eg:

sales={2019:{'jan':40000,'feb':50000,'mar':60000,'apr':20000},

2020:{'jan':20000,'feb':30000}}

sales2={year:{month:amt for month,amt in s.items() if amt>20000} for year,s in sales.items()}

print(sales)

print(sales2)

Q: what is diff between list,set,dictionary?

list set dictionary

1. list is ordered collection.

1. set is unordered collection.

1. dictionary is unordered collection.

2. it is index based collection, where reading and writing is done using index.

2. is non index based collection.

2. it is key based collection where reading and writing is done using key.

3. it allows slicing.

3. it does not allows slicing.

3. it does not allows slicing.

4. it allows duplicates.

167
4. it does not allows duplicates.

4. it allows duplicate values but not allows duplicate keys.

strings

======

==> string is a collection of characters, these characters can be alphabets,digits or special characters.

==> in python string is represented as constant or immutable.

==> becoz of immutability string can be shared.

==> in python string represented in 3 ways.

1. string is represented with in singe quotes ' '

2. string is represented with in double " "

3. string is represented within 3 single quotes or 3 double quotes

''' ''' , """ """

==> it is also represetend using str() type.

==> string is sequence datatype.

==> in string all characters are organized in seq order.

==> string is index based collection or sequence.

10/7/2020
=========

strings

======

==> string is a collection of characters, these characters can be alphabets,digits or

special characters.

==> in python string is represented as constant or immutable.

==> becoz of immutability string can be shared.

==> in python string represented in 3 ways.

1. string is represented with in singe quotes ' '

2. string is represented with in double " "

3. string is represented within 3 single quotes or 3 double quotes

168
''' ''' , """ """

==> it is also represetend using str() type.

==> string is sequence datatype.

==> in string all characters are organized in seq order.

==> string is index based collection or sequence.

eg:

str1="PYTHON"

str2='PYTHON'

print(str1)

print(str2)

str3="'PYTHON'"

str4='"PYTHON"'

print(str3)

print(str4)

str5='\'PYTHON\''

str6="\"PYTHON\""

print(str5)

print(str6)

str7="""PYTHON

PROGRAMMING

LANGUAGE"""

str8='''PYTHON

PROGRAMMING

LANGUAGE'''

print(str7)

print(str8)

str9='PYTHON\nPROGRAMMING\nLANGUAGE'

str10="PYTHON\nPROGRAMMING\nLANGUAGE"

print(str9)

169
print(str10)

str9='''"PYTHON"

"PROGRAMMING"

"LANGAUGE"'''

print(str9)

str10="""'PYTHON'

'LANGUAGE'

"""

print(str10)

eg:

str1=''

str2=str()

str3=str(100)

str4=str(1.5)

str5=str(1+2j)

str6=str(True)

print(str1,str2,str3,str4,str5,str6)

string indexing and slicing

=====================

==> indexing allows to only one element or value or character from string

==> slicing allows to read more than one character from string.

==> each character read from string is again string.

len() ==> this function returns lenth of any iterable.

eg:

# write a program/script to find length of string

# without using predefined function

# string is also iterable

str1=input("Enter any string")

c=0

170
for ch in str1: # string is iterable which allows to read one character

print(ch)

c+=1

print("Count of characters ",c)

eg: finding length of string using len predefined function

str1=input("Enter any string")

l=len(str1)

print("Length of string is ",l)

eg:

# reading characters from string using index

import random

str1=input("Enter any string") # PYTHON

for i in range(len(str1)): # range(6) ==> 0 1 2 3 4

print(str1[i])

i=1

while i<len(str1):

n=random.randint(0,len(str1))

print(str1[n])

i+=1

eg:

import random

str1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

n=random.randint(0,25)

print(str1[n])

eg:

import random

str1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

str2="0123456789"

str3="$*%"

171
password=''

for i in range(4):

n=random.randint(0,25)

password=password+str1[n]

for i in range(2):

n=random.randint(0,9)

password=password+str2[n]

n=random.randint(0,2)

password=password+str3[n]

print(password)

slicing ==> allows to read more than one value or character from string.

==> it is done in two ways.

1. slice operator

2. slice method

str1="PROGRAMMING"

str2=str1[:]

str3=str1[::]

print(str1)

print(str2)

print(str3)

str4=str1[-1::-1]

print(str4)

str5=str1[len(str1)-1::-1]

print(str5)

str6=str1[::-1]

print(str6)

str7=str1[::2]

print(str7)

methods of string

172
===============

string examine methods:

1. isalpha()

2. isdigit()

3. isupper()

4. islower()

5. istitle()

6. isalnum()

==> these methods return boolean values(True/False)

eg:

name=input("Enter name")

b=name.isalpha()

if b==True:

print(name,"Hello")

else:

print(name," is not valid should contain only alphabets")

eg:

name=input("Enter Name")

username=input("Enter UserName")

b1=name.isalpha()

b2=username.isalnum()

if b1==True:

if b2==True:

print("Valid name and username")

else:

print("Invlid username")

else:

print("invalid name")

eg:

173
n=input("Enter any number")

b=n.isdigit()

print(b)

eg:

str1="abc" # lowercase

str2="ABC" # uppercase

str3="Abc" # titlecase

b1=str1.isupper()

b2=str1.islower()

b3=str1.istitle()

print(b1,b2,b3) # False,True,False

b4=str2.isupper() # True

b5=str2.islower() # False

b6=str2.istitle() # False

print(b4,b5,b6)

b7=str3.isupper() # False

b8=str3.islower() # False

b9=str3.istitle() # True

print(b7,b8,b9)

string conversion methods

======================

=> upper() ==> return string in uppercase

=> lower() ==> return string in lowercase

=> title() ==> return string in titlecase

=> translate() ==> string translation.

=> maketranslate()

174
11/7/2020
=========

string conversion methods:

==========================

=> upper() ==> return string in uppercase

=> lower() ==> return string in lowercase

=> title() ==> return string in titlecase

=> translate() ==> string translation.

=> maketranslate()

eg:

str1="python"

str2="PYTHON"

str3="oracle"

str4=str1.upper()

str5=str2.lower()

str6=str3.title()

print(str1,str2,str3)

print(str4,str5,str6)

list1=['naresh','suresh','rajesh','kishore']

list2=[name.upper() for name in list1]

print(list1)

print(list2)

list3=[name.lower() for name in list2]

print(list3)

list4=[name.title() for name in list2]

print(list4)

list5=['a','b','c','d','A','B','C','z','D','p','Q']

list6=[s for s in list5 if s.isupper()]

175
list7=[s for s in list5 if s.islower()]

print(list5)

print(list6)

print(list7)

list8=['ab','bc','dc','12','pq123','p123*']

list9=[s for s in list8 if s.isalpha()]

list10=[s for s in list8 if s.isalnum()]

print(list8)

print(list9)

print(list10)

translate and maketranslate

=======================

"java"

aeiou ==> *+&%$

maketranslate:

==============

this method create taranslation table.

maketranslate(src,dest)

table=str.marktranslate("aeiou","*+&%$")

str1="java"

str2=str1.translate(table)

print(str1) ==> java

print(str2) ==> j*v*

eg:

str1="programming"

table=str.maketrans("aeiou","12345")

str2=str1.translate(table)

print(str1)

print(str2)

176
split methods:

=============

1. split

2. rsplit

3. partition

4. rpartition

5. splitlines

==> str.split(sep=None, maxsplit=- 1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is

given, at most maxsplit splits are done. If maxsplit is not specified or -1, then there is

no limit on the number of splits

eg:

str1="a,b,c,d,e,f"

print(str1)

l1=str1.split(",")

print(l1)

l2=str1.split(",",2)

print(l2)

l3=str1.split(",",3)

print(l3)

eg:

str1="ab*cd*de"

l=str1.split("*")

print(l)

str2="ab cd de"

l1=str2.split(" ")

print(l1)

l2=str2.split(" ",1)

print(l2)

177
eg:

name="gudio van rossum"

names=name.split(" ")

print(name)

print(names)

str.rsplit(sep=None, maxsplit=- 1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is

given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or

None, any whitespace string is a separator.

eg:

s1="1,2,3,4,5,6,7,8,9,10"

print(s1)

l1=s1.split(",")

l2=s1.rsplit(",")

print(l1)

print(l2)

l3=s1.split(",",3)

print(l3)

l4=s1.rsplit(",",3)

print(l4)

s2='a,b,c,d,e,f,g,h,j,k'

l5=s2.split(",")

l6=s2.rsplit(",")

print(l5)

print(l6)

l7=s2.split(',',4)

l8=s2.rsplit(',',4)

print(l7)

print(l8)

178
str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not

included in the resulting list unless keepends is given and true.

str1="python\nprogramming\nlangauage"

l1=str1.splitlines()

print(l1)

l2=str1.splitlines(True)

print(l2)

eg:

str1="python\nlanguage\vis\reasy\n"

l1=str1.splitlines()

print(l1)

str2='''python

programming

language'''

print(str2)

l2=str2.splitlines()

print(l2)

str.partition(sep)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part

before the separator, the separator itself, and the part after the separator. If the

separator is not found, return a 3-tuple containing the string itself, followed by two

empty strings.

"a,b,c,d,e".partition(",") ==> ('a',',','b,c,d,e')

"a:b,c:d,e".partition(",") ==>('a:b',',','c:d,e')

"abcde".partition("c")==>('ab','c','de')

13/7/2020
==========

179
trimming/strip methods:

=======================

1. str.lstrip([chars])

Return a copy of the string with leading characters removed. The chars argument is a

string specifying the set of characters to be removed. If omitted or None, the chars

argument defaults to removing whitespace. The chars argument is not a prefix; rather,

all combinations of its values are stripped:

2. str.rstrip([chars])

Return a copy of the string with trailing characters removed. The chars argument is a

string specifying the set of characters to be removed. If omitted or None, the chars

argument defaults to removing whitespace. The chars argument is not a suffix; rather,

all combinations of its values are stripped:

3.str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. The

chars argument is a string specifying the set of characters to be removed. If omitted

or None, the chars argument defaults to removing whitespace. The chars argument is

not a prefix or suffix; rather, all combinations of its values are stripped:

eg:

str1=" nit"

print(len(str1)) # 5

b=str1=="nit"

print(b) # False

str2=str1.lstrip() # "nit"

print(len(str2)) # 3

b=str2=="nit"

print(b)

eg:

str1="***nit"

print(str1)

180
str2=str1.lstrip("*")

print(str2)

str3="ababcabcnit"

print(str3)

str4=str3.lstrip("ab")

print(str4)

eg:

str1="nit "

print(len(str1))

str2=str1.rstrip()

print(len(str2))

print(str1)

print(str2)

eg:

str1="nit***"

str2=str1.rstrip("*")

print(str1)

print(str2)

str3="nit.$&*&*."

str4=str3.rstrip(".*&")

print(str3)

print(str4)

str5="nitabcabcabc"

str6=str5.rstrip("bc")

print(str5)

print(str6)

eg:

str1=input("any string")

print(str1)

181
print(len(str1))

str2=str1.rstrip()

print(str2)

print(len(str2))

eg:

str1=" nit "

print(str1)

print(len(str1))

str2=str1.strip()

print(str2)

print(len(str2))

str3="***nit****"

print(str3)

print(str3.strip("*"))

str4="ababcnitababc"

str5=str4.strip("abc")

print(str4)

print(str5)

eg:

str1="www.gmail.com"

str2=str1.lstrip("w.")

print(str1)

print(str2)

str3=str2.rstrip(".com")

print(str3)

str4=str1.strip("w.com")

print(str4)

finding and match methods:

===========================

182
1. str.endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise return False. suffix

can also be a tuple of suffixes to look for. With optional start, test beginning at that

position. With optional end, stop comparing at that position.

2. str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found within the slice s

[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 if sub is not found

3. str.rfind(sub[, start[, end]])

Return the highest index in the string where substring sub is found, such that sub is

contained within s[start:end]. Optional arguments start and end are interpreted as in

slice notation. Return -1 on failure.

4. str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a

tuple of prefixes to look for. With optional start, test string beginning at that position.

With optional end, stop comparing string at that position.

eg:

names_list=['naresh','kishore','ramesh','suresh','pavan']

names_list1=[name for name in names_list if name.endswith('h')]

print(names_list)

print(names_list1)

names_list2=[name for name in names_list if name.endswith(('a','e','i','o','u'))]

print(names_list2)

eg:

str1="programming"

b=str1.endswith('g')

print(b)

b=str1.endswith('m',0,7) # progrmm

print(b)

183
eg:

names_list=['amar','pavan','krishna','naresh','rajesh','om','ramesh','rama']

names_list1=[name for name in names_list if name.startswith('r')]

print(names_list)

print(names_list1)

names_list2=[name for name in names_list if name.startswith(('a','e','i','o','u'))]

print(names_list2)

names_list3=[name for name in names_list if not name.startswith(('a','e','i','o','u'))]

print(names_list3)

eg:

str1="naresh technologies"

index=str1.find("te")

print(index)

str2="python is a programming language"

index1=str2.find('g')

index2=str2.rfind('g')

print(index1)

print(index2)

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If

the optional argument count is given, only the first count occurrences are replaced.

str1="python java python java python java"

str2=str1.replace("java","python")

print(str1)

print(str2)

str3=str1.replace("java","oracle",1)

print(str3)

str4="aaaabbbbbccccdddd"

str5=str4.replace('a','A')

184
print(str5)

str6=str4.replace('a','A',2)

print(str6)

justification methods:

======================

str.center(width[, fillchar])

Return centered in a string of length width. Padding is done using the specified

fillchar (default is an ASCII space). The original string is returned if width is less than

or equal to len(s).

str.ljust(width[, fillchar])

Return the string left justified in a string of length width. Padding is done using the

specified fillchar (default is an ASCII space). The original string is returned if width is

less than or equal to len(s).

str.rjust(width[, fillchar])

Return the string right justified in a string of length width. Padding is done using the

specified fillchar (default is an ASCII space). The original string is returned if width is

less than or equal to len(s).

eg:

name1="naresh"

name2=name1.center(20)

print(name1)

print(name2)

name3=name1.center(20,'*')

print(name3)

name4=name1.center(30)

print(name4)

eg:

list_names=['naresh','kishore','rama','suresh','kiran']

for name in list_names:

185
print(name.center(20,'*'))

name1="naresh"

name2=name1.ljust(20)

print(name1)

print(name2)

name3=name1.ljust(20,'*')

print(name3)

name_list=['naresh','suresh','rama','kishore','kiran']

for name in name_list:

print(name.ljust(20,"*"))

eg:

name1="naresh"

name2=name1.rjust(20)

print(name1)

print(name2)

name3=name1.rjust(20,'*')

print(name3)

list_names=['naresh','suresh','kishore','raja','kiran']

for name in list_names:

print(name.rjust(20,'*'),name.ljust(20,'*'),name.center(20,'*'))

14&15-7-2020
============

functions

========

==> Python is a multiparadigm programming language.

==> It allows you to write programs using different programming

paradigm or approches.

1. unstructured programming

186
2. procedural programming

3. object oriented programming

==> in unstructured programming instructions are organized in seq order.

Q: What is a function?

==> a function is self contained block, which contain set of instructions inorder to

perform some operations.

==> a function is named block.

==> a function is small program within program.

1. Modularity

2. Reusability

3. Efficiency

==> Modularity: dividing programming instructions according two operation into small

modules. Which allows easy to understand code.

==> Reusability : functions allows to write code once and use number of time. this

avoid code redundency.

==> Efficiency : function reduce the size of program, which incr efficiency.

Types of functions

===============

1. predefined functions

2. user defined functions

predefined functions: the existing functions are called predefined functions. the

functions which are provided by python lib.

eg: input(),print(),int(),float(),.....

userdefined functions : the functions developed by python programmer are called

userdefined functions.

syntax:

def <function-name>([arguments]):

'''document string'''

statement-1

187
statement-2

statement-3

==> function must have atleast one statement.

==> inorder to write a function without any operation include pass.

Working with PyCharm

===================

Q: What is PyCharm?

==> PyCharm is python ide(Integrated Development Environment).

==> PyCharm is product of JetBrains.

==> PyCharm provide environment developing and executing python applications.

==> PyCharm work on the top of Python Software.

https://www.jetbrains.com/pycharm/download/#section=windows

download community pycharm

Creating project?

==> A project collection of programs/modules,packages and virtual environment.

How to create project?

==> File ==> New Project

Location ==> g:\project11am

==> Select Project ==> New ==> File ==> Python File

eg:

# writing defination of function

def sayHello():

print("Hello")

sayHello() # invoking function as an executable statement

sayHello() # invoking

sayHello() # invoking

sayHello() # invoking

eg:

def fun1(): # writing function

188
print("inside fun1")

fun1() # calling function

def fun2(): # writing function

print("inside fun2")

fun2() # calling function

==> function must be defined before calling it.

eg:

def drawLine():

for i in range(40):

print("*",end="")

print()

drawLine()

print("PYTHON")

drawLine()

print("LANGUAGE")

drawLine()

==> by writting or defining function it is not inovked or executed.

==> inorder to execute it must be called.

writing main function

=================

==> main is a userdefined function.

==> main function can programming logic.

==> main is called entry point the program execution.

eg:

def main(): # userdefined function

print("Inside main function")

main() # calling main function as executable statement

print("after executing main")

eg:

189
def fun1():

print("inside fun1")

def fun2():

print("inside fun2")

def main(): # calling function

fun1() # called function

fun2() # called function

main()

==> a function is never executed automatically. it has to be called by another function.

==> main is userdefined function which include all the operations done by program.

==> a program/module which is having executable statements is called executable

module/program. This module or program by default python assign one name called

__main__.

local variables

============

==> the variables declared inside function are called local variables.

==> the scope these variables within function, these variables cannot accessed

outside the function.

def fun1():

a=100 # local variable

print(a)

def fun2():

print(a) # error

def main():

fun1()

fun2()

main()

==> the memory for local variables allocated when function is called and deallocated

after execution of funtion.

190
eg:

def fun1():

a=10

print(a)

def main():

fun1()

main()

eg:

def add():

a=100 # creating local variable in add

b=200 # creating local variable in add

c=a+b # creating loca variable in add

print(c)

def sub():

a=300 # creating local variable in sub

b=400 # creating local variable in sub

c=a-b # creating local variable in sub

print(c)

def main():

add()

sub()

main()

==> the lifetime of local variales are until execution of funtion.

global variables

==============

==>

16&17-7-2020
=============

191
global variables

==============

==> The variables which are declared outside the function or at the top of the

program are called global variables.

==>These variables can be used inside more than one function of same program or

another program.

==> global variables are shared by one or more than one function.

eg:

a=100 # global variable

b=200 # global variable

def fun1():

print(a)

print(b)

def fun2():

print(a)

print(b)

def main():

fun1()

fun2()

print(a,b)

main()

eg:

list1=[1,2,3,4,5,6,7,8,9,10]

def sqr():

for n in list1:

print(n**2,end='')

def cube():

for n in list1:

print(n**3,end='')

192
def main():

sqr()

print()

cube()

main()

eg:

a=100 # global variable

def fun1():

b=200 # local variable

print(a)

print(b)

def main():

fun1()

main()

eg:

a=100 # global variable

def fun1():

b=200 # local variable

a=300 # create local variable in fun1

print(a)

print(b)

def fun2():

print(a)

def main():

fun1()

fun2()

main()

The global statement or global keyword

=================================

193
The global statement is a declaration which holds for the entire current code block. It

means that the listed identifiers are to be interpreted as globals. It would be

impossible to assign to a global variable without global, although free variables may

refer to globals without being declared global.

global <variable1>,<variable2>,...

eg:

a=100

def fun1():

global a

a=300

print(a)

def fun2():

print(a)

def main():

fun1()

fun2()

main()

eg:

base=0

height=0

def readData():

global base,height

base=float(input("Enter Base"))

height=float(input("Enter height"))

def findArea():

area=0.5*base*height

print("Area of triangle is ",area)

def main():

readData()

194
findArea()

main()

eg:

a=100

def fun1():

a=200 # local variable

print(a) # 200

global a

a=400 # error

def main():

fun1()

main()

function with arguments

====================

==> python allows you to write function with arguments and without arguments.

==> arguments are local variables which receive values from another function.

==> if function required input from another function, that function is defined with

arguments.

==> function without arguments cannot receive any values.

==> function with arguments receive values from caller.

python allows to write function with different types of arguments.

1. required arguments/positional arguments

2. default arguments

3. variable length arguments

4. keyword arguments

def fun1(): # function without arguments

pass

fun1(100) # invalid

def fun2(a): # function with arguments

195
pass

fun2(100)

def add(a,b):

....

.....

required arguments

================

==> An argument which required a value at the time of calling function.

eg:

def fun1(a,b): # required arguments

print(a,b)

def main():

fun1(100,200)

fun1(100) # error

fun1() # error

main()

eg:

def drawLine(symbol,width):# required arguments

for i in range(width):

print(symbol,end='')

print()

def main():

drawLine('*',20)

print("Python Programming")

drawLine('#',30)

print("Scripting Language")

drawLine('%',20)

main()

eg:

196
def findMax(a,b,c):

if a>b and a>c:

print(a)

elif b>c:

print(b)

elif c>a and c>b:

print(c)

else:

print("equal")

def main():

findMax(100,200,300)

findMax(200,300,100)

findMax(300,100,200)

findMax(100,100,100)

main()

eg:

def add(a,b):

print(a+b)

def sub(a,b):

print(a-b)

def multiply(a,b):

print(a*b)

def division(a,b):

print(a/b)

def main():

while True:

n1=int(input("Enter first number"))

n2=int(input("Enter second number"))

print("Calculator")

197
print("1.Add")

print("2.Sub")

print("3.Multiply")

print("4.Division")

print("5.Exit")

opt=int(input("enter option"))

if opt==1:

add(n1,n2)

if opt==2:

sub(n1,n2)

if opt==3:

multiply(n1,n2)

if opt==4:

division(n1,n2)

if opt==5:

break

main()

==> data in python is represented as objects.

==> sending objects to fuction is like sending address of object to function.

==> whenever we pass variables to function, it send address of object hold by

variable.

==> in python variables are reference variables, which does not values it hold

address.

eg:

def toUpper(l):

for i in range(len(l)):

l[i]=l[i].upper()

def main():

198
namesList=['naresh','suresh','rajesh','kishore']

print(namesList)

toUpper(namesList)

print(namesList)

main()

eg:

def swap(a,b):

a,b=b,a

def main():

x=100

y=200

print(x,y)

swap(x,y)

print(x,y)

main()

eg:

def fun1(a,b):

print(a,b)

def main():

# changing order of sending values

# by giving argument name

fun1(b=100,a=200)

fun1(300,400)

fun1(b=1000,a=2000)

fun1(a=3000,b=4000)

main()

return keyword

============

==> function return value to the calling function.

199
==> function receive values and perform operation and return result of that operation

to calling function using return keyword.

==> return terminate execution of function by returning value.

eg:

def average(a,b):

r=(a+b)/2

return r

def main():

a=int(input("Enter any number"))

b=int(input("Enter any number"))

c=average(100,200)

print(a,b,c)

main()

eg:

def toUppercase(s):

s1=''

for i in range(len(s)):

if s[i]>='a' and s[i]<='z':

ch=chr(ord(s[i])-32)

s1=s1+ch

else:

s1=s1+s[i]

return s1

def main():

str1="naresh"

str2=toUppercase(str1)

print(str1)

print(str2)

main()

200
eg:

def countWords(s):

c=1

c=c+s.count(' ')

return c

def main():

str1='python'

str2='python is a programming langauge'

c1=countWords(str1)

c2=countWords(str2)

print(c1)

print(c2)

main()

eg:

def countVowels(s):

c=0

for ch in s:

if ch in "aeiouAEIOU":

c+=1

return c

def countSpecial(s):

c=0

for ch in s:

if (ch>'a' and ch<='z') or (ch>='A' and ch<='Z') or (ch>='0' and ch<='9'):

pass

else:

c+=1

return c

def countDigits(s):

201
c=0

for ch in s:

if ch>='0' and ch<='9':

c+=1

return c

def main():

count1=countVowels("python program")

count2=countDigits("python 3.8")

count3=countSpecial("python current version is 3.8.1.2 * 7%$")

print(count1)

print(count2)

print(count3)

main()

18-7-2020
==========

Function with default arguments

================================

==> an argument given value at the time of defining the function is called default

arguemt.

==> this argument does not required value at the time of calling the function.

def function-name(arg1,arg2,arg3,arg4=<value>,..):

statement-1

statement-2

statement-3

==> arg1,arg2,arg3 are called required arguments.

==> arg4 is called default argument. it does not required to send value at the time of

calling function.

eg:

202
def fun1(a,b,c): # function with required arguemnts

print(a,b,c)

def fun2(a,b,c=100): # a,b are required c is default

print(a,b,c)

def main():

fun1(1,2,3)

fun2(10,20)

fun2(100,200,300)

main()

eg:

def drawLine(ch='*',width=30):

for i in range(width):

print(ch,end='')

print()

def main():

drawLine()

print("Python Programming")

drawLine('$')

print("Good Language")

drawLine('%',25)

print("Naresh Technologies")

drawLine(width=40)

main()

eg:

def fun1(a=100,b):

print(a,b)

def main():

fun1(200,300)

main()

203
Expl: the above script or code gives an error becoz

non default argument must followed by default.

eg:

def simple_intrest(amt,t,rate=1.5):

si=amt*t*rate/100

return si

def main():

res1=simple_intrest(5000,12)

res2=simple_intrest(6000,12,2.0)

print(res1)

print(res2)

main()

eg:

def sortList(l,order='ascending'):

if order=='ascending':

for i in range(len(l)):

for j in range(len(l)-1):

if l[j]>l[j+1]:

l[j],l[j+1]=l[j+1],l[j]

elif order=="descending":

for i in range(len(l)):

for j in range(len(l)-1):

if l[j]<l[j+1]:

l[j],l[j+1]=l[j+1],l[j]

def main():

list1=[10,50,20,40,30]

print(list1)

sortList(list1)

print(list1)

204
sortList(list1,'descending')

print(list1)

main()

eg:

def fun1(a,b=100,c):

print(a,b,c)

def main():

fun1(100,200,300)

main()

Expl: the above function gives an error.

eg:

def fun1(a,b=10,c=20,d=30):

print(a,b,c,d,)

def main():

fun1(100)

fun1(200,300,)

fun1(400,500,600)

fun1(700,800,900,1000)

fun1(b=1,a=2)

fun1(c=10,b=1,a=3)

fun1(10,d=100,c=300,)

main()

variable length argument or variable number of arguments

========================================================

==> an argument which receive 0 or more values is called variable length argument.

==> variable length argument is of type tuple.

def <function-name>(req-args,def-args=value,*var-length):

statement-1

statement-2

205
statement-3

==> variable length argument is prefix with *

20&21-7-2020
=============

variable length argument or variable number of arguments

=================================================

==> an argument which receive 0 or more values is called variable length argument.

==> variable length argument is of type tuple.

def <function-name>(req-args,def-args=value,*var-length):

statement-1

statement-2

statement-3

==> variable length argument is prefix with *

eg:

def fun1(*a):

print(a)

print(type(a))

print(a[0],a[1])

def main():

fun1(100,200)

main()

eg:

def maximum(*a):

if len(a)==0:

return None

elif len(a)==1:

return a[0]

else:

206
m=a[0]

for i in range(1,len(a)):

if a[i]>m:

m=a[i]

return m

def main():

res1=maximum()

res2=maximum(100)

res3=maximum(400,200,500,300)

print(res1,res2,res3)

main()

eg:

def fun1(a,*b):

print(a,b)

def main():

fun1(100)

fun1(200,300)

fun1(400,500,600,700)

fun1(1,2,3,4,5,6,7,8,9,10)

main()

eg:

def fun1(*a,*b):

print(a,b)

def main():

fun1(100,200,300)

main()

Expl: the above function display syntax error becoz a function contain only one

variable length argument.

eg:

207
def fun1(*a,b):

print(a,b)

def main():

fun1(b=100)

fun1(10,20,30,40,b=50)

fun1(100,200,300,400,500,b=600)

main()

eg:

def vowelCount(*alpha):

c=0

for value in alpha:

if value in "aeiouAEIOU":

c+=1

return c

def main():

count1=vowelCount('a','b','c')

count2=vowelCount('a','b','c','e','o')

print(count1)

print(count2)

main()

eg:

def addNumber(*n):

s=0

for value in n:

s=s+value

return s

def main():

res1=addNumber()

res2=addNumber(100)

208
res3=addNumber(10,20,30)

print(res1)

print(res2)

print(res3)

main()

# example of required arguments,default arguments and variablelength args

def fun1(a,b=10,*c):

print(a)

print(b)

print(c)

def main():

fun1(100)

fun1(100,200)

fun1(100,200,300,400,500)

main()

eg:

def fun1(*a,*b):

print(a,b)

def main():

print(100,200,300,400,500)

main()

Expl: the above function display error becoz a function cannot have multiple variable

length arguments.

keyword arguments

================

==> a function with keyword argument receive key and values.

==> keyword argument is of type dict.

==> keyword argument is prefix **

syntax:

209
def function-name(**kwargs):

statement-1

statement-2

eg:1

def fun1(**a):

print(a)

print(type(a))

def main():

fun1(x=100,y=200)

main()

eg:2

def drawLine(**kwargs):

keys=kwargs.keys()

listKey=list(keys)

value1=kwargs[listKey[0]]

value2=kwargs[listKey[1]]

for i in range(value2):

print(value1,end='')

print()

def main():

drawLine(char='*',width=30)

drawLine(x='$',y=40)

drawLine(line='%',size=50)

main()

eg:

def fun1(**kwargs):

print(kwargs['a'])

print(kwargs['b'])

def main():

210
fun1(a=100,b=200)

fun1(x=100,y=200) # error

main()

eg:

def simpleIntrest(**kwargs): # {'amt':6000,'time':24,'r':1.5}

si=kwargs['amt']*kwargs['time']*kwargs['rate']/100

return si

def main():

res=simpleIntrest(amt=5000,time=12,rate=2.5)

print(res)

res=simpleIntrest(amt=6000,time=24,rate=1.5)

print(res)

main()

eg:

def fun1(**kwargs):

print(kwargs)

def main():

fun1() # a function with keyword arguments can be called without

fun1(a=100) # giving key and value it is optional

main()

eg:

def fun1(a,*b,**c): # 1. required argument 2.arbitary arg 3.keyword args

print(a)

print(b)

print(c)

def main():

fun1(100)

fun1(200,300)

fun1(400,500,600,700)

211
fun1(800,900,x=1000,y=2000)

main()

eg:

def fun1(*a,b):

print(a)

print(b)

def main():

fun1(b=100)

fun1(10,20,30,b=40)

main()

Nested functions

==============

==> a function inside function is called nested function.

==> the inner function is called within outer function but

cannot called outside the outer function.

def <function-name>(args): # outer function

statement-1

statement-2

def <function-name>(args): # inner function

statement-3

statement-4

==> dividing the functionality of one function into number sub functions.

def fun1():

print("inside outer function")

def fun2(): # writing function or defining function

print("inside inner function")

fun2() # calling or invoking function

def main():

fun1()

212
main()

eg:

def calculator(n1,n2,opr):

def add():

return n1+n2

def sub():

return n1-n2

def multiply():

return n1*n2

def division():

return n1/n2

if opr=='+':

r=add()

return r

if opr=='-':

r=sub()

return r

if opr=='*':

r=multiply()

return r

if opr=='/':

r=division()

return r

def main():

num1=int(input("Enter first number"))

num2=int(input("Enter second number"))

o=input("Enter operator")

res=calculator(num1,num2,o)

print(res)

213
main()

==> nested function can use the variables of outer function.

==> outer function cannot use the variables/values of inner function.

22-07-2020
==========

==> nested function can use the variables of outer function.

==> outer function cannot use the variables/values of inner function.

eg: inner function/nested function can access local variables of outer function

def outer():

x=100 # local variable of outer function

def inner():

print(x)

inner()

def main():

outer()

main()

eg: outer function cannot access local variables of inner function.

def outer():

def inner():

x=200

print(x) # error

def main():

outer()

main()

eg:

def complexOperations(comp1,comp2,opr):

def addComplex():

return comp1+comp2

214
def subComplex():

return comp1-comp2

if opr=='+':

return addComplex()

if opr=='-':

return subComplex()

def main():

res1=complexOperations((1+2j),(2+3j),'+')

res2=complexOperations((2+3j),(1+2j),'-')

print(res1)

print(res2)

main()

eg:

x=100 # global variable

def fun1():

y=200 # local variable of function1

def fun2():

z=300 # local variable of function2

print("local variable value ",z)

print("outer function or enclosed function variable",y)

print("global variable",x)

fun2()

print("local variable value",y)

print("global variable value",x)

def main():

fun1()

main()

eg:

def fun1():

215
x=100

def fun2():

x=200 # creating variable in fun2

print(x)

fun2()

print(x)

def main():

fun1()

main()

nonlocal

========

The nonlocal statement causes the listed identifiers to refer to previously bound

variables in the nearest enclosing scope excluding globals. This is important because

the default behavior for binding is to search the local namespace first.

nonlocal variable1,variable2,variable3,....

eg:

def fun1():

x=100

def fun2():

nonlocal x

x=300

print(x)

fun2()

print(x)

def main():

fun1()

main()

eg:

def findAreaOfTriangle():

216
base=0.0

height=0.0

def read():

nonlocal base,height

base=float(input("Enter base of triangle"))

height=float(input("Enter height of triangle"))

read()

area=0.5*base*height

return area

def main():

a1=findAreaOfTriangle()

print(a1)

main()

eg:

x=100 # global variable

def fun1():

y=200 # local variable(Eclosing block)

def fun2():

z=300 # local variable

print(x)

print(y)

print(z)

fun2()

def fun3():

print(x)

def main():

print(x)

fun1()

fun3()

217
main()

eg:

res=None # global variable

def findResult():

rno=None

name=None

sub1,sub2=(0,0)

def read():

nonlocal rno,name,sub1,sub2

rno=int(input("Enter rollno"))

name=input("Enter name")

sub1=int(input("Enter subject1"))

sub2=int(input("Enter subject2"))

read()

print(f"Rollno {rno}")

print(f'Name {name}')

print(f'Subject1 {sub1}')

print(f'Subject2 {sub2}')

global res

if sub1<40 or sub2<40:

res="Fail"

else:

res="Pass"

def main():

findResult()

print(f'Result is {res}')

main()

eg:

n=100

218
def fun1():

def fun2():

global n

n=300

print(n)

fun2()

print(n)

def main():

fun1()

print(n)

main()

eg:

def fun1():

x=100

def fun2():

y=200

def fun3():

nonlocal x

x=400

print(x)

fun3()

fun2()

def main():

fun1()

main()

23/07/2020
Generators:

============

219
==> A generator is special function which does not return a single value, instead it returns iterator object
with sequence of values.

==> A generator function return value using yield keyword.

==> yield return value to the calling function, after returning it pause execution of function.

==> any function which contain yield statement is generator function.eg:

def fun1(): # generator function

yield 10

yield 20

yield 30

def main():

g=fun1()

r=range(1,100)

value1=next(g)

value2=next(g)

print(value1)

print(value2)

value3=next(g)

print(value3)

main()

eg:

def alphagenerator():

for i in range(65,91):

yield chr(i)

def main():

alpha=alphagenerator()

value1=next(alpha)

value2=next(alpha)

value3=next(alpha)

print(value1,value2,value3)

220
for value in alpha:

print(value,end=' ')

main()

eg:

def prime_generator(start,stop):

for num in range(start,stop+1):

c=0

for i in range(1,num+1):

if num%i==0:

c+=1

if c==2:

yield num

def main():

prime=prime_generator(5,10)

for value in prime:

print(value)

prime=prime_generator(1,100)

for value in prime:

print(value,end=' ')

prime=prime_generator(1,20)

list1=list(prime)

print(list1)

main()

eg:

import random

def otpgenerator():

while True:

221
otp=str(random.randint(0,9))+str(random.randint(0,9))+str(random.randint(0,9))+str(random.randint(0,
9))

yield int(otp)

def main():

otpgen=otpgenerator()

otp1=next(otpgen)

otp2=next(otpgen)

print(otp1)

print(otp2)

for i in range(5):

otp=next(otpgen)

print(otp,end=' ')

main()

Closure Function or Closures:

==============================

==> A closure is a function that remembers values in enclosing scopes even if they are not present
memory.

def fun1():

x=100

def fun2(): # closure function

print(x)

return fun2

def main():

f2=fun1()

f2()

==> closure function is useful when outer function receive the value and inner function perform
differenet operations using that value.

24&25-7-2020
Closure Function or Closures

222
=============================

==> A closure is a function that remembers values in enclosing scopes even if they are not present
memory.

def fun1():

x=100

def fun2(): # closure function

print(x)

return fun2

def main():

f2=fun1()

f2()

eg:

def readNum(num):

def pow(p):

r=num**p

return r

return pow

def main():

c1=readNum(5)

res1=c1(2)

res2=c1(3)

res3=c1(4)

print(res1,res2,res3)

main()

eg:

def draw_line(ch):

def draw(width):

for i in range(width):

print(ch,end='')

223
print()

return draw

def main():

draw1=draw_line('*')

draw1(30)

draw1(20)

draw1(40)

main()

==> closure function is useful when outer function receive the value and inner function perform
differenet operations using that value.

Decorators or function decorators

============================

==> A decorator takes in a function,adds some functionality and returns it.

==> Adding functionality to existing function without modifing it.

==> decorator function receive input as a function and return new function with additional functionality.

def box(f):

def draw():

print("****************")

f()

print("****************")

return draw

@box # decorator function

def fun1():

print("Hello")

@box # decorator function

def fun2():

print("Bye")

def main():

fun1()

224
fun2()

''' internal working of decorator'''

''' nfun1=box(fun1)

nfun2=box(fun2)

nfun1()

nfun2()'''

main()

eg:

def smart_division(fun):

def div(n1,n2):

if n2==0:

print("Cannot divide number with zero")

return

else:

r=fun(n1,n2)

return r

return div

@smart_division

def division(n1,n2):

n3=n1/n2

return n3

def main():

res1=division(5,2)

print(res1)

res2=division(5,0)

main()

Decorator chaining OR chained decorators

=========================================

==> if function is decorated with multiple decorators, it is called chained decorators.

225
==> a function decorator is calling another function decorator, which is called decorator chaining.

def draw_stars(f):

def draw():

print("*"*30)

f()

print("*"*30)

return draw

def draw_doller(f):

def draw():

print("$"*30)

f()

print("$"*30)

return draw

@draw_doller

@draw_stars

def fun1():

print("Hello")

def main():

fun1()

main()

eg:

def A(f):

def d():

print("A")

f()

return d

def B(f):

def d():

print("B")

226
f()

return d

@B

@A

def fun1():

print("Hello")

def main():

fun1()

main()

27/7/2020
=========

Lambda functions or lambda expressions

==================================

==> Lambda function is anonymous function.

==> A function without any name is called anonymous function.

==> Lambda functions are used as higher order function, a function which receive a

function as an argument.

syntax:

lambda <arguments>:expression

# lambda function without arguments

def main():

a=lambda :print("I Am Lambda Function")

a()

a()

main()

# lambda with arguments and return value

def main():

227
a=lambda x,y:x if x>y else y

max1=a(100,200)

max2=a(400,300)

print(max1)

print(max2)

main()

# lambda with arguments and return value

def main():

a=lambda x,y:x+y

res1=a(100,200)

res2=a(300,400)

print(res1)

print(res2)

main()

# labmda with higer order function

def calculator(f):

x=100

y=200

r=f(x,y)

return r

def main():

res1=calculator(lambda n1,n2:n1+n2)

res2=calculator(lambda n1,n2:n1-n2)

res3=calculator(lambda n1,n2:n1*n2)

print(res1)

print(res2)

print(res3)

main()

filter()

228
=====

filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true.

iterable may be either a sequence, a container which supports iteration, or an iterator.

If function is None, the identity function is assumed, that is, all elements of iterable

that are false are removed.

# filtering even and odd numbers

def main():

list1=list(range(1,25))

print(list1)

i=filter(lambda n:n%2==0,list1)

list2=list(i)

print(list2)

i=filter(lambda n:n%2!=0,list1)

list3=list(i)

print(list3)

main()

===================================================================

def main():

listOfNames=['naresh','NARESH','suresh','RAJESH','KISHORE']

i1=filter(lambda x:x.isupper(),listOfNames)

i2=filter(lambda x:x.islower(),listOfNames)

i3=filter(lambda x:x.startswith(('n','s')),listOfNames)

i4=filter(lambda x:x.endswith(('H','E')),listOfNames)

print(list(i1))

print(list(i2))

print(list(i3))

print(list(i4))

main()

229
==================================================================

def main():

list1=[True,False,False,True,False,True]

list2=list(filter(None,list1))

print(list1)

print(list2)

list3=[1,2,3,4,5,True,False,True,False,1.5]

list4=list(filter(None,list3))

print(list3)

print(list4)

list5=['a','b','c','d','e','f','True','False']

list6=list(filter(None,list5))

print(list5)

print(list6)

main()

====================================================================

map(function, iterable, ...)

Return an iterator that applies function to every item of iterable, yielding the results. If additional
iterable arguments are passed, function must take that many arguments and is applied to the items
from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is
exhausted.

60 ====> A

80 ====> A+

50 ====> B

70 ====> A

90 ====> A+

28/7/2020
==========

230
eg:

def main():

list1=[1,2,3,4,5,6,7,8,9,10]

i1=map(lambda x:x*x,list1)

i2=map(lambda x:x**3,list1)

print(list1)

print(list(i1))

print(list(i2))

main()

eg:

def main():

list1=["a","b","c","d","e"]

i=map(list,list1)

print(list1)

print(list(i))

i1=map(str.upper,list1)

print(list(i1))

list2=[1,2,3,4,5,6,7,8,9]

list3=list(map(str,list2))

print(list2)

print(list3)

list4=["123","456","678"]

list5=list(map(int,list4))

print(list4)

print(list5)

main()

eg:

def main():

list1=[1,2,3,4,5]

231
list2=[5,6,7,8,9]

list3=list(map(lambda x,y:x+y,list1,list2))

print(list1)

print(list2)

print(list3)

main()

eg:

def main():

list1=['a','b','c','d']

list2=['m','n','o']

list3=list(map(lambda x,y:x+y,list1,list2))

print(list1)

print(list2)

print(list3)

main()

reduce()

========

functools.reduce(function, iterable[, initializer])

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce
the iterable to a single value

eg:

import functools

def main():

list1=[10,20,30,40,50,60,70,80,90,100]

s=functools.reduce(lambda x,y:x+y,list1)

print(s)

m=functools.reduce(lambda x,y:x if x>y else y,list1)

print(m)

n=functools.reduce(lambda x,y:x if x<y else y,list1)

232
print(n)

main()

eg:

import functools

def main():

list1=['a','b','c','d','e','f']

s=functools.reduce(lambda x,y:x+y,list1)

print(s)

print(list1)

main()

function recursion or recursive functions

==========================================

==> calling function it self is called function recursion or recursive call.

eg:

def fun1():

print("inside fun1")

fun1() # recursive call

def main():

fun1()

main()

==> inorder work with function recursion we required 3 statements.

1. init statement

2. condition

3. updation

==> init statement define init value of condition.

==> condition define how many time recursion has to done

==> updation statement, which update condition.

==> function recursion eval is done using stack.

eg:

233
def printNum(n):

if n>0:

printNum(n-1)

print(n)

def main():

printNum(3)

main()

eg:

def factorial(n):

if n==0:

return 1

else:

return n*factorial(n-1)

def main():

num=int(input("Enter any number"))

res=factorial(num)

print("Factorial is ",res)

main()

29/7/2020
=========

modules and packages

====================

Q: What is module?

==> Every python program is called module.

==> Any file which is saved with ext .py is called module.

==> A module is collection of variables,functions,classes and objects.

==> these modules are two types.

1. predefined modules

234
2. userdefined modules

Q.predefined modules?

==> the modules provided by python are called predefined modules (OR) existing

modules are called predefined modules.

eg: os module,tkinter modules,datetime module,sys module,builtins module,...

Q.user defined modules?

==> the modules which are created by programmer or user are called userdefined modules.

==> modules provide modularity and reusability.

==> dividing the functions of an application into number of programs and each program is called one
module.

==> the content of one module can be used inside another module, which is called reusability.

==> userdefined modules are two types.

1. executable modules

2. reusable modules

==> executable modules consist of executable statements. this module is given a name python
runtime(PVM). the name of that module is __main__.

eg:

def fun1():

print("inside fun1")

def fun2():

print("inside fun2")

def fun3():

print("inside fun3")

print(__name__)

using the content of one module inside another module

=====================================================

import statement

==============

==> import is a keyword in python.

235
==> import statement allows to use the content of one

module inside another module.

==> import statement allows to import module name.

import module-name

==> in one program we can have multiple import statements.

module1.py

==========

def power(n,p):

return n**p

def maxTwo(n1,n2):

if n1>n2:

return n1

else:

return n2

module2.py

==========

import module1

def main():

res1=module1.power(5,2)

res2=module1.maxTwo(100,200)

print("Result1",res1)

print("Result2",res2)

main()

importing module with alias name

=================================

==> the module name can be imported with another name with the help of the

following syntax.

import moudle-name as alias-name

eg;

236
import module1 as m1

def main():

res1=m1.power(5,2)

res2=m1.maxTwo(100,200)

print(res1)

print(res2)

main()

importing content of the module

==========================

==> we can import the content of module inside current module using the following syntax.

from module-name import <function-name>,<variable-name>,..

from module-name import *

30&31/7/2020
=============

using the content of one module inside another module

=============================================

import statement

==============

==> import is a keyword in python.

==> import statement allows to use the content of one module inside another module.

==> import statement allows to import module name.

import module-name

==> in one program we can have multiple import statements.

module1.py

==========

def power(n,p):

return n**p

237
def maxTwo(n1,n2):

if n1>n2:

return n1

else:

return n2

module2.py

==========

import module1

def main():

res1=module1.power(5,2)

res2=module1.maxTwo(100,200)

print("Result1",res1)

print("Result2",res2)

main()

importing module with alias name

============================

==> the module name can be imported with another name with the help of the following syntax.

import moudle-name as alias-name

eg;

import module1 as m1

def main():

res1=m1.power(5,2)

res2=m1.maxTwo(100,200)

print(res1)

print(res2)

main()

importing content of the module

==========================

==> we can import the content of module inside current module using the following syntax.

238
from module-name import <function-name>,<variable-name>,..

from module-name import *

How to import executable module as reusable module

============================================

==> we need to check the following condition inorder import executable module as reusable module.

if __name__=='__main__':

main()

module4.py

=========

def fun1():

print("inside function1")

def fun2():

print("inside function2")

def fun3():

print("inside function3")

def main():

fun1()

fun2()

fun3()

if __name__=='__main__':

main()

module5.py

==========

import module4

def fun4():

print("inside function4")

def main():

module4.fun1()

fun4()

239
main()

package

=======

Q: What is package?

==> A package collection of modules.

==> A package is directory which contain .py files.

==> A package contain a special file called __init__.py.

==> This file does not contain any code. this file indicates that it

is a package.

How to create package?

==> select project

==> click right mouse button

==> select new ==> select python package

pip command

============

==> pip is a command or tool.

==> this tool used to manage packages related with python.

==> pip also python package installer.

==> pip is used to install python packages from the python package index and other.

Q: What PyPI?

==> PyPI is called python package index.

==> It is repository where all python packages available.

Open terminal

============

>pip

==> it shows all the commands related to pip

pip install <package-name> ==> installing package

pip unistall <package-name> ==> uninstalling package

pip list ==> to find installed packages

240
Q: What is virtual environment?

==> python virtual environment which consist of python software and installed packages(local
repository).

==> python virtual envrironment is used to develop and execute python applications.

==> by creating virutal environment we can manage versions and packages.

Q:How to create virtual environment?

==> first step install virtualenv module/tool. which is used to work with virtual environment.

1. pip install virtualenv

==> creating virtual environment.

virtualenv <evnrionment-name>

(OR)

python -m venv <environment-name>

2. virtualenv <envrionment-name>

eg: virtualenv myenv

==> on creation virtualenvironment, it include python interpreter and default lib and other tools

How to activate virtual environement?

3. c:\>c:\myenv\Scripts\activate

How to deactivate virtual environment

c:\>c:\myenv\Scripts\deactivate

1/8/2020
========

Object Oriented Programming(OOP)

Q: What is object oriented programming?

==> Object oriented programming is a programming paradigm.

==> Object oriented programming is not a language. It is a concept which define set of

rules and reg to organize data and instructions.

==> In object oriented application development data is represented as objects.

Q: What is object?

==> An object is real world entity.

241
==> Every object is having properties and behaviour.

==> Properties define the state of object.

==> Behaviour define the functionality object.

==> every object is an instance of a class.

Q: What is class?

==> class is blue print object.

==> class is a userdefined datatype.

==> class define the structure of object.

==> class is encapsulated with properties/attributes and behaviour/methods of object.

==> class is used to create object or class allocates memory of object.

predefined class: int,float,list,str,tuple,dict,frozenset,range,...

eg: list1=[10,20,30,40,50] ==> list

C: Python

int x; x=100 ==> int ==> class

x=100 y=1.5 ==> float ==> float

==> every datatype in python is a class and instances are objects.

Object Oriented Concepts:

1. Encapsulation

2. Polymorphism

3. Inheritance

4. class

5. object

Encapsulation:

=============

==> Encapsulation is a process binding data with related operations.

==> Encapsulation is a process of grouping data and operations which operate on that

within signle entity(class).

Adv:

Data Hiding : preventing data access from unrelated operations is called data hiding.

242
Adv object oriented programming:

1. Modularity ==> Encapsulation,Polymorphism,Inheritance

2. Reusability

3. Security

4. Extensibility

5. Efficiency

How to define class?

=================

==> define a class is creating a new datatype/userdefined datatype.

==> class is a collection of variables and methods /attributes and method/properties

and functions.

==> variables define the properties of object.

==> methods define the functionality of object.

syntax of class

============

class <class-name>:

variables

methods/member function

variables

========

==> variables declared inside a class are two types.

1. object level variables/instance variables

2. class level variable

3/8/2020
========

object level variables/instance variables

=================================

==> object properties are defined using instance variables/object level variables.

243
==> these variables are created in different ways.

1. constructor method __init__(self)

2. setattr() function

3. properties class

__init__(self):

==> this constructor method, this method is called automatically at the time of creating

object.

==> any method which suffix and prefix with __ is called magic method and these

methods are called automatically.

==> it is having first argument as self.

==> self is an argument name, which hold address of created object.

==> __init__() method refere to created object using self.

==> using self, we can create or access object level variables/instance variables.

==> object init is done using init.

==> __init__(self) contain the operations which has to be performed at the time of

creating.

eg:

class A:

def __init__(self):

print("object created")

print("object address is",self)

def main():

a1=A()

a2=A()

a3=A()

print(a1)

print(a2)

print(a3)

main()

244
Note: in the place of self we can use any other name.

eg:

class Student:

def __init__(self):

self.rno=0

self.name=""

def main():

stud1=Student()

stud2=Student()

stud1.rno=101

stud1.name="naresh"

stud2.rno=102

stud2.name="suresh"

print(stud1.rno,stud1.name)

print(stud2.rno,stud2.name)

main()

==> each object is having object level variables/instance variables.

==> object level variables/properties are accessed with object name.

eg:

class A:

def __init__(self):

self.x=100

self.y=200

def main():

print(A.x,A.y)

main()

Expl: the above code display syntax error becoz object level variables accessed with

object name not with class name and cannot accessed without creating object.

==> the variables declared inside class can be private,public or protected.

245
==> by default the variables are public.

==> private variables are prefix __ (double underscore)

==> protected variables are prefix _ (single underscore)

==> if variable is not prefix with underscore it is public.

eg: class A:

def __init__(self):

self.x=100

self.y=200

class B:

def __init__(self):

self.__x=100

self.__y=200

def main():

obj1=A()

print(obj1.x,obj1.y)

obj2=B()

print(obj2.__x,obj2.__y)

main()

==> private members are accessible by members(functions/methods) of these same

class but cannot accessible by non-members or members of other classes (OR)

cannot accessible outside the class/object.

class Student:

def __init__(self):

self.__rno=101

self.__name="naresh"

self.__course="python"

def main():

stud1=Student()

print(stud1.__rno)

246
print(stud1.__name)

print(stud1.__course)

list1=list()

list1.append()

main()

4/8/2020
========

==> private members are accessible by members(functions/methods) of these same

class but cannot accessible by non-members or members of other classes (OR)

cannot accessible outside the class/object.

class Student:

def __init__(self):

self.__rno=101

self.__name="naresh"

self.__course="python"

def main():

stud1=Student()

print(stud1.__rno)

print(stud1.__name)

print(stud1.__course)

list1=list()

list1.append()

main()

methods

========

==> a function defined inside the class is called method.

==> a method define behaviour of object.

==> a method define functionality of object.

247
==> methods written inside class are 3 types.

1. object level methods/instance methods

2. class level methods

3. static methods

object level methods/instance methods

================================

==> these methods are used to perform operation on object level variables.

==> these methods operate on object data.

==> any method defined inside class with first argument 'self' is called object level

method or instance method.

==> this method access object level variables using 'self' argument inorder to

manipulate data or to perform operations.

syntax:

def <method-name>(self,arg1,arg2,arg3,...):

statement-1

statement-2

==> this method is called with object and cannot called without creating object.

ex:

class Student:

def __init__(self):

self.__rno=101

self.__name="naresh"

self.__course="python"

def printStudent(self):

print(self.__rno)

print(self.__name)

print(self.__course)

def main():

stud1=Student()

248
# print(stud1.__rno)

# print(stud1.__name)

# print(stud1.__course)

stud1.printStudent()

main()

eg:

class Triangle:

def __init__(self):

self.__base=0.0

self.__height=0.0

def setBase(self,b):

self.__base=b

def setHeight(self,h):

self.__height=h

def findArea(self):

return self.__base*self.__height*0.5

def main():

t1=Triangle()

t1.setBase(1.5)

t1.setHeight(2.5)

t1_area=t1.findArea()

print("Area of triangle1 is ",t1_area)

t2=Triangle()

t2.setBase(2.5)

t2.setHeight(3.5)

t2_area=t2.findArea()

print("Area of triangle2 is ",t2_area)

main()

eg:

249
class Matrix:

def __init__(self):

self.__m=[[0,0],[0,0]]

def printMatrix(self):

for row in self.__m:

for col in row:

print(col,end=' ')

print()

def readMatrix(self):

for i in range(2):

for j in range(2):

self.__m[i][j]=int(input("Enter element"))

def main():

m1=Matrix()

m1.printMatrix()

m2=Matrix()

m2.printMatrix()

m1.readMatrix()

m1.printMatrix()

m2.readMatrix()

m2.printMatrix()

main()

eg:

class Stack:

def __init__(self):

self.__s=[]

self.__top=-1

def push(self,value):

self.__s.append(value)

250
print("element pushed")

self.__top=self.__top+1

def pop(self):

if self.__top==-1:

print("Stack is empty")

else:

value=self.__s[self.__top]

del self.__s[self.__top]

self.__top=self.__top-1

return value

def main():

stack1=Stack()

stack1.push(100)

stack1.push(200)

stack1.push(300)

e1=stack1.pop()

e2=stack1.pop()

print(e1)

print(e2)

main()

eg:

# constructor method with arguments

class Calculator:

def __init__(self,n1,n2):

self.__num1=n1

self.__num2=n2

def add(self):

return self.__num1+self.__num2

def sub(self):

251
return self.__num1-self.__num2

def multiply(self):

return self.__num1*self.__num2

def main():

calc1=Calculator(100,200)

print(calc1.add())

print(calc1.sub())

print(calc1.multiply())

main()

1. Write a class to find area rectangle

2. write a class to find area of circle

3. write a class to represent marks details of student and calculate total,avg and result

5/8/2020
=========

2. Write a class to find area rectangle

class Circle:

def __init__(self):

self.__r=0.0

def setR(self,r): # argument local variable

self.__r=r

def findArea(self):

return 3.147*self.__r*self.__r

def main():

circle1=Circle()

circle1.setR(1.2)

area1=circle1.findArea()

print("Area of circle is ",area1)

main()

252
1. Write a class to find area rectangle

class Rectangle:

def __init__(self):

self.__l=0.0

self.__b=0.0

def setL(self,l):

self.__l=l

def setB(self,b):

self.__b=b

def findArea(self):

return self.__l*self.__b

def main():

rect1=Rectangle()

rect1.setL(1.5)

rect1.setB(2.5)

area1=rect1.findArea()

print("Area of rectangle ",area1)

main()

3. write a class to represent marks details of student and calculate total,avg and

result

class StudentMarks:

def __init__(self):

self.__rno=0

self.__name=""

self.__sub1=0

self.__sub2=0

def readData(self):

self.__rno=int(input("Enter rollno"))

self.__name=input("Enter name")

253
self.__sub1=int(input("Enter subject1"))

self.__sub2=int(input("Enter subject2"))

def printData(self):

print(f'Rollno {self.__rno}')

print(f'Name {self.__name}')

print(f'Subject1 {self.__sub1}')

print(f'Subject2 {self.__sub2}')

print(f'Total {self.__sub1+self.__sub2}')

print(f'Avg {(self.__sub1+self.__sub2)/2}')

if self.__sub1<40 or self.__sub2<40:

print("Result is Fail")

else:

print("Result is Pass")

def main():

n=int(input("Enter how many students"))

studentList=[]

for i in range(n):

s=StudentMarks()

s.readData()

studentList.append(s)

for stud in studentList:

stud.printData()

main()

# develop score board application

class Player:

def __init__(self):

self.__name=""

self.__score=0

def setName(self,n):

254
self.__name=n

def setScore(self,s):

self.__score=s

def getName(self):

return self.__name

def getScore(self):

return self.__score

def main():

n=int(input("Enter how many players"))

playerList=list()

for i in range(n):

p=Player()

n=input("Enter name")

s=int(input("Enter score"))

p.setName(n)

p.setScore(s)

playerList.append(p)

tot=0

for p in playerList:

tot=tot+p.getScore()

print(f'{p.getName()}--->{p.getScore()}')

print(f'Total Score -----> {tot}')

main()

6&7/8/2020
==========

class level variables and class level methods

=====================================

class level variables

255
=================

==> the variables declared inside the class are called class level

variable.

==> this variable is used create a property which is common

for all the objects.

==> this variable can be accessed with class name without creating

object.

eg:

class Account:

minBalance=5000 # class level variable, this is global to all the objects

def __init__(self,accno,cname,bal):

self.__accno=accno # object level variable/instance variable

self.__cname=cname # object level variable/instance variable

self.__bal=bal # object level variable/instance variable

def deposit(self,amt):

self.__bal=self.__bal+amt

def withdraw(self,amt):

if self.__bal-amt<Account.minBalance:

print("Insuff balance")

else:

self.__bal=self.__bal-amt

def printAccount(self):

print(f'AccountNo {self.__accno}')

print(f'CustomerName {self.__cname}')

print(f'Balance {self.__bal}')

def main():

acc1=Account(101,"suresh",50000)

acc1.printAccount()

acc1.withdraw(45000)

256
acc1.printAccount()

acc1.withdraw(2000)

acc2=Account(102,"kishore",6000)

main()

#find output

class A:

x=100

def __init__(self):

self.y=200

def main():

print(A.x) # 100

a1=A()

a2=A()

a1.x=200

a1.y=300

a2.x=400

a2.y=500

print(a1.x,a1.y)

print(a2.x,a2.y)

main()

Ouput:

200 300

400 500

==> class level variable cannot modify with object name. if we trying modify with

object name python create a variable at object level.

==> class level variable is modified with class name.

==> class level variable can access with object name but cannot modified.

class level method

===============

257
==> a method defined inside class with first argument as 'cls' is called class level

method.

==> this method is called with class name, without creating object.

==> 'cls' is a first argument, which hold address of class.

==> inorder to declare class level method we use a decorator called @classmethod

syntax:

@classmethod

def <method-name>(cls,arg1,arg2,arg3,...):

statement-1

statement-2

statement-3

==> class level methods are used in application development for creating objects.

==> class level methods are called factory methods, these methods create object

and return address.

eg:

class A:

def m1(self):

print("object level method")

@classmethod

def m2(cls):

print("class level method")

def main():

A.m2()

# A.m1() error

obj1=A()

obj1.m1()

main()

eg:

class Person:

258
def __init__(self,n,a):

self.name=n

self.age=a

@classmethod

def createPerson(cls,n,dob):

a=2020-dob

p=Person(n,a)

return p

def printPerson(self):

print(f'Name :{self.name}')

print(f'Age : {self.age}')

def main():

p1=Person("naresh",40)

p2=Person("suresh",30)

p3=Person.createPerson("kishore",1980)

p4=Person.createPerson("rajesh",1992)

p1.printPerson()

p2.printPerson()

p3.printPerson()

p4.printPerson()

main()

eg:

class Employee:

def __init__(self,eno,en,s,c):

self.__empno=eno

self.__ename=en

self.__salary=s

self.__comm=c

@classmethod

259
def createEmployee(cls,eno,en,s):

c=0

if s>=10000:

c=s*10/100

elif s>=5000 and s<10000:

c=s*5/100

else:

c=s*2/100

e=cls(eno,en,s,c)

return e

def printEmployee(self):

print(f'EmployeeNo {self.__empno}')

print(f'EmployeeName {self.__ename}')

print(f'Salary {self.__salary}')

print(f'Comm {self.__comm}')

def main():

emp1=Employee(101,"naresh",5000,100)

emp2=Employee.createEmployee(102,"suresh",9000)

emp1.printEmployee()

emp2.printEmployee()

main()

static methods

============

==> a method defined inside class without first argument as 'cls' or 'self' is called

static method.

==> this method is declared with a decorator @staticmethod.

==> this method is called with class name.

@staticmethod

def method-name(arg1,arg2,...):

260
statement1

statement2

class Math:

@staticmethod

def maxOfIntegers(n1,n2):

if n1>n2:

return n1

else:

return n2

@staticmethod

def power(n,p):

return n**p

def main():

m1=Math.maxOfIntegers(100,200)

m2=Math.power(5,2)

print("Max is ",m1)

print("Result is ",m2)

main()

8/8/2020
========

class reusability

=============

==> object oriented application is a collection of classes.

==> the content of one class can be used inside another class in

different ways.

1. composition (has-a)

2. aggregation (use-a)

3. inheritance (is-a)

261
composition(has-a)

===============

==> composition is a process of creating an object of one class inside another class.

==> composition is between unrelated classes.

1. one-one

2. one-many

3. many-one

4. many-many

# one-many

class Address:

def __init__(self):

self.__street=None

self.__city=None

def setStreet(self,st):

self.__street=st

def setCity(self,c):

self.__city=c

def getStreet(self):

return self.__street

def getCity(self):

return self.__city

class Person:

def __init__(self):

self.__name=None

self.add1=Address()

self.add2=Address()

def setName(self,n):

self.__name=n

def getName(self):

262
return self.__name

def main():

p1=Person()

p1.setName("naresh")

p1.add1.setStreet("S.R.Nager")

p1.add1.setCity("Hyd")

p1.add2.setStreet("M.G.Road")

p1.add2.setCity("Hyd")

print(p1.getName())

print(p1.add1.getStreet())

print(p1.add1.getCity())

print(p1.add2.getStreet())

print(p1.add2.getCity())

main()

# one - one

class Dept:

def __init__(self):

self.__deptno=None

self.__dname=None

def setDeptno(self,dno):

self.__deptno=dno

def setDname(self,dn):

self.__dname=dn

def getDeptno(self):

return self.__deptno

def getDeptName(self):

return self.__dname

class Employee:

def __init__(self):

263
self.__ename=None

self.dept=Dept()

def setName(self,n):

self.__ename=n

def getName(self):

return self.__ename

def main():

emp1=Employee()

emp1.setName("naresh")

emp1.dept.setDeptno(10)

emp1.dept.setDname("Sales")

print(emp1.getName())

print(emp1.dept.getDeptno())

print(emp1.dept.getDeptName())

main()

# many to one

class College:

def __init__(self):

self.__came=None

def setCname(self,cn):

self.__cname=cn

def getCname(self):

return self.__cname

class Student:

college=College() # one time (OR) class level variable

def __init__(self):

self.__rno=None

self.__name=None

def setRno(self,rno):

264
self.__rno=rno

def getRno(self):

return self.__rno

def setName(self,name):

self.__name=name

def getName(self):

return self.__name

def main():

Student.college.setCname("NIT")

stud1=Student()

stud2=Student()

stud1.setRno(101)

stud1.setName("naresh")

stud2.setRno(102)

stud2.setName("Suresh")

print(stud1.getRno())

print(stud1.getName())

print(stud2.getRno())

print(stud2.getName())

print(Student.college.getCname())

main()

# write program for many-many relation

Aggregation(Use-A)

================

In composition,

1. the lifetime of contained object is until container object is exist

2. contained object is bind with only one type.

==> In aggregation contained object is not created within

container object, it is send using methods/inject using methods.

265
class Engine:

def start(self):

print("Car start...")

def stop(self):

print("Car stop..")

class Car:

def __init__(self,e):

self.__e=e

def carStart(self):

self.__e.start()

def carStop(self):

self.__e.stop()

def main():

engine1=Engine()

car1=Car(engine1)

car1.carStart()

car1.carStop()

main()

=======================================================

class BSNLSim:

def call(self):

print("Connects to BSNL Network....")

class AirtelSim:

def call(self):

print("Connects to Airtel Network")

class Mobile:

def __init__(self):

self.__sim=None

def insert(self,s):

266
self.__sim=s

def call(self):

self.__sim.call()

def main():

mobile1=Mobile()

bsnlsim1=BSNLSim()

mobile1.insert(bsnlsim1)

mobile1.call()

airtelsim1=AirtelSim()

mobile1.insert(airtelsim1)

mobile1.call()

main()

10/8/2020
Inheritance(IS_A)

===============

==> Inheritance allows to define class that inherit all the methods and properties from

another class.

==> Inheritance allows to define new class from an existing class. new class is called

derived class(child class) and existing class is base class(parent class).

==> Ineritance allows reusability(proerties and methods) and exitensibility(modify or

extend functionality of existing class without modifing it).

==> Inheritance model is called is-relationship. It means that derived class inherit

properties and methods of base class.

syntax

======

class derivedclass(base class1,base class2,base class3,....):

prperties

methods

267
==>python support the following types inheritances.

1. single level inheritance

2. multi level inheritance

3. multiple inheritance

4. hierarchical inheritance

5. hybrid inheritance

# single level inheritance

# A class methods are inheritane in B

class A: # parent class

def m1(self):

print("m1 of A")

class B(A): # child class

def m2(self):

print("m2 of B")

def main():

objb=B()

objb.m1()

objb.m2()

main()

# single level inheritance

# derived class inherit properties of base class

class A:

def __init__(self):

self.x=100

class B(A):

def __init__(self):

self.y=200

super().__init__()

def main():

268
objb=B()

print(objb.x)

print(objb.y)

main()

==> inorder to inherit properties of base class , it is required to call constructor

(__init__()) method of base class within derived class.

==> if constructor method of base class is not called in derived class the properties of

base class are not inherited in derived class.

==> this calling is done using super().__init__() .

==> super() refere to super class/base class.

# hierarchical Inheritance

class Employee:

def __init__(self):

self.__empid=None

self.__ename=None

def setEmpid(self,eid):

self.__empid=eid

def setEname(self,en):

self.__ename=en

def getEmpid(self):

return self.__empid

def getEname(self):

return self.__ename

class SalriedEmployee(Employee):

def __init__(self):

self.__salary=None

super().__init__()

def setSalary(self,sal):

self.__salary=sal

269
def getSalary(self):

return self.__salary

class CommEmployee(Employee):

def __init__(self):

self.__comm=None

super().__init__()

def setComm(self,com):

self.__comm=com

def getComm(self):

return self.__comm

def main():

emp1=SalriedEmployee()

emp2=CommEmployee()

emp1.setEmpid(101)

emp1.setEname("rajesh")

emp1.setSalary(50000)

emp2.setEmpid(102)

emp2.setEname("kishore")

emp2.setComm(500)

print(f'{emp1.getEmpid()},{emp1.getEname()},{emp1.getSalary()}')

print(f'{emp2.getEmpid()},{emp2.getEname()},{emp2.getComm()}')

main()

This is calling base class constructor with arguments.

class Alpha:

def __init__(self,x):

self.__x=x

def getX(self):

return self.__x

class Beta(Alpha):

270
def __init__(self,x,y):

self.__y=y

super().__init__(x)

def getY(self):

return self.__y

def main():

b1=Beta(100,200)

print(b1.getX())

print(b1.getY())

main()

# private members of base class are not accessible inside derived class

class A:

def __init__(self):

self.__x=100

class B(A):

def __init__(self):

super().__init__()

def printX(self):

print(self.__x)

def main():

b1=B()

b1.printX()

main()

# public members of base class/super class are accessible inside derived class

class A:

def __init__(self):

self.x=100

class B(A):

def __init__(self):

271
super().__init__()

def printX(self):

print(self.x)

def main():

b1=B()

b1.printX()

main()

=====================================================================

class Account:

def __init__(self,accno,cname,bal):

self.__accno=accno

self.__cname=cname

self.__bal=bal

def getAccno(self):

return self.__accno

def getCname(self):

return self.__cname

def getBal(self):

return self.__bal

def setBal(self,b):

self.__bal=b

class SavingAccount(Account):

def __init__(self,accno,cname,bal,cheqfac):

self.__cheqfac=cheqfac

super().__init__(accno,cname,bal)

def deposit(self,tamt):

b=self.getBal()

b=b+tamt

self.setBal(b)

272
def getCheqFac(self):

return self.__cheqfac

def main():

acc1=SavingAccount(101,"ramesh",6000,True)

print(acc1.getAccno(),acc1.getCname(),acc1.getBal(),acc1.getCheqFac())

acc1.deposit(2000)

print(acc1.getAccno(), acc1.getCname(), acc1.getBal(), acc1.getCheqFac())

main()

Multiple inheritance

================

==> if a class derive more than one base class ,it is called multiple inheritance.

==> in multiple inheritance derived class must call the constructor of base classes.

these constructors are called with class name by sending self.

class A:

def __init__(self):

self.x=100

class B:

def __init__(self):

self.y=200

class C(A,B): # multiple inheritance

def __init__(self):

self.z=300

A.__init__(self)

B.__init__(self)

def main():

objc=C()

print(objc.x)

print(objc.y)

print(objc.z)

273
main()

constructor with arguments

=======================

class A:

def __init__(self,x):

self.__x=x

def getX(self):

return self.__x

class B:

def __init__(self,y):

self.__y=y

def getY(self):

return self.__y

class C(A,B):

def __init__(self,x,y,z):

self.__z=z

A.__init__(self,x)

B.__init__(self,y)

def getZ(self):

return self.__z

def main():

objc=C(100,200,300)

print(objc.getX(),objc.getY(),objc.getZ())

main()

11/8/2020
Hierarchical Inheritance

====================

class Person:

274
def __init__(self,id,name):

self.__id=id

self.__name=name

def getId(self):

return self.__id

def getName(self):

return self.__name

class Student(Person):

def __init__(self,id,name,course):

self.__course=course

super().__init__(id,name)

def setCourse(self,course):

self.__course=course

def getCourse(self):

return self.__course

class Teacher(Person):

def __init__(self,id,name,subject):

self.__subject=subject

super().__init__(id,name)

def getSubject(self):

return self.__subject

class AdminStaff(Person):

def __init__(self,id,name,job):

self.__job=job

super().__init__(id,name)

def getJob(self):

return self.__job

def main():

stud1=Student(101,"naresh","python")

275
t1=Teacher(102,"suresh","java")

ns=AdminStaff(103,"kishore","Acc")

print(stud1.getId(),stud1.getName(),stud1.getCourse())

print(t1.getId(),t1.getName(),t1.getSubject())

print(ns.getId(),ns.getName(),ns.getJob())

main()

protected members

=================

==> protected members are prefix single underscore _

==> private members are prefix with __

From Charan A to Everyone: 11:50 AM

so sign for our convience to remind not to use outside class

From Nilesh Deosarkar to Me: (Privately) 11:50 AM

its on programmer choice where to access it outside class

class A:

def __init__(self):

self.__x=100 # private

self._y=200 # protected

self.z=300 # public

class B(A):

def printY(self):

print(self._y)

def main():

obja=A()

print(obja._y)

print(obja.z)

main()

Method Overriding

===============

276
==> redefining of base class instance method or object level method within derived

class is called method overriding.

==> defining method inside derived class with same name and arguments of method

exist in base class is called method overriding.

==> method overriding allows to extend or modify functionality of base class method

inside derived class.

==> if derived class wants to have different implementation of method exists in base

class,we override method.

class Parent:

def eat(self): # overriden method

print("parent eat veg....")

class Child(Parent):

def eat(self): # overriding method

print("child eat non veg...")

def sleep(self):

print("child sleep")

def main():

c=Child()

c.eat() # parent eat veg

c.sleep() # child sleep

================================================

class A:

def m1(self):

print("Overriden method")

class B(A):

def m1(self):

print("Overriding method")

def main():

objb=B()

277
objb.m1()

main()

==================================================

class Account:

def __init__(self):

self.__accno=None

self.__bal=None

def read(self):

self.__accno=int(input("AccountNo :"))

self.__bal=float(input("Balance :"))

def printAcc(self):

print("AccountNo :",self.__accno)

print("Balance ",self.__bal)

class CurrentAccount(Account):

def __init__(self):

self.__creditCard=None

def read(self): # ovrrride method

super().read() # calling method of base class

self.__creditCard=input("Enter Yes/No")

def printAcc(self): # overriding method

super().printAcc() # calling method of base class

print("CreaditCard :",self.__creditCard)

def main():

acc1=CurrentAccount()

acc1.read()

acc1.printAcc()

main()

==================================================================

object class

278
==========

==> every class by default inherit object class.

==> object class is a base class of all class in python.

12/8/2020
object class

==========

==> every class by default inherit object class.

==> object class is a base class of all class in python.

__str__() : it is method of object class this method returns type and id of object. this

method called when ever we print variable. this method is called automatically

whenever we print variable.

overriding __str__ method to return string representation of object.

class Student:

def __init__(self,rno,name):

self.__rno=rno

self.__name=name

def __str__(self): # overriding __str__ method

return str(self.__rno)+","+self.__name

def main():

stud1=Student(101,"naresh")

print(stud1)

list1=list([10,20,30,40,50])

print(list1)

main()

==> override __str__ to return state of the object whenever print reference variable.

==> predefined classes like int,float,complex,list,set,dict,... override the __str__

method, becoz of that when ever we print variables of these type, it print values not

address.

279
class Employee:

def __init__(self,eid,en):

self.empid=eid

self.ename=en

def __str__(self):

return str(self.empid)+","+self.ename

def main():

emp1=Employee(101,"suresh")

print(emp1)

list1=list()

list1.append(Employee(102,"kishore"))

list1.append(Employee(103,"naresh"))

print(list1)

e1=list1[0]

print(e1)

main()

__eq__ method

============

==> it is method of object, this method by default compare

address of one object with another object and return True/False.

==> inorder to compare with values, this method is override in

userdefined class.

==> this method is called automatically when ever we use

== operator.

predefined classes like list,set,dict,.. override __eq__ method becoz it compare

values not address of object.

def main():

list1=[10,20,30,40,50]

list2=[10,20,30,40,50]

280
b=list1==list2

print(b)

print(id(list1))

print(id(list2))

main()

# overriding __eq__ method to compare object values/state.

class Player:

def __init__(self,pn,r):

self.pname=pn

self.runs=r

def __eq__(self, other):

if self.runs==other.runs:

return True

else:

return False

def main():

p1=Player('rahul',100)

p2=Player('rohit',100)

p3=Player('virat',60)

b=p1==p2 # p1.__eq__(p2)

print(b)

print(id(p1))

print(id(p2))

b=p1==p3 # p1.__eq__(p3)

print(b)

main()

class Alpha:

def __init__(self,x):

self.__x=x

281
def __str__(self):

return str(self.__x)

def __eq__(self, other):

if self.__x==other.__x:

return True

else:

return False

def main():

a1=Alpha(100)

a2=Alpha(200)

a3=Alpha(100)

print(a1,a2,a3)

b1=a1==a2

b2=a1==a3

print(b1,b2)

main()

__hash__ method of object class

==========================

==> to converting userdefined object as an hashable object

inorder to add inside set collection we need override

__hash__ method.

==> if two objects are equal according to __eq__ method

it should generate same hashcode.

==> the value used in comparing objects, the same value is

used to generate hashcode or hashvalue.

eg:

282
class A:

def __init__(self,x):

self.__x=x

def __str__(self):

return str(self.__x)

def __eq__(self, other):

if self.__x==other.__x:

return True

else:

return False

def __hash__(self):

return self.__x

def main():

obj1=A(100)

obj2=A(200)

set1=set()

set1.add(obj1)

set1.add(obj2)

for s in set1:

print(s)

main()

eg:

class Student:

def __init__(self,rno,name):

self.__rno=rno

self.__name=name

def __str__(self):

return str(self.__rno)+","+self.__name

def __eq__(self, other):

283
if self.__rno==other.__rno:

return True

else:

return False

def __hash__(self):

return self.__rno

def main():

studSet=set()

studSet.add(Student(101,"naresh"))

studSet.add(Student(102,"suresh"))

studSet.add(Student(101,"kishore"))

for s in studSet:

print(s)

main()

abstract class and abstract methods

==============================

abstractmethod

=============

==> a method without implementation is called abstract method.

==> a method without body is called abstract method.

==> abstract method define a role/protocol, which has to be

followed by derived classes.

==> inorder to declare method as abstract, we need to use

@abstractmethod decorator

==> abstract method is defined only in abstract class.

syntax:

@abstractmethod

def <method-name>(self,arg1,arg2,arg3,..):

pass

284
==> abstract method must override in derived class.

abstract class

============

==> abstract class is a collection of abstract methods and non abstract methods.

==> if class is derived from "ABC" class, it is called abstract base class.

==> this is predefined class and exists in "abc" module.

==> abstract class is inherited, but cannot used for creating object.

==> abstract class define abstracts,set of rules and reg which

has to be followed by every derived class.

import abc

class <class-name>(abc.ABC):

variables

method

eg:

from abc import *

class A(ABC):

@abstractmethod

def m1(self):

pass

def main():

obja=A()

main()

==> the above code/program display error becoz we cannot create object of

abstract base class.

eg:

from abc import *

class A(ABC):

@abstractmethod

285
def m1(self):

pass

def m2(self):

print("non abstract method")

class B(A):

def m3(self):

print("m2 of B")

def main():

objb=B()

main()

==> the above program display error becoz the class which inherit abstract base

class must override all abstract method if not, the derived calss cannot used for

creating object.

13/8/2020
=========

==> the above program display error becoz the class which inherit abstract base class

must override all abstract method if not, the derived calss cannot used for creating

object.

from abc import *

class Shape(ABC):

def __init__(self):

self._dim1=None

self._dim2=None

def read(self):

self._dim1=float(input("Enter dim1"))

self._dim2=float(input("Enter dim2"))

@abstractmethod

def findArea(self):

286
pass

class Triangle(Shape):

def __init__(self):

super().__init__()

def findArea(self):

return self._dim1*self._dim2*0.5

class Rectangle(Shape):

def __init__(self):

super().__init__()

def findArea(self):

return self._dim1*self._dim2

def main():

t1=Triangle()

t1.read()

r1=Rectangle()

r1.read()

a1=t1.findArea()

a2=r1.findArea()

print("Area of triangle ",a1)

print("Area of rectangle ",a2)

main()

==> Inheritance is process of grouping all the classes which share common properties

and behaviour.

duck typing

==========

==> Duck typing in computer programming is an application of the duck test— "If it

walks like a duck and it quacks like a duck, then it must be a duck"— to determine if an

object can be used for a particular purpose.

==> Duck typing is a concept related to dynamic typing, where the type or the class of

287
an object is less important than the methods it defines. When you use duck typing, you

do not check types at all. Instead, you check for the presence of a given method or

attribute.

==>Python follows the EAFP (Easier to Ask Forgiveness than Permission) rather than

the LBYL (Look Before You Leap) philosophy. The Python philosophy of EAFP is

somewhat linked to its "duck typing" style of coding.

==> Loosly Coupled Code, The code which work with any

type is called loosly coupled code.

class DebitCard:

def withdraw(self):

print("withdraw from debitcard")

class CreditCard:

def withdraw(self):

print("withdraw from creditcard")

class EMICard:

def withdraw(self):

print("withdraw from EMICard")

class SwappingMachine:

def swap(self,s):

s.withdraw()

class ATM:

def swap(self,s):

s.withdraw()

def main():

card1=DebitCard()

card2=CreditCard()

card3=EMICard()

s1=SwappingMachine()

a1=ATM()

288
s1.swap(card1)

s1.swap(card2)

s1.swap(card3)

a1.swap(card1)

a1.swap(card2)

a1.swap(card3)

main()

eg:

class AirtelSim:

def call(self):

print("connect to airtel network")

class BsnlSim:

def call(self):

print("connect to bsnl network")

class JioSim:

def call(self):

print("connecto Jio network")

class Mobile:

def call(self,s):

s.call()

def main():

mobile1=Mobile()

sim1=AirtelSim()

sim2=BsnlSim()

sim3=JioSim()

mobile1.call(sim1)

mobile1.call(sim2)

mobile1.call(sim3)

main()

289
mokey patching

============

A MonkeyPatch is a piece of Python code which extends or modifies other code at

runtime.

Monkey patching is a technique that allows you to alter the behavior of objects at

runtime.

Monkey patching is tightly related to the idea of mutability in Python.

14/8/2020
==========

monkey patching

=============

A MonkeyPatch is a piece of Python code which extends or modifies other code at

runtime.

Monkey patching is a technique that allows you to alter the behavior of objects at

runtime.

Monkey patching is tightly related to the idea of mutability in Python.

What is monkey patching?

Monkey patching is a technique used to dynamically update the behavior of a piece of

code at run-time.

Why use monkey patching?

It allows us to modify or extend the behavior of libraries, modules, classes or methods

at runtime without actually modifying the source code

eg:

class A:

@classmethod

def m1(cls):

print("Hello")

@classmethod

290
def m2(cls):

print("Bye")

def main():

A.m1()

A.m1=m2 # monkey patching

A.m1()

main()

eg:

class A:

def m1(self):

print("Hello")

def m2(self):

print("Bye")

def main():

obj1=A()

obj1.m1()

A.m1=m2 # monkey patching

obj1.m1()

main()

class Employee:

def __init__(self):

self.empno=None

self.ename=None

self.salary=None

self.comm=None

def readEmployee(self):

self.empno=int(input("Enter EmployeeNo"))

self.ename=input("Enter EmployeeName")

self.salary=float(input("Enter Salary"))

291
if self.salary>=10000:

self.comm=self.salary*10/100

elif self.salary>=5000 and self.salary<10000:

self.comm=self.salary*5/100

else:

self.comm=0

def printEmployee(self):

print(self.empno,self.ename,self.salary,self.comm)

#patch

def readEmployeeNew(self):

self.empno=int(input("Enter employeeno"))

self.ename=input("Enter employeename")

self.salary=float(input("Enter salary"))

if self.salary>=20000:

self.comm=self.salary*10/1000

elif self.salary>=10000 and self.salary<20000:

self.comm=self.salary*5/100

else:

self.comm=0

def main():

emp1=Employee()

emp1.readEmployee()

emp1.printEmployee()

emp2=Employee()

Employee.readEmployee=readEmployeeNew

emp2.readEmployee()

emp2.printEmployee()

Employee.readEmployee=Employee.readEmployee

emp3=Employee()

292
emp3.readEmployee()

emp3.printEmployee()

main()

Operator overloading

==================

==> Operator overloading allows to modify or extends functionality of existing

operators (OR) Operator overloading allows to create new operators or functions

which operator on userdefined datatypes.

eg:

class Integer:

def __init__(self,v):

self.value=v

def __add__(self, other):

return self.value+other.value

def __str__(self):

return str(self.value)

def __sub__(self, other):

return self.value-other.value

def __mul__(self, other):

return self.value*other.value

def main():

a=100

b=200

c=a+b

print(a,b,c)

d=a-b

print(a,b,d)

e=a*b

print(a,b,e)

293
n1=Integer(100)

n2=Integer(200)

n3=n1+n2

print(n1,n2,n3)

n4=n1-n2

print(n1,n2,n4)

n5=n1*n2

print(n1,n2,n5)

main()

==> for every operator there is equal method available in object class.

==> inorder to perform operations on userdefined type,we need operator related

methods of object class.

class Student:

def __init__(self):

self.rno=None

self.sub1=None

self.sub2=None

def readStudent(self):

self.rno=int(input("Enter any rollno"))

self.sub1=int(input("Enter subject1"))

self.sub2=int(input("Enter subject2"))

def printStudent(self):

print(self.rno,self.sub1,self.sub2)

def __eq__(self, other):

if self.sub1==other.sub1 and self.sub2==other.sub2:

return True

else:

return False

def main():

294
stud1=Student()

stud1.readStudent()

stud1.printStudent()

stud2=Student()

stud2.readStudent()

stud2.printStudent()

b=stud1==stud2 # stud1.__eq__(stud2)

print(b)

main()

operator methods

+ __add__

- __sub__

* __mul__

class Employee:

def __init__(self):

self.empno=None

self.salary=None

def readEmployee(self):

self.empno=int(input("Enter empno"))

self.salary=float(input("Enter salary"))

def printEmployee(self):

print(self.empno,self.salary)

def __add__(self, other):

return self.salary+other.salary

def main():

emp1=Employee()

emp2=Employee()

emp1.readEmployee()

emp2.readEmployee()

295
total=emp1+emp2

print(total)

emp1.printEmployee()

emp2.printEmployee()

main()

Method Resolution Order in python(MRO)

===================================

==> Method Resolution Order is an order in which python search or looks for method

in inheritance or hierarchy classes.

__mro__ ==> this attribute return method resolution order

class A:

def m1(self):

print("m1 of A")

class B(A):

def m2(self):

print("m2 of B")

class C(B):

def m3(self):

print("m3 of C")

def main():

objc=C()

objc.m1()

print(C.mro())

main()

15&17/8/2020
Exception Handling or Error Handling

===============================

==> In application development we find two types of errors.

296
1. syntax errors

2. runtime errors

==> If there is a syntax error within program, it cannot be executed. these error

recognized by python translator/compiler. until these errors are not rectified program

execution is not done.

eg:

print("Hello")

print("Bye")

if True:

print("Bye")

runtime error

===========

==> the errors which occurs during execution of program are called runtime errors.

these runtime error also called logical errors.

==> why these errors occurs becoz of wrong input given by end user.

eg:

n1=int(input("Enter first number"))

n2=int(input("Enter second number"))

n3=n1/n2

print(n1,n2,n3)

output:

Enter first number5

Enter second number2

5 2 2.5

Enter first number3

Enter second number0

Traceback (most recent call last):

File "C:/Users/admin/AppData/Local/Programs/Python/Python38-32/extest1.py", line

3, in <module>

297
n3=n1/n2

ZeroDivisionError: division by zero

eg:

x=int(input("enter integer value"))

print(x)

output:

enter integer value12

12

enter integer valueab

Traceback (most recent call last):

File "C:/Users/admin/AppData/Local/Programs/Python/Python38-32/extest2.py", line

1, in <module>

x=int(input("enter integer value"))

ValueError: invalid literal for int() with base 10: 'ab'

==> the error which occurs during the execution of program are called runtime errors

or exceptions.

==> every error is one type/class, whose object created by function and raise

generate.

==> error types can be predefined or userdefined.

==> predefined errors types are exists within predefined modules.

these types are used by predefined functions.

int() ==> ValueError

float() ==> ValueError

list() ==> TypeError

NameError,ZeroDivisionError,...

list1=list([10,20,30,40,50])

print(list1)

list2=list(10)

==> when there is an error during execution of program,

298
program execution is terminated. to avoid abnormal termination

of program we use exception handlers or error handlers.

need of error handling:

1. avoiding abnormal termination of program

2. separating business and error logic

exception handlers or error handlers

==============================

==> the following keywords are used to handler errors.

1. try

2. except

3. finally

4. raise

5. assert

all error types are inherited from exception class.

1. ValueError

Raised when an operation or function receives an argument that has the right type but

an inappropriate value

2. TypeError

Raised when an operation or function is applied to an object of inappropriate type.

The associated value is a string giving details about the type mismatch.

Passing arguments of the wrong type (e.g. passing a list when an int is expected)

should result in a TypeError.

int([10,20,30])

list(10)

3. ZeroDivisionError

Raised when the second argument of a division or modulo operation is zero.

4. IndexError

Raised when a sequence subscript is out of range

5. KeyError

299
KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

6. NameError

Raised when a local or global name is not found

7. exception ModuleNotFoundError

A subclass of ImportError which is raised by import when a module could not be

located

try block

=======

==> this block contain the statements which raise and exception.

==> this block contain the statements which has to be monitored for exception

handling.

syntax:

try:

statement-1

statement-2

except block

===========

==> except block is an error handler block. when there is an error/exception within try

block it is handled by except block.

==> try block followed by one or more except blocks.

syntax:

try:

statements which raise an exception

except <error-type>:

statement

except <error-type>:

statement

==> if try block raise/generate more than one type of exception, it is handled by using

300
mulitple except blocks.

eg:

def main():

x=int(input("Enter first number"))

y=int(inEnter second number"))

try:

z=x/y

print(z)

except ZeroDivisionError:

print("Cannot divide number with zero")

print("Complete")

main()

eg:

def main():

dict1={'java':5000,'python':4000,'c':2000,'c++':1000}

ans='yes'

while ans!='no':

key=input("Enter course name")

try:

fees=dict1[key]

print(fees)

except KeyError:

print("Course not exists")

print("You want to find for another course")

ans=input("Enter answer")

main()

try block with multiple except blocks.

==> it try block raises more than one exception, it is handled using

multiple except blocks.

301
def main():

try:

x=int(input("Enter x value"))

y=int(input("Enter y value"))

z=x/y

print(z)

except ZeroDivisionError:

print("cannot divide number with zero")

except ValueError:

print("input must be number")

main()

handling multiple types of exceptions or errors using one except block

=========================================================

==> inorder t handle multiple errors using one except block, we need to

write except block without error type.

import sys

def main():

try:

n1=int(input("Enter first number"))

n2=int(input("Enter second number"))

n3=n1/n2

print(n3)

except:

print(sys.exc_info())

t=sys.exc_info()

print(t[1])

main()

finally

=====

302
==> finally is not an exception/error handler.

==> it is block which is excuted after try block and except block.

==> this block contain the code which is common for try block

and except block.

==> this block is used to deallocate resources allocted within

try block.

resources: open file, establishing connection to database,network connection.

try:

establish connection server program # allocating resource

send message

except type:

error is handled

finally:

close connection # deallocating resource

when finally block is executed?

1. after executing try block.

2. after executing except block

3. if there is an error inside try block and not handled by except block, it execute

finally block and terminate execution program.

eg:

def main():

try:

print("inside try block")

x=int(input("enter any number"))

print(x)

except ValueError:

print("Inside except block")

finally:

print("Inside finally block")

303
print("Continue")

main()

30&31/7/2020
=============

using the content of one module inside another module

=============================================

import statement

==============

==> import is a keyword in python.

==> import statement allows to use the content of one module inside another module.

==> import statement allows to import module name.

import module-name

==> in one program we can have multiple import statements.

module1.py

==========

def power(n,p):

return n**p

def maxTwo(n1,n2):

if n1>n2:

return n1

else:

return n2

module2.py

==========

import module1

def main():

304
res1=module1.power(5,2)

res2=module1.maxTwo(100,200)

print("Result1",res1)

print("Result2",res2)

main()

importing module with alias name

============================

==> the module name can be imported with another name with the help of the following syntax.

import moudle-name as alias-name

eg;

import module1 as m1

def main():

res1=m1.power(5,2)

res2=m1.maxTwo(100,200)

print(res1)

print(res2)

main()

importing content of the module

==========================

==> we can import the content of module inside current module using the following syntax.

from module-name import <function-name>,<variable-name>,..

from module-name import *

How to import executable module as reusable module

============================================

==> we need to check the following condition inorder import executable module as reusable module.

if __name__=='__main__':

main()

module4.py

=========

305
def fun1():

print("inside function1")

def fun2():

print("inside function2")

def fun3():

print("inside function3")

def main():

fun1()

fun2()

fun3()

if __name__=='__main__':

main()

module5.py

==========

import module4

def fun4():

print("inside function4")

def main():

module4.fun1()

fun4()

main()

package

=======

Q: What is package?

==> A package collection of modules.

==> A package is directory which contain .py files.

==> A package contain a special file called __init__.py.

==> This file does not contain any code. this file indicates that it

is a package.

306
How to create package?

==> select project

==> click right mouse button

==> select new ==> select python package

pip command

============

==> pip is a command or tool.

==> this tool used to manage packages related with python.

==> pip also python package installer.

==> pip is used to install python packages from the python package index and other.

Q: What PyPI?

==> PyPI is called python package index.

==> It is repository where all python packages available.

Open terminal

============

>pip

==> it shows all the commands related to pip

pip install <package-name> ==> installing package

pip unistall <package-name> ==> uninstalling package

pip list ==> to find installed packages

Q: What is virtual environment?

==> python virtual environment which consist of python software and installed packages(local
repository).

==> python virtual envrironment is used to develop and execute python applications.

==> by creating virutal environment we can manage versions and packages.

Q:How to create virtual environment?

==> first step install virtualenv module/tool. which is used to work with virtual environment.

1. pip install virtualenv

==> creating virtual environment.

307
virtualenv <evnrionment-name>

(OR)

python -m venv <environment-name>

2. virtualenv <envrionment-name>

eg: virtualenv myenv

==> on creation virtualenvironment, it include python interpreter and default lib and other tools

How to activate virtual environement?

3. c:\>c:\myenv\Scripts\activate

How to deactivate virtual environment

c:\>c:\myenv\Scripts\deactivate

1/8/2020
========

Object Oriented Programming(OOP)

Q: What is object oriented programming?

==> Object oriented programming is a programming paradigm.

==> Object oriented programming is not a language. It is a concept which define set of

rules and reg to organize data and instructions.

==> In object oriented application development data is represented as objects.

Q: What is object?

==> An object is real world entity.

==> Every object is having properties and behaviour.

==> Properties define the state of object.

==> Behaviour define the functionality object.

==> every object is an instance of a class.

Q: What is class?

==> class is blue print object.

==> class is a userdefined datatype.

==> class define the structure of object.

308
==> class is encapsulated with properties/attributes and behaviour/methods of object.

==> class is used to create object or class allocates memory of object.

predefined class: int,float,list,str,tuple,dict,frozenset,range,...

eg: list1=[10,20,30,40,50] ==> list

C: Python

int x; x=100 ==> int ==> class

x=100 y=1.5 ==> float ==> float

==> every datatype in python is a class and instances are objects.

Object Oriented Concepts:

1. Encapsulation

2. Polymorphism

3. Inheritance

4. class

5. object

Encapsulation:

=============

==> Encapsulation is a process binding data with related operations.

==> Encapsulation is a process of grouping data and operations which operate on that

within signle entity(class).

Adv:

Data Hiding : preventing data access from unrelated operations is called data hiding.

Adv object oriented programming:

1. Modularity ==> Encapsulation,Polymorphism,Inheritance

2. Reusability

3. Security

4. Extensibility

5. Efficiency

How to define class?

=================

309
==> define a class is creating a new datatype/userdefined datatype.

==> class is a collection of variables and methods /attributes and method/properties

and functions.

==> variables define the properties of object.

==> methods define the functionality of object.

syntax of class

============

class <class-name>:

variables

methods/member function

variables

========

==> variables declared inside a class are two types.

1. object level variables/instance variables

2. class level variable

3/8/2020
========

object level variables/instance variables

=================================

==> object properties are defined using instance variables/object level variables.

==> these variables are created in different ways.

1. constructor method __init__(self)

2. setattr() function

3. properties class

__init__(self):

==> this constructor method, this method is called automatically at the time of creating

object.

==> any method which suffix and prefix with __ is called magic method and these

310
methods are called automatically.

==> it is having first argument as self.

==> self is an argument name, which hold address of created object.

==> __init__() method refere to created object using self.

==> using self, we can create or access object level variables/instance variables.

==> object init is done using init.

==> __init__(self) contain the operations which has to be performed at the time of

creating.

eg:

class A:

def __init__(self):

print("object created")

print("object address is",self)

def main():

a1=A()

a2=A()

a3=A()

print(a1)

print(a2)

print(a3)

main()

Note: in the place of self we can use any other name.

eg:

class Student:

def __init__(self):

self.rno=0

self.name=""

def main():

stud1=Student()

311
stud2=Student()

stud1.rno=101

stud1.name="naresh"

stud2.rno=102

stud2.name="suresh"

print(stud1.rno,stud1.name)

print(stud2.rno,stud2.name)

main()

==> each object is having object level variables/instance variables.

==> object level variables/properties are accessed with object name.

eg:

class A:

def __init__(self):

self.x=100

self.y=200

def main():

print(A.x,A.y)

main()

Expl: the above code display syntax error becoz object level variables accessed with

object name not with class name and cannot accessed without creating object.

==> the variables declared inside class can be private,public or protected.

==> by default the variables are public.

==> private variables are prefix __ (double underscore)

==> protected variables are prefix _ (single underscore)

==> if variable is not prefix with underscore it is public.

eg: class A:

def __init__(self):

self.x=100

self.y=200

312
class B:

def __init__(self):

self.__x=100

self.__y=200

def main():

obj1=A()

print(obj1.x,obj1.y)

obj2=B()

print(obj2.__x,obj2.__y)

main()

==> private members are accessible by members(functions/methods) of these same

class but cannot accessible by non-members or members of other classes (OR)

cannot accessible outside the class/object.

class Student:

def __init__(self):

self.__rno=101

self.__name="naresh"

self.__course="python"

def main():

stud1=Student()

print(stud1.__rno)

print(stud1.__name)

print(stud1.__course)

list1=list()

list1.append()

main()

4/8/2020
========

313
==> private members are accessible by members(functions/methods) of these same

class but cannot accessible by non-members or members of other classes (OR)

cannot accessible outside the class/object.

class Student:

def __init__(self):

self.__rno=101

self.__name="naresh"

self.__course="python"

def main():

stud1=Student()

print(stud1.__rno)

print(stud1.__name)

print(stud1.__course)

list1=list()

list1.append()

main()

methods

========

==> a function defined inside the class is called method.

==> a method define behaviour of object.

==> a method define functionality of object.

==> methods written inside class are 3 types.

1. object level methods/instance methods

2. class level methods

3. static methods

object level methods/instance methods

================================

==> these methods are used to perform operation on object level variables.

==> these methods operate on object data.

314
==> any method defined inside class with first argument 'self' is called object level

method or instance method.

==> this method access object level variables using 'self' argument inorder to

manipulate data or to perform operations.

syntax:

def <method-name>(self,arg1,arg2,arg3,...):

statement-1

statement-2

==> this method is called with object and cannot called without creating object.

ex:

class Student:

def __init__(self):

self.__rno=101

self.__name="naresh"

self.__course="python"

def printStudent(self):

print(self.__rno)

print(self.__name)

print(self.__course)

def main():

stud1=Student()

# print(stud1.__rno)

# print(stud1.__name)

# print(stud1.__course)

stud1.printStudent()

main()

eg:

class Triangle:

def __init__(self):

315
self.__base=0.0

self.__height=0.0

def setBase(self,b):

self.__base=b

def setHeight(self,h):

self.__height=h

def findArea(self):

return self.__base*self.__height*0.5

def main():

t1=Triangle()

t1.setBase(1.5)

t1.setHeight(2.5)

t1_area=t1.findArea()

print("Area of triangle1 is ",t1_area)

t2=Triangle()

t2.setBase(2.5)

t2.setHeight(3.5)

t2_area=t2.findArea()

print("Area of triangle2 is ",t2_area)

main()

eg:

class Matrix:

def __init__(self):

self.__m=[[0,0],[0,0]]

def printMatrix(self):

for row in self.__m:

for col in row:

print(col,end=' ')

print()

316
def readMatrix(self):

for i in range(2):

for j in range(2):

self.__m[i][j]=int(input("Enter element"))

def main():

m1=Matrix()

m1.printMatrix()

m2=Matrix()

m2.printMatrix()

m1.readMatrix()

m1.printMatrix()

m2.readMatrix()

m2.printMatrix()

main()

eg:

class Stack:

def __init__(self):

self.__s=[]

self.__top=-1

def push(self,value):

self.__s.append(value)

print("element pushed")

self.__top=self.__top+1

def pop(self):

if self.__top==-1:

print("Stack is empty")

else:

value=self.__s[self.__top]

del self.__s[self.__top]

317
self.__top=self.__top-1

return value

def main():

stack1=Stack()

stack1.push(100)

stack1.push(200)

stack1.push(300)

e1=stack1.pop()

e2=stack1.pop()

print(e1)

print(e2)

main()

eg:

# constructor method with arguments

class Calculator:

def __init__(self,n1,n2):

self.__num1=n1

self.__num2=n2

def add(self):

return self.__num1+self.__num2

def sub(self):

return self.__num1-self.__num2

def multiply(self):

return self.__num1*self.__num2

def main():

calc1=Calculator(100,200)

print(calc1.add())

print(calc1.sub())

print(calc1.multiply())

318
main()

1. Write a class to find area rectangle

2. write a class to find area of circle

3. write a class to represent marks details of student and calculate total,avg and result

5/8/2020
=========

2. Write a class to find area rectangle

class Circle:

def __init__(self):

self.__r=0.0

def setR(self,r): # argument local variable

self.__r=r

def findArea(self):

return 3.147*self.__r*self.__r

def main():

circle1=Circle()

circle1.setR(1.2)

area1=circle1.findArea()

print("Area of circle is ",area1)

main()

1. Write a class to find area rectangle

class Rectangle:

def __init__(self):

self.__l=0.0

self.__b=0.0

def setL(self,l):

self.__l=l

def setB(self,b):

319
self.__b=b

def findArea(self):

return self.__l*self.__b

def main():

rect1=Rectangle()

rect1.setL(1.5)

rect1.setB(2.5)

area1=rect1.findArea()

print("Area of rectangle ",area1)

main()

3. write a class to represent marks details of student and calculate total,avg and

result

class StudentMarks:

def __init__(self):

self.__rno=0

self.__name=""

self.__sub1=0

self.__sub2=0

def readData(self):

self.__rno=int(input("Enter rollno"))

self.__name=input("Enter name")

self.__sub1=int(input("Enter subject1"))

self.__sub2=int(input("Enter subject2"))

def printData(self):

print(f'Rollno {self.__rno}')

print(f'Name {self.__name}')

print(f'Subject1 {self.__sub1}')

print(f'Subject2 {self.__sub2}')

print(f'Total {self.__sub1+self.__sub2}')

320
print(f'Avg {(self.__sub1+self.__sub2)/2}')

if self.__sub1<40 or self.__sub2<40:

print("Result is Fail")

else:

print("Result is Pass")

def main():

n=int(input("Enter how many students"))

studentList=[]

for i in range(n):

s=StudentMarks()

s.readData()

studentList.append(s)

for stud in studentList:

stud.printData()

main()

# develop score board application

class Player:

def __init__(self):

self.__name=""

self.__score=0

def setName(self,n):

self.__name=n

def setScore(self,s):

self.__score=s

def getName(self):

return self.__name

def getScore(self):

return self.__score

def main():

321
n=int(input("Enter how many players"))

playerList=list()

for i in range(n):

p=Player()

n=input("Enter name")

s=int(input("Enter score"))

p.setName(n)

p.setScore(s)

playerList.append(p)

tot=0

for p in playerList:

tot=tot+p.getScore()

print(f'{p.getName()}--->{p.getScore()}')

print(f'Total Score -----> {tot}')

main()

6&7/8/2020
==========

class level variables and class level methods

=====================================

class level variables

=================

==> the variables declared inside the class are called class level

variable.

==> this variable is used create a property which is common

for all the objects.

==> this variable can be accessed with class name without creating

object.

eg:

322
class Account:

minBalance=5000 # class level variable, this is global to all the objects

def __init__(self,accno,cname,bal):

self.__accno=accno # object level variable/instance variable

self.__cname=cname # object level variable/instance variable

self.__bal=bal # object level variable/instance variable

def deposit(self,amt):

self.__bal=self.__bal+amt

def withdraw(self,amt):

if self.__bal-amt<Account.minBalance:

print("Insuff balance")

else:

self.__bal=self.__bal-amt

def printAccount(self):

print(f'AccountNo {self.__accno}')

print(f'CustomerName {self.__cname}')

print(f'Balance {self.__bal}')

def main():

acc1=Account(101,"suresh",50000)

acc1.printAccount()

acc1.withdraw(45000)

acc1.printAccount()

acc1.withdraw(2000)

acc2=Account(102,"kishore",6000)

main()

#find output

class A:

x=100

def __init__(self):

323
self.y=200

def main():

print(A.x) # 100

a1=A()

a2=A()

a1.x=200

a1.y=300

a2.x=400

a2.y=500

print(a1.x,a1.y)

print(a2.x,a2.y)

main()

Ouput:

200 300

400 500

==> class level variable cannot modify with object name. if we trying modify with

object name python create a variable at object level.

==> class level variable is modified with class name.

==> class level variable can access with object name but cannot modified.

class level method

===============

==> a method defined inside class with first argument as 'cls' is called class level

method.

==> this method is called with class name, without creating object.

==> 'cls' is a first argument, which hold address of class.

==> inorder to declare class level method we use a decorator called @classmethod

syntax:

@classmethod

def <method-name>(cls,arg1,arg2,arg3,...):

324
statement-1

statement-2

statement-3

==> class level methods are used in application development for creating objects.

==> class level methods are called factory methods, these methods create object

and return address.

eg:

class A:

def m1(self):

print("object level method")

@classmethod

def m2(cls):

print("class level method")

def main():

A.m2()

# A.m1() error

obj1=A()

obj1.m1()

main()

eg:

class Person:

def __init__(self,n,a):

self.name=n

self.age=a

@classmethod

def createPerson(cls,n,dob):

a=2020-dob

p=Person(n,a)

return p

325
def printPerson(self):

print(f'Name :{self.name}')

print(f'Age : {self.age}')

def main():

p1=Person("naresh",40)

p2=Person("suresh",30)

p3=Person.createPerson("kishore",1980)

p4=Person.createPerson("rajesh",1992)

p1.printPerson()

p2.printPerson()

p3.printPerson()

p4.printPerson()

main()

eg:

class Employee:

def __init__(self,eno,en,s,c):

self.__empno=eno

self.__ename=en

self.__salary=s

self.__comm=c

@classmethod

def createEmployee(cls,eno,en,s):

c=0

if s>=10000:

c=s*10/100

elif s>=5000 and s<10000:

c=s*5/100

else:

c=s*2/100

326
e=cls(eno,en,s,c)

return e

def printEmployee(self):

print(f'EmployeeNo {self.__empno}')

print(f'EmployeeName {self.__ename}')

print(f'Salary {self.__salary}')

print(f'Comm {self.__comm}')

def main():

emp1=Employee(101,"naresh",5000,100)

emp2=Employee.createEmployee(102,"suresh",9000)

emp1.printEmployee()

emp2.printEmployee()

main()

static methods

============

==> a method defined inside class without first argument as 'cls' or 'self' is called

static method.

==> this method is declared with a decorator @staticmethod.

==> this method is called with class name.

@staticmethod

def method-name(arg1,arg2,...):

statement1

statement2

class Math:

@staticmethod

def maxOfIntegers(n1,n2):

if n1>n2:

return n1

else:

327
return n2

@staticmethod

def power(n,p):

return n**p

def main():

m1=Math.maxOfIntegers(100,200)

m2=Math.power(5,2)

print("Max is ",m1)

print("Result is ",m2)

main()

8/8/2020
========

class reusability

=============

==> object oriented application is a collection of classes.

==> the content of one class can be used inside another class in

different ways.

1. composition (has-a)

2. aggregation (use-a)

3. inheritance (is-a)

composition(has-a)

===============

==> composition is a process of creating an object of one class inside another class.

==> composition is between unrelated classes.

1. one-one

2. one-many

3. many-one

4. many-many

328
# one-many

class Address:

def __init__(self):

self.__street=None

self.__city=None

def setStreet(self,st):

self.__street=st

def setCity(self,c):

self.__city=c

def getStreet(self):

return self.__street

def getCity(self):

return self.__city

class Person:

def __init__(self):

self.__name=None

self.add1=Address()

self.add2=Address()

def setName(self,n):

self.__name=n

def getName(self):

return self.__name

def main():

p1=Person()

p1.setName("naresh")

p1.add1.setStreet("S.R.Nager")

p1.add1.setCity("Hyd")

p1.add2.setStreet("M.G.Road")

p1.add2.setCity("Hyd")

329
print(p1.getName())

print(p1.add1.getStreet())

print(p1.add1.getCity())

print(p1.add2.getStreet())

print(p1.add2.getCity())

main()

# one - one

class Dept:

def __init__(self):

self.__deptno=None

self.__dname=None

def setDeptno(self,dno):

self.__deptno=dno

def setDname(self,dn):

self.__dname=dn

def getDeptno(self):

return self.__deptno

def getDeptName(self):

return self.__dname

class Employee:

def __init__(self):

self.__ename=None

self.dept=Dept()

def setName(self,n):

self.__ename=n

def getName(self):

return self.__ename

def main():

emp1=Employee()

330
emp1.setName("naresh")

emp1.dept.setDeptno(10)

emp1.dept.setDname("Sales")

print(emp1.getName())

print(emp1.dept.getDeptno())

print(emp1.dept.getDeptName())

main()

# many to one

class College:

def __init__(self):

self.__came=None

def setCname(self,cn):

self.__cname=cn

def getCname(self):

return self.__cname

class Student:

college=College() # one time (OR) class level variable

def __init__(self):

self.__rno=None

self.__name=None

def setRno(self,rno):

self.__rno=rno

def getRno(self):

return self.__rno

def setName(self,name):

self.__name=name

def getName(self):

return self.__name

def main():

331
Student.college.setCname("NIT")

stud1=Student()

stud2=Student()

stud1.setRno(101)

stud1.setName("naresh")

stud2.setRno(102)

stud2.setName("Suresh")

print(stud1.getRno())

print(stud1.getName())

print(stud2.getRno())

print(stud2.getName())

print(Student.college.getCname())

main()

# write program for many-many relation

Aggregation(Use-A)

================

In composition,

1. the lifetime of contained object is until container object is exist

2. contained object is bind with only one type.

==> In aggregation contained object is not created within

container object, it is send using methods/inject using methods.

class Engine:

def start(self):

print("Car start...")

def stop(self):

print("Car stop..")

class Car:

def __init__(self,e):

self.__e=e

332
def carStart(self):

self.__e.start()

def carStop(self):

self.__e.stop()

def main():

engine1=Engine()

car1=Car(engine1)

car1.carStart()

car1.carStop()

main()

=======================================================

class BSNLSim:

def call(self):

print("Connects to BSNL Network....")

class AirtelSim:

def call(self):

print("Connects to Airtel Network")

class Mobile:

def __init__(self):

self.__sim=None

def insert(self,s):

self.__sim=s

def call(self):

self.__sim.call()

def main():

mobile1=Mobile()

bsnlsim1=BSNLSim()

mobile1.insert(bsnlsim1)

mobile1.call()

333
airtelsim1=AirtelSim()

mobile1.insert(airtelsim1)

mobile1.call()

main()

10/8/2020
Inheritance(IS_A)

===============

==> Inheritance allows to define class that inherit all the methods and properties from

another class.

==> Inheritance allows to define new class from an existing class. new class is called

derived class(child class) and existing class is base class(parent class).

==> Ineritance allows reusability(proerties and methods) and exitensibility(modify or

extend functionality of existing class without modifing it).

==> Inheritance model is called is-relationship. It means that derived class inherit

properties and methods of base class.

syntax

======

class derivedclass(base class1,base class2,base class3,....):

prperties

methods

==>python support the following types inheritances.

1. single level inheritance

2. multi level inheritance

3. multiple inheritance

4. hierarchical inheritance

5. hybrid inheritance

# single level inheritance

# A class methods are inheritane in B

334
class A: # parent class

def m1(self):

print("m1 of A")

class B(A): # child class

def m2(self):

print("m2 of B")

def main():

objb=B()

objb.m1()

objb.m2()

main()

# single level inheritance

# derived class inherit properties of base class

class A:

def __init__(self):

self.x=100

class B(A):

def __init__(self):

self.y=200

super().__init__()

def main():

objb=B()

print(objb.x)

print(objb.y)

main()

==> inorder to inherit properties of base class , it is required to call constructor

(__init__()) method of base class within derived class.

==> if constructor method of base class is not called in derived class the properties of

base class are not inherited in derived class.

335
==> this calling is done using super().__init__() .

==> super() refere to super class/base class.

# hierarchical Inheritance

class Employee:

def __init__(self):

self.__empid=None

self.__ename=None

def setEmpid(self,eid):

self.__empid=eid

def setEname(self,en):

self.__ename=en

def getEmpid(self):

return self.__empid

def getEname(self):

return self.__ename

class SalriedEmployee(Employee):

def __init__(self):

self.__salary=None

super().__init__()

def setSalary(self,sal):

self.__salary=sal

def getSalary(self):

return self.__salary

class CommEmployee(Employee):

def __init__(self):

self.__comm=None

super().__init__()

def setComm(self,com):

self.__comm=com

336
def getComm(self):

return self.__comm

def main():

emp1=SalriedEmployee()

emp2=CommEmployee()

emp1.setEmpid(101)

emp1.setEname("rajesh")

emp1.setSalary(50000)

emp2.setEmpid(102)

emp2.setEname("kishore")

emp2.setComm(500)

print(f'{emp1.getEmpid()},{emp1.getEname()},{emp1.getSalary()}')

print(f'{emp2.getEmpid()},{emp2.getEname()},{emp2.getComm()}')

main()

This is calling base class constructor with arguments.

class Alpha:

def __init__(self,x):

self.__x=x

def getX(self):

return self.__x

class Beta(Alpha):

def __init__(self,x,y):

self.__y=y

super().__init__(x)

def getY(self):

return self.__y

def main():

b1=Beta(100,200)

print(b1.getX())

337
print(b1.getY())

main()

# private members of base class are not accessible inside derived class

class A:

def __init__(self):

self.__x=100

class B(A):

def __init__(self):

super().__init__()

def printX(self):

print(self.__x)

def main():

b1=B()

b1.printX()

main()

# public members of base class/super class are accessible inside derived class

class A:

def __init__(self):

self.x=100

class B(A):

def __init__(self):

super().__init__()

def printX(self):

print(self.x)

def main():

b1=B()

b1.printX()

main()

=====================================================================

338
class Account:

def __init__(self,accno,cname,bal):

self.__accno=accno

self.__cname=cname

self.__bal=bal

def getAccno(self):

return self.__accno

def getCname(self):

return self.__cname

def getBal(self):

return self.__bal

def setBal(self,b):

self.__bal=b

class SavingAccount(Account):

def __init__(self,accno,cname,bal,cheqfac):

self.__cheqfac=cheqfac

super().__init__(accno,cname,bal)

def deposit(self,tamt):

b=self.getBal()

b=b+tamt

self.setBal(b)

def getCheqFac(self):

return self.__cheqfac

def main():

acc1=SavingAccount(101,"ramesh",6000,True)

print(acc1.getAccno(),acc1.getCname(),acc1.getBal(),acc1.getCheqFac())

acc1.deposit(2000)

print(acc1.getAccno(), acc1.getCname(), acc1.getBal(), acc1.getCheqFac())

main()

339
Multiple inheritance

================

==> if a class derive more than one base class ,it is called multiple inheritance.

==> in multiple inheritance derived class must call the constructor of base classes.

these constructors are called with class name by sending self.

class A:

def __init__(self):

self.x=100

class B:

def __init__(self):

self.y=200

class C(A,B): # multiple inheritance

def __init__(self):

self.z=300

A.__init__(self)

B.__init__(self)

def main():

objc=C()

print(objc.x)

print(objc.y)

print(objc.z)

main()

constructor with arguments

=======================

class A:

def __init__(self,x):

self.__x=x

def getX(self):

return self.__x

340
class B:

def __init__(self,y):

self.__y=y

def getY(self):

return self.__y

class C(A,B):

def __init__(self,x,y,z):

self.__z=z

A.__init__(self,x)

B.__init__(self,y)

def getZ(self):

return self.__z

def main():

objc=C(100,200,300)

print(objc.getX(),objc.getY(),objc.getZ())

main()

11/8/2020
Hierarchical Inheritance

====================

class Person:

def __init__(self,id,name):

self.__id=id

self.__name=name

def getId(self):

return self.__id

def getName(self):

return self.__name

class Student(Person):

341
def __init__(self,id,name,course):

self.__course=course

super().__init__(id,name)

def setCourse(self,course):

self.__course=course

def getCourse(self):

return self.__course

class Teacher(Person):

def __init__(self,id,name,subject):

self.__subject=subject

super().__init__(id,name)

def getSubject(self):

return self.__subject

class AdminStaff(Person):

def __init__(self,id,name,job):

self.__job=job

super().__init__(id,name)

def getJob(self):

return self.__job

def main():

stud1=Student(101,"naresh","python")

t1=Teacher(102,"suresh","java")

ns=AdminStaff(103,"kishore","Acc")

print(stud1.getId(),stud1.getName(),stud1.getCourse())

print(t1.getId(),t1.getName(),t1.getSubject())

print(ns.getId(),ns.getName(),ns.getJob())

main()

protected members

=================

342
==> protected members are prefix single underscore _

==> private members are prefix with __

From Charan A to Everyone: 11:50 AM

so sign for our convience to remind not to use outside class

From Nilesh Deosarkar to Me: (Privately) 11:50 AM

its on programmer choice where to access it outside class

class A:

def __init__(self):

self.__x=100 # private

self._y=200 # protected

self.z=300 # public

class B(A):

def printY(self):

print(self._y)

def main():

obja=A()

print(obja._y)

print(obja.z)

main()

Method Overriding

===============

==> redefining of base class instance method or object level method within derived

class is called method overriding.

==> defining method inside derived class with same name and arguments of method

exist in base class is called method overriding.

==> method overriding allows to extend or modify functionality of base class method

inside derived class.

==> if derived class wants to have different implementation of method exists in base

class,we override method.

343
class Parent:

def eat(self): # overriden method

print("parent eat veg....")

class Child(Parent):

def eat(self): # overriding method

print("child eat non veg...")

def sleep(self):

print("child sleep")

def main():

c=Child()

c.eat() # parent eat veg

c.sleep() # child sleep

================================================

class A:

def m1(self):

print("Overriden method")

class B(A):

def m1(self):

print("Overriding method")

def main():

objb=B()

objb.m1()

main()

==================================================

class Account:

def __init__(self):

self.__accno=None

self.__bal=None

def read(self):

344
self.__accno=int(input("AccountNo :"))

self.__bal=float(input("Balance :"))

def printAcc(self):

print("AccountNo :",self.__accno)

print("Balance ",self.__bal)

class CurrentAccount(Account):

def __init__(self):

self.__creditCard=None

def read(self): # ovrrride method

super().read() # calling method of base class

self.__creditCard=input("Enter Yes/No")

def printAcc(self): # overriding method

super().printAcc() # calling method of base class

print("CreaditCard :",self.__creditCard)

def main():

acc1=CurrentAccount()

acc1.read()

acc1.printAcc()

main()

==================================================================

object class

==========

==> every class by default inherit object class.

==> object class is a base class of all class in python.

12/8/2020
object class

==========

==> every class by default inherit object class.

345
==> object class is a base class of all class in python.

__str__() : it is method of object class this method returns type and id of object. this

method called when ever we print variable. this method is called automatically

whenever we print variable.

overriding __str__ method to return string representation of object.

class Student:

def __init__(self,rno,name):

self.__rno=rno

self.__name=name

def __str__(self): # overriding __str__ method

return str(self.__rno)+","+self.__name

def main():

stud1=Student(101,"naresh")

print(stud1)

list1=list([10,20,30,40,50])

print(list1)

main()

==> override __str__ to return state of the object whenever print reference variable.

==> predefined classes like int,float,complex,list,set,dict,... override the __str__

method, becoz of that when ever we print variables of these type, it print values not

address.

class Employee:

def __init__(self,eid,en):

self.empid=eid

self.ename=en

def __str__(self):

return str(self.empid)+","+self.ename

def main():

emp1=Employee(101,"suresh")

346
print(emp1)

list1=list()

list1.append(Employee(102,"kishore"))

list1.append(Employee(103,"naresh"))

print(list1)

e1=list1[0]

print(e1)

main()

__eq__ method

============

==> it is method of object, this method by default compare

address of one object with another object and return True/False.

==> inorder to compare with values, this method is override in

userdefined class.

==> this method is called automatically when ever we use

== operator.

predefined classes like list,set,dict,.. override __eq__ method becoz it compare

values not address of object.

def main():

list1=[10,20,30,40,50]

list2=[10,20,30,40,50]

b=list1==list2

print(b)

print(id(list1))

print(id(list2))

main()

# overriding __eq__ method to compare object values/state.

class Player:

def __init__(self,pn,r):

347
self.pname=pn

self.runs=r

def __eq__(self, other):

if self.runs==other.runs:

return True

else:

return False

def main():

p1=Player('rahul',100)

p2=Player('rohit',100)

p3=Player('virat',60)

b=p1==p2 # p1.__eq__(p2)

print(b)

print(id(p1))

print(id(p2))

b=p1==p3 # p1.__eq__(p3)

print(b)

main()

class Alpha:

def __init__(self,x):

self.__x=x

def __str__(self):

return str(self.__x)

def __eq__(self, other):

if self.__x==other.__x:

return True

else:

return False

def main():

348
a1=Alpha(100)

a2=Alpha(200)

a3=Alpha(100)

print(a1,a2,a3)

b1=a1==a2

b2=a1==a3

print(b1,b2)

main()

__hash__ method of object class

==========================

==> to converting userdefined object as an hashable object

inorder to add inside set collection we need override

__hash__ method.

==> if two objects are equal according to __eq__ method

it should generate same hashcode.

==> the value used in comparing objects, the same value is

used to generate hashcode or hashvalue.

eg:

class A:

def __init__(self,x):

self.__x=x

def __str__(self):

return str(self.__x)

def __eq__(self, other):

if self.__x==other.__x:

return True

349
else:

return False

def __hash__(self):

return self.__x

def main():

obj1=A(100)

obj2=A(200)

set1=set()

set1.add(obj1)

set1.add(obj2)

for s in set1:

print(s)

main()

eg:

class Student:

def __init__(self,rno,name):

self.__rno=rno

self.__name=name

def __str__(self):

return str(self.__rno)+","+self.__name

def __eq__(self, other):

if self.__rno==other.__rno:

return True

else:

return False

def __hash__(self):

return self.__rno

def main():

studSet=set()

350
studSet.add(Student(101,"naresh"))

studSet.add(Student(102,"suresh"))

studSet.add(Student(101,"kishore"))

for s in studSet:

print(s)

main()

abstract class and abstract methods

==============================

abstractmethod

=============

==> a method without implementation is called abstract method.

==> a method without body is called abstract method.

==> abstract method define a role/protocol, which has to be

followed by derived classes.

==> inorder to declare method as abstract, we need to use

@abstractmethod decorator

==> abstract method is defined only in abstract class.

syntax:

@abstractmethod

def <method-name>(self,arg1,arg2,arg3,..):

pass

==> abstract method must override in derived class.

abstract class

============

==> abstract class is a collection of abstract methods and non abstract methods.

==> if class is derived from "ABC" class, it is called abstract base class.

==> this is predefined class and exists in "abc" module.

==> abstract class is inherited, but cannot used for creating object.

==> abstract class define abstracts,set of rules and reg which

351
has to be followed by every derived class.

import abc

class <class-name>(abc.ABC):

variables

method

eg:

from abc import *

class A(ABC):

@abstractmethod

def m1(self):

pass

def main():

obja=A()

main()

==> the above code/program display error becoz we cannot create object of

abstract base class.

eg:

from abc import *

class A(ABC):

@abstractmethod

def m1(self):

pass

def m2(self):

print("non abstract method")

class B(A):

def m3(self):

print("m2 of B")

def main():

352
objb=B()

main()

==> the above program display error becoz the class which inherit abstract base

class must override all abstract method if not, the derived calss cannot used for

creating object.

13/8/2020
=========

==> the above program display error becoz the class which inherit abstract base class

must override all abstract method if not, the derived calss cannot used for creating

object.

from abc import *

class Shape(ABC):

def __init__(self):

self._dim1=None

self._dim2=None

def read(self):

self._dim1=float(input("Enter dim1"))

self._dim2=float(input("Enter dim2"))

@abstractmethod

def findArea(self):

pass

class Triangle(Shape):

def __init__(self):

super().__init__()

def findArea(self):

return self._dim1*self._dim2*0.5

class Rectangle(Shape):

def __init__(self):

353
super().__init__()

def findArea(self):

return self._dim1*self._dim2

def main():

t1=Triangle()

t1.read()

r1=Rectangle()

r1.read()

a1=t1.findArea()

a2=r1.findArea()

print("Area of triangle ",a1)

print("Area of rectangle ",a2)

main()

==> Inheritance is process of grouping all the classes which share common properties

and behaviour.

duck typing

==========

==> Duck typing in computer programming is an application of the duck test— "If it

walks like a duck and it quacks like a duck, then it must be a duck"— to determine if an

object can be used for a particular purpose.

==> Duck typing is a concept related to dynamic typing, where the type or the class of

an object is less important than the methods it defines. When you use duck typing, you

do not check types at all. Instead, you check for the presence of a given method or

attribute.

==>Python follows the EAFP (Easier to Ask Forgiveness than Permission) rather than

the LBYL (Look Before You Leap) philosophy. The Python philosophy of EAFP is

somewhat linked to its "duck typing" style of coding.

==> Loosly Coupled Code, The code which work with any

type is called loosly coupled code.

354
class DebitCard:

def withdraw(self):

print("withdraw from debitcard")

class CreditCard:

def withdraw(self):

print("withdraw from creditcard")

class EMICard:

def withdraw(self):

print("withdraw from EMICard")

class SwappingMachine:

def swap(self,s):

s.withdraw()

class ATM:

def swap(self,s):

s.withdraw()

def main():

card1=DebitCard()

card2=CreditCard()

card3=EMICard()

s1=SwappingMachine()

a1=ATM()

s1.swap(card1)

s1.swap(card2)

s1.swap(card3)

a1.swap(card1)

a1.swap(card2)

a1.swap(card3)

main()

eg:

355
class AirtelSim:

def call(self):

print("connect to airtel network")

class BsnlSim:

def call(self):

print("connect to bsnl network")

class JioSim:

def call(self):

print("connecto Jio network")

class Mobile:

def call(self,s):

s.call()

def main():

mobile1=Mobile()

sim1=AirtelSim()

sim2=BsnlSim()

sim3=JioSim()

mobile1.call(sim1)

mobile1.call(sim2)

mobile1.call(sim3)

main()

mokey patching

============

A MonkeyPatch is a piece of Python code which extends or modifies other code at

runtime.

Monkey patching is a technique that allows you to alter the behavior of objects at

runtime.

Monkey patching is tightly related to the idea of mutability in Python.

356
14/8/2020
==========

monkey patching

=============

A MonkeyPatch is a piece of Python code which extends or modifies other code at

runtime.

Monkey patching is a technique that allows you to alter the behavior of objects at

runtime.

Monkey patching is tightly related to the idea of mutability in Python.

What is monkey patching?

Monkey patching is a technique used to dynamically update the behavior of a piece of

code at run-time.

Why use monkey patching?

It allows us to modify or extend the behavior of libraries, modules, classes or methods

at runtime without actually modifying the source code

eg:

class A:

@classmethod

def m1(cls):

print("Hello")

@classmethod

def m2(cls):

print("Bye")

def main():

A.m1()

A.m1=m2 # monkey patching

A.m1()

main()

357
eg:

class A:

def m1(self):

print("Hello")

def m2(self):

print("Bye")

def main():

obj1=A()

obj1.m1()

A.m1=m2 # monkey patching

obj1.m1()

main()

class Employee:

def __init__(self):

self.empno=None

self.ename=None

self.salary=None

self.comm=None

def readEmployee(self):

self.empno=int(input("Enter EmployeeNo"))

self.ename=input("Enter EmployeeName")

self.salary=float(input("Enter Salary"))

if self.salary>=10000:

self.comm=self.salary*10/100

elif self.salary>=5000 and self.salary<10000:

self.comm=self.salary*5/100

else:

self.comm=0

def printEmployee(self):

358
print(self.empno,self.ename,self.salary,self.comm)

#patch

def readEmployeeNew(self):

self.empno=int(input("Enter employeeno"))

self.ename=input("Enter employeename")

self.salary=float(input("Enter salary"))

if self.salary>=20000:

self.comm=self.salary*10/1000

elif self.salary>=10000 and self.salary<20000:

self.comm=self.salary*5/100

else:

self.comm=0

def main():

emp1=Employee()

emp1.readEmployee()

emp1.printEmployee()

emp2=Employee()

Employee.readEmployee=readEmployeeNew

emp2.readEmployee()

emp2.printEmployee()

Employee.readEmployee=Employee.readEmployee

emp3=Employee()

emp3.readEmployee()

emp3.printEmployee()

main()

Operator overloading

==================

==> Operator overloading allows to modify or extends functionality of existing

operators (OR) Operator overloading allows to create new operators or functions

359
which operator on userdefined datatypes.

eg:

class Integer:

def __init__(self,v):

self.value=v

def __add__(self, other):

return self.value+other.value

def __str__(self):

return str(self.value)

def __sub__(self, other):

return self.value-other.value

def __mul__(self, other):

return self.value*other.value

def main():

a=100

b=200

c=a+b

print(a,b,c)

d=a-b

print(a,b,d)

e=a*b

print(a,b,e)

n1=Integer(100)

n2=Integer(200)

n3=n1+n2

print(n1,n2,n3)

n4=n1-n2

print(n1,n2,n4)

n5=n1*n2

360
print(n1,n2,n5)

main()

==> for every operator there is equal method available in object class.

==> inorder to perform operations on userdefined type,we need operator related

methods of object class.

class Student:

def __init__(self):

self.rno=None

self.sub1=None

self.sub2=None

def readStudent(self):

self.rno=int(input("Enter any rollno"))

self.sub1=int(input("Enter subject1"))

self.sub2=int(input("Enter subject2"))

def printStudent(self):

print(self.rno,self.sub1,self.sub2)

def __eq__(self, other):

if self.sub1==other.sub1 and self.sub2==other.sub2:

return True

else:

return False

def main():

stud1=Student()

stud1.readStudent()

stud1.printStudent()

stud2=Student()

stud2.readStudent()

stud2.printStudent()

b=stud1==stud2 # stud1.__eq__(stud2)

361
print(b)

main()

operator methods

+ __add__

- __sub__

* __mul__

class Employee:

def __init__(self):

self.empno=None

self.salary=None

def readEmployee(self):

self.empno=int(input("Enter empno"))

self.salary=float(input("Enter salary"))

def printEmployee(self):

print(self.empno,self.salary)

def __add__(self, other):

return self.salary+other.salary

def main():

emp1=Employee()

emp2=Employee()

emp1.readEmployee()

emp2.readEmployee()

total=emp1+emp2

print(total)

emp1.printEmployee()

emp2.printEmployee()

main()

Method Resolution Order in python(MRO)

===================================

362
==> Method Resolution Order is an order in which python search or looks for method

in inheritance or hierarchy classes.

__mro__ ==> this attribute return method resolution order

class A:

def m1(self):

print("m1 of A")

class B(A):

def m2(self):

print("m2 of B")

class C(B):

def m3(self):

print("m3 of C")

def main():

objc=C()

objc.m1()

print(C.mro())

main()

15&17/8/2020
Exception Handling or Error Handling

===============================

==> In application development we find two types of errors.

1. syntax errors

2. runtime errors

==> If there is a syntax error within program, it cannot be executed. these error

recognized by python translator/compiler. until these errors are not rectified program

execution is not done.

eg:

print("Hello")

363
print("Bye")

if True:

print("Bye")

runtime error

===========

==> the errors which occurs during execution of program are called runtime errors.

these runtime error also called logical errors.

==> why these errors occurs becoz of wrong input given by end user.

eg:

n1=int(input("Enter first number"))

n2=int(input("Enter second number"))

n3=n1/n2

print(n1,n2,n3)

output:

Enter first number5

Enter second number2

5 2 2.5

Enter first number3

Enter second number0

Traceback (most recent call last):

File "C:/Users/admin/AppData/Local/Programs/Python/Python38-32/extest1.py", line

3, in <module>

n3=n1/n2

ZeroDivisionError: division by zero

eg:

x=int(input("enter integer value"))

print(x)

output:

enter integer value12

364
12

enter integer valueab

Traceback (most recent call last):

File "C:/Users/admin/AppData/Local/Programs/Python/Python38-32/extest2.py", line

1, in <module>

x=int(input("enter integer value"))

ValueError: invalid literal for int() with base 10: 'ab'

==> the error which occurs during the execution of program are called runtime errors

or exceptions.

==> every error is one type/class, whose object created by function and raise

generate.

==> error types can be predefined or userdefined.

==> predefined errors types are exists within predefined modules.

these types are used by predefined functions.

int() ==> ValueError

float() ==> ValueError

list() ==> TypeError

NameError,ZeroDivisionError,...

list1=list([10,20,30,40,50])

print(list1)

list2=list(10)

==> when there is an error during execution of program,

program execution is terminated. to avoid abnormal termination

of program we use exception handlers or error handlers.

need of error handling:

1. avoiding abnormal termination of program

2. separating business and error logic

exception handlers or error handlers

==============================

365
==> the following keywords are used to handler errors.

1. try

2. except

3. finally

4. raise

5. assert

all error types are inherited from exception class.

1. ValueError

Raised when an operation or function receives an argument that has the right type but

an inappropriate value

2. TypeError

Raised when an operation or function is applied to an object of inappropriate type.

The associated value is a string giving details about the type mismatch.

Passing arguments of the wrong type (e.g. passing a list when an int is expected)

should result in a TypeError.

int([10,20,30])

list(10)

3. ZeroDivisionError

Raised when the second argument of a division or modulo operation is zero.

4. IndexError

Raised when a sequence subscript is out of range

5. KeyError

KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

6. NameError

Raised when a local or global name is not found

7. exception ModuleNotFoundError

A subclass of ImportError which is raised by import when a module could not be

located

366
try block

=======

==> this block contain the statements which raise and exception.

==> this block contain the statements which has to be monitored for exception

handling.

syntax:

try:

statement-1

statement-2

except block

===========

==> except block is an error handler block. when there is an error/exception within try

block it is handled by except block.

==> try block followed by one or more except blocks.

syntax:

try:

statements which raise an exception

except <error-type>:

statement

except <error-type>:

statement

==> if try block raise/generate more than one type of exception, it is handled by using

mulitple except blocks.

eg:

def main():

x=int(input("Enter first number"))

y=int(inEnter second number"))

try:

z=x/y

367
print(z)

except ZeroDivisionError:

print("Cannot divide number with zero")

print("Complete")

main()

eg:

def main():

dict1={'java':5000,'python':4000,'c':2000,'c++':1000}

ans='yes'

while ans!='no':

key=input("Enter course name")

try:

fees=dict1[key]

print(fees)

except KeyError:

print("Course not exists")

print("You want to find for another course")

ans=input("Enter answer")

main()

try block with multiple except blocks.

==> it try block raises more than one exception, it is handled using

multiple except blocks.

def main():

try:

x=int(input("Enter x value"))

y=int(input("Enter y value"))

z=x/y

print(z)

except ZeroDivisionError:

368
print("cannot divide number with zero")

except ValueError:

print("input must be number")

main()

handling multiple types of exceptions or errors using one except block

=========================================================

==> inorder t handle multiple errors using one except block, we need to

write except block without error type.

import sys

def main():

try:

n1=int(input("Enter first number"))

n2=int(input("Enter second number"))

n3=n1/n2

print(n3)

except:

print(sys.exc_info())

t=sys.exc_info()

print(t[1])

main()

finally

=====

==> finally is not an exception/error handler.

==> it is block which is excuted after try block and except block.

==> this block contain the code which is common for try block

and except block.

==> this block is used to deallocate resources allocted within

try block.

resources: open file, establishing connection to database,network connection.

369
try:

establish connection server program # allocating resource

send message

except type:

error is handled

finally:

close connection # deallocating resource

when finally block is executed?

1. after executing try block.

2. after executing except block

3. if there is an error inside try block and not handled by except block, it execute

finally block and terminate execution program.

eg:

def main():

try:

print("inside try block")

x=int(input("enter any number"))

print(x)

except ValueError:

print("Inside except block")

finally:

print("Inside finally block")

print("Continue")

main()

18,19,20 Aug 2020


370
============
raise keyword
============
==> the raise keyword is used to generate exception by the programmer.
==> explicit generating of error is done using raise keyword.
raise exceptiontype/errortype
==> generating error object or exception object.
==> errortype can be predefined error type or userdefined error type.
eg:
import sys
def multiply(n1,n2):
if n1==0 or n2==0:
raise ValueError("Cannot multiply number with zero")
else:
return n1*n2
def main():
res1=multiply(10,2)
print(res1)
try:
res2=multiply(10,0)
print(res2)
except ValueError:
t=sys.exc_info()
print(t[1])
print(t[0])
print(t[2])
main()
eg:
import sys
def login(user,password):
if user=="nit" and password=="nit123":
return "Welcome to my application"
else:
raise ValueError("Invalid user name or password")

371
def main():
u=input("Enter Username")
p=input("Enter Password")
try:
x=login(u,p)
print(x)
except ValueError:
t=sys.exc_info()
print(t[1])
main()
custom errortypes or userdefined error types
=====================================
==> each error type is one class.
==> userdefined errortype is also class which must inherit exception class.
syntax:
class <exception-class-name>(exception):
def __init__(self):
super().__init__()
eg:
class LoginError(Exception): # user define error type
def __init__(self):
super().__init__()
def login(user,password):
if user=='nit' and password=='nit123':
return "welcome to my application"
else:
raise LoginError()
def main():
u=input("Enter username")
p=input("Enter password")
try:
r=login(u,p)
print(r)
except LoginError:

372
print("invalid user name or password")
main()
eg:
class InsuffBalError(Exception):
def __init__(self):
super().__init__()
class Account:
def __init__(self,accno,balance):
self.accno=accno
self.balance=balance
def withdraw(self,tamt):
if self.balance<tamt:
raise InsuffBalError()
else:
self.balance=self.balance-tamt
def getBalance(self):
return self.balance
def getAccno(self):
return self.accno
def main():
acc1=Account(101,5000)
print(acc1.getAccno(),acc1.getBalance())
try:
acc1.withdraw(2000)
print(acc1.getAccno(),acc1.getBalance())
acc1.withdraw(4000)
print(acc1.getAccno(),acc1.getBalance())
except InsuffBalError:
print("Balance not avl")
main()
assert keyword
=============
==> assert keyword is used for debugging code.
==> assert keyword is used to check the given condition is True or False

373
syntax:
assert test
assert test,"message"
==> if test condition is True it continue statement otherwise raises AssertionError.
==> it used by only programmer for debugging purpose.
==> after debugging these assertions are removed from program.
a=6
assert a==5
print("hello")
print("bye")
files
====
Q: What is a file?
==> file is a collection of data.
==> file is used to save the data permanently.
==> the data which is stored in RAM is temp, inorder
to persist data we use files or database.
Inorder to work with files, we need follow these steps.
1. open the file
2. write or read data
3. close file
types of files
==========
==> there are two types of files.
1. text files
2. binary files
==> text file is a collection of characters. the data is stored in character format.
==> binary file is a collection of bytes. the data will be stored in one byte format.
text files
=======
==> text file is a collection of characters. the data is stored in character format.
open()
=====
open(file, mode='r')

374
Open file and return a corresponding file object. If the file cannot be opened, an
OSError is raised.
file is a path-like object giving the pathname
mode is an optional string that specifies the mode in which the file is opened. It
defaults to 'r' which means open for reading in text mode.
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open for updating (reading and writing)
"w"
open for writing, truncating the file first. if file with name is already exists it
truncate/delete and write data.
write(s)
Write the string s to the stream and return the number of characters written.
writelines(lines)
Write a list of lines to the stream. Line separators are not added, so it is usual for each
of the lines provided to have a line separator at the end
eg: file is created in current working directory
def main():
f=open("file1.txt","w")
s="Python is a object oriented programming language"
f.write(s)
f.close()
main()
eg: file is created in give path
def main():
f=open("d:\\file1.txt","w")
s="Python is a object oriented programming language"
f.write(s)
f.close()

375
main()
eg: writing inside file using print function
def main():
f=open("student.txt","w")
ans="yes"
while ans!="no":
rno=input("Enter rollno")
name=input("Enter name")
course=input("Enter course")
print(rno,name,course,file=f)
ans=input("Add another student")
f.close()
main()
# writing more than one string
def main():
l=["keyboard\n","mouse\n","monitor\n","harddisk\n"]
f=open("file2.txt","w")
f.writelines(l)
f.close()
main()
"r"
===
open for reading (default). if file not exists it raises OSError
read(size=-1)
Read and return at most size characters from the stream as a single str. If size is
negative or None, reads until EOF.
readline(size=-1)
Read until newline or EOF and return a single str. If the stream is already at EOF, an
empty string is returned.
If size is specified, at most size characters will be read.
eg:
# reading complete file content
def main():
try:

376
f=open("file10.txt","r")
s=f.read()
print(s)
f.close()
except FileNotFoundError:
print("File not exists")
main()
eg:
# reading speficied number of characters
def main():
try:
f=open("file1.txt","r")
s=f.read(10)
print(s)
f.close()
except FileNotFoundError:
print("File not exists")
main()
# write a program to count number vowels in a given file
def main():
f=open("file1.txt","r")
count=0
while True:
ch=f.read(1)
if ch=='':
break
elif ch in "aeiouAEIOU":
count+=1
print("count of vowels ",count)
f.close()
main()
eg:
def main():
f=open("file2.txt","r")

377
l1=f.readline()
print(l1)
l2=f.readlines()
print(l2)
main()
eg: appnd to the existing file
def main():
f=open("file1.txt","a")
f.write("This is appended text")
f.close()
main()
eg: "x" mode ==> if the file is exists with given filename, it raises FileExistsError
def main():
f=open("file1.txt","x") ==> this file1.txt is exists so we can create another file with
same name
f.write("more text")
f.close()
main()
Serialization and DeSerialization (OR) “pickling” and “unpickling”.
======================================================
pickle — Python object serialization
The pickle module implements binary protocols for serializing and de-serializing a
Python object structure. “Pickling” is the process whereby a Python object hierarchy
is converted into a byte stream, and “unpickling” is the inverse operation, whereby a
byte stream (from a binary file or bytes-like object) is converted back into an object
hierarchy. Pickling (and unpickling) is alternatively known as “serialization”,
“marshalling,” or “flattening”; however, to avoid confusion, the terms used here are “pickling” and
“unpickling”.
a=100 ==> bytes ==> pickling
b=1.5 ==> bytes ==> pickling
s=Student() ==> bytes ==> pickling
object ==> bytes ==> pickling
bytes ==> object ==> unpickling
pickle module provide the following functions.

378
pickle.dump(obj, file)
Write the pickled representation of the object obj to the open file object file.
eg:
import pickle
def main():
f=open("file3","wb")
x=100
y=1.5
z=1+2j
pickle.dump(x,f) # type information , properties,data
pickle.dump(y,f)
pickle.dump(z,f)
f.close()
main()
py479.py
class Employee:
def __init__(self):
self.__empno=0
self.__ename=None
self.__salary=None
def readEmployee(self):
self.__empno=int(input("enter empno"))
self.__ename=input("enter ename")
self.__salary=float(input("enter salary"))
def printEmployee(self):
print(f'{self.__empno},{self.__ename},{self.__salary}')
py480.py ==> writing employee details into file
from py479 import Employee
from pickle import *
def main():
f=open("emp.ser","wb")
e1=Employee()
e1.readEmployee()
e2=Employee()

379
e2.readEmployee()
dump(e1,f)
dump(e2,f)
f.close()
main()
how to read these objects from file?
reading is process of converting bytes into object, this process is called
deserialization or unpickling.
pickle.load(file)
Read the pickled representation of an object from the open file object file and return
the reconstituted object hierarchy specified therein.
from pickle import *
def main():
f=open("file3","rb")
x=load(f)
y=load(f)
z=load(f)
print(x)
print(y)
print(z)
f.close()
main()
eg:
from py479 import Employee
from pickle import *
def main():
f=open("emp.ser","rb")
emp1=load(f)
emp2=load(f)
emp1.printEmployee()
emp2.printEmployee()
f.close()
main()
object ==> bytes ==> pickling/serialization

380
bytes ==> object ==> unpicking/deserialization
CSV files
========
==> CSV stands comma separated values.
==> CSV is a standard import and export format.
csv — CSV File Reading and Writing
The so-called CSV (Comma Separated Values) format is the most common import and
export format for spreadsheets and databases.
The csv module implements classes to read and write tabular data in CSV format. It
allows programmers to say, “write this data in the format preferred by Excel,” or “read
data from this file which was generated by Excel,” without knowing the precise details
of the CSV format used by Excel. Programmers can also describe the CSV formats
understood by other applications or define their own special-purpose CSV formats.
The csv module’s reader and writer objects read and write sequences. Programmers
can also read and write data in dictionary form using the DictReader and DictWriter
classes.

21/8/2020
=========
CSV files
========
==> CSV stands comma separated values.
==> CSV is a standard import and export format.
csv — CSV File Reading and Writing
The so-called CSV (Comma Separated Values) format is the most common import and
export format for spreadsheets and databases.
The csv module implements classes to read and write tabular data in CSV format. It
allows programmers to say, “write this data in the format preferred by Excel,” or “read
data from this file which was generated by Excel,” without knowing the precise details
of the CSV format used by Excel. Programmers can also describe the CSV formats
understood by other applications or define their own special-purpose CSV formats.
The csv module’s reader and writer objects read and write sequences. Programmers
can also read and write data in dictionary form using the DictReader and DictWriter
classes.

381
Reading from csv file
==================
1. open microsoft excel
2. prepare data
Empno Ename Salary Deptno
1 aaa 5000 10
2 bbb 4000 10
3 ccc 3000 20
4 ddd 7000 30
5 eee 9000 10
6 fff 8000 30
7 ggg 6700 20
8 iiii 5600 10
9 hhh 4500 20
10 kkk 3500 10
3. save the file with employee.csv ==> file type ==> csv
eg:
import csv
def main():
f=open("d:\\employee.csv","r")
r=csv.reader(f)
for row in r:
print(row)
f.close()
main()
eg:
import csv
def main():
f=open("d:\\employee.csv","r")
r=csv.reader(f)
l=list(r)
print(l)
for row in l:
print(row[2])

382
s=0
del l[0]
print(l)
for row in l:
s=s+int(row[2])
print("total is",s)
f.close()
main()
create csv file or writing into csv format
=================================
csv.writer(csvfile)
==> this function return csvwriter object.
writerow() is method of writer object which is used
to write one row/list.
import csv
def main():
f=open("sales.csv","w",newline='')
wobj=csv.writer(f)
wobj.writerow(['name','sales'])
wobj.writerow(['naresh',60000])
wobj.writerow(['suresh',80000])
wobj.writerow(['kishore',45000])
f.close()
main()
writerows() this method write more than one row,
this multiple rows are represented using nested lists.
import csv
def main():
f=open("players.csv","w",newline='')
players=[]
n=int(input("enter how many players"))
for i in range(n):
p=[]
name=input("enter name")

383
runs=int(input("enter runs"))
p.append(name)
p.append(runs)
players.append(p)
wobj=csv.writer(f)
wobj.writerows(players)
f.close()
main()
eg:
import csv
def main():
f=open("players.csv","r")
robj=csv.reader(f)
players=list(robj)
print(players)
s=0
for row in players:
s=s+int(row[1])
print("Total Score",s)
main()
class csv.DictWriter(f, fieldnames)
Create an object which operates like a regular writer but maps dictionaries onto
output rows
import csv
def main():
sales_dict={'2015':[50000,7000,90000],'2016':[70000,9000,9000],'2017':

[80000,90000],'2018':[90000]}
print(sales_dict)
f=open("sales1.csv","w")
swobj=csv.DictWriter(f,fieldnames=['2015','2016','2017','2018'])
swobj.writeheader()
swobj.writerow(sales_dict)
f.close()

384
main()

24 and 25/08/2020
class csv.DictReader(f, fieldnames=None)
Create an object that operates like a regular reader but maps the information in each row to a dict whose
keys are given by the optional fieldnames parameter.

import csv
def main():
f=open("sales1.csv","r")
d=csv.DictReader(f)
l=list(d)
print(l)
main()
JSON file
========
JSON (JavaScript Object Notation) is a lightweight data-interchange format.
It is easy for humans to read and write. It is easy for machines to parse and generate.
JSON is standard way of interchaning data between two different application and these applications are
written in same language or different language.
JSON is a text format that is completely language independent but uses conventions that are familiar
programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many
others. These properties make JSON an ideal data-interchange language.
inorder parse json data, python provide json module.
create the json file.
{"name":"naresh",
"course":["java","python"]}
save this file with student_details.json
# reading content of json file
import json
def main():
f=open("g:\\student_details.json","r")
d=json.load(f)
print(d)

385
print(d['name'])
print(d['course'])
f.close()
main()
# converting dict into json
import json
def main():
emp_dict={'empno':101,'ename':'kishore','salary':50000}
emp=json.dumps(emp_dict)
print(type(emp_dict))
print(type(emp))
print(emp_dict)
print(emp)
print(emp_dict["ename"])
main()
# writing dict into json file
import json
def main():
f=open("g:\\product.json","w")
p={'pname':'keyboard','price':3000}
json.dump(p,f)
f.close()
main()
OS module
=========
==> os module is used to interact with operating system (OR) this module allows python application to
communicate with operating system.
==> This module provides a portable way of using operating system dependent functionality.
1. creating directory or folder
os.mkdir(path)
Create a directory named path with numeric mode mode
import os
def main():
os.mkdir("g:\\folder1")

386
print("folder created")
main()
2. changing directory
os.chdir(path)
Change the current working directory to path.
3. os.getcwd()
Return a string representing the current working directory.
import os
def main():
print(os.getcwd())
os.chdir("g:\\folder1")
print(os.getcwd())
f=open("file1","w")
f.write("Hello Python")
f.close()
main()
4. os.listdir(path='.')
Return a list containing the names of the entries in the directory given by path
import os
def main():
l=os.listdir("g:\\project11am")
print(l)
print(len(l))
for name in l:
print(name)
main()
5. os.rmdir(path)
Remove (delete) the directory path. If the directory does not exist or is not empty, an FileNotFoundError
or an OSError .
import os
def main():
dname=input("Enter directory name")
try:
os.rmdir(dname)

387
print('directory deleted')
except FileNotFoundError:
print("Dictory not exists")
except OSError:
print("Directory not empty")
main()
6. os.rename(src, dst)
Rename the file or directory src to dst. If dst exists, the operation will fail with an OSError .
import os
def main():
src_name=input("Enter source file name")
dest_name=input("Enter dest file name")
os.rename(src_name,dest_name)
print("file renamed")
main()
7. os.remove(path)
Remove (delete) the file path.
import os
def main():
fname=input("Enter filename to delete")
os.remove(fname)
print("File deleted")
main()

26-08-2020
re.search(pattern, string)
Scan through string looking for the first location where the regular expression pattern produces a match,
and return a corresponding match object. Return None if no position in the string matches the pattern.
Example1:
import re
def main():
str1="python is a programming language"
m1=re.search(r'is',str1)
print(m1)

388
m2=re.search(r'the',str1)
print(m2)
print(m1.span())
print(m1.group())
main()
Example2:
import re
def main():
str1="python java python java"
m=re.search(r'java',str1)
print(m)
print(m.span())
print(m.group())
main()
re.match(pattern, string)
If zero or more characters at the beginning of string match the regular expression pattern, return a
corresponding match object. Return None if the string does not match the pattern;
re.findall(pattern, string)
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-
right, and matches are returned in the order found.
Example3:
import re
def main():
str1="python java python java python"
l=re.findall(r'java',str1)
print(l)
m=re.match(r'p',str1)
print(m)
m=re.match(r'q',str1)
print(m)
main()
The special characters which are used to represent patterns
.(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been
specified, this matches any character including a newline.

389
import re
def main():
str1="this is string\npython"
l=re.findall(r'.',str1)
print(l)
str1 = "\npython"
m=re.match(r'.',str1)
if m==None:
print("String should not start with newline")
else:
print("valid")
main()
import re
def main():
str1="python is programming"
m=re.search(r'i.',str1)
if m!=None:
print(m.group())
print(m.span())
str2="py jy ny ppy jpy"
l=re.findall(r'.y',str2)
print(l)
main()
^ (Caret.) Matches the start of the string.
import re
def main():
names=['suresh','ramesh','kishore','\nrajesh']
for name in names:
m=re.search(r'^.',name)
if m!=None:
print(name)
main()
$ Matches the end of the string or just before the newline at the end of the string
import re

390
def main():
names=['rama rao','krishna rao','ramesh','kishore']
for name in names:
m=re.search(r'..o$',name)
if m!=None:
print(name)
main()
* Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are
possible.
import re
def main():
str1='abc abb acb a bca'
l=re.findall(r'ab*',str1)
print(l)
main()
+ Causes the resulting RE to match 1 or more repetitions of the preceding RE.
? Causes the resulting RE to match 0 or 1 repetitions of the preceding RE.
{m} Specifies that exactly m copies of the previous RE should be matched
{m,n} Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match
as many repetitions as possible.
[] Used to indicate a set of characters. In a set:
匹haracters can be listed individually ['a','b','c']
紐anges of characters can be indicated by giving two characters and separating them by a '-', [A-
Z] [a-z] [0-9]
[A-Za-z0-9]
eg: date validation
def main():
d=input('input date')
m=re.search(r'[0-9]{2}-[0-9]{2}-[0-9]{4}',d)
if m!=None:
print(d,"is valid")
else:
print(d,"is invalid")
main()

391
eg: email validation
def main():
email=input("Enter mail-id")
m=re.search(r'[a-z0-9A-Z]+@[a-z]+\.[a-z]+',email)
if m!=None:
print(email,"is valid")
else:
print(email,"is invalid")
main()

27-08-2020
() ==> capture and group
Eg:
import re
def main():
str1="date of birth of a person is 01-02-2020"
m=re.search(r'([0-9]{2})-([0-9]{2})-([0-9]{4})',str1)
print(m)
print(m.group())
print(m.group(1))
print(m.group(2))
print(m.group(3))
main()
Eg:
import re
def main():
email="emailid is nareshit@gmail.com"
m=re.search(r'([a-z0-9A-Z]+)@([a-z]+\.[a-z]+)',email)
print(m.group())
print(m.group(1))
print(m.group(2))
main()
Special sequence characters or escape characters
==========================================

392
\A Matches only at the start of the string.
\b Matches the empty string, but only at the beginning or end of a word
import re
def main():
str1="the their they the"
l=re.findall(r'the',str1)
print(l)
l=re.findall(r'\bthe\b',str1)
print(l)
main()
\B Matches the empty string, but only when it is not at the beginning or end of a word
import re
def main():
str1 = "the their they the python"
l=re.findall(r'\Bthe\B',str1)
print(l)
main()
\d Matches any decimal digit; this is equivalent to [0-9].
import re
def main():
str1="python version 3.8"
m=re.search(r'\d',str1)
print(m.group())
l=re.findall(r'\d',str1)
print(l)
m=re.match(r'\d',str1)
print(m)
main()
import re
def main():
str1="mobile no 997766555"
m=re.search(r'\d{9}',str1)
print(m.group())
main()

393
\D Matches any character which is not a decimal digit
import re
def main():
str1="NareshIt MobileNO: 877665544"
l=re.findall(r'\D',str1)
print(l)
l=re.findall(r'\d',str1)
print(l)
main()
\s Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v].

28-08-2020
\s Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v].
\SMatches any character which is not a whitespace character. This is the opposite of \s.
import re
def main():
str1="python programming\nlanguage"
l=re.findall(r'\s',str1)
print(l)
l=re.findall(r'\S',str1)
print(l)
str2="python programming\tlangauge\nOOP"
l=re.findall(r'\s',str2)
print(l)
main()
\w
Matches characters considered alphanumeric in the ASCII character set; this is equivalent to [a-zA-Z0-9_].
\W Matches any character which is not a word character This is the opposite of \w
import re
def main():
uname=input("Enter username")
s=re.search(r'\W',uname)
if s==None:

394
print('valid user name')
else:
print('invalid username')
main()
\Z Matches only at the end of the string.
re.split(pattern, string, maxsplit=0)
Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit
splits occur, and the remainder of the string is returned as the final element of the list.
import re
def main():
str1="python language\npython\tscripting\vlanguage"
l=re.split(r'\s',str1)
print(l)
main()
import re
def main():
str1="python,langauge:python;scripting.lagnauge"
l=re.split(r'[,:;\.]',str1)
print(l)
main()
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the
replacement repl. If the pattern isn’t found, string is returned unchanged
import re
def main():
str1="python is a programming langauge"
str2=re.sub(r'\s','-',str1)
print(str1)
print(str2)
str3="python is\na\tprogramming\rlangauge"
str4=re.sub(r'\s'," ",str3)
print(str3)
print(str4)

395
main()
Multithreading
============
Types Applications
================
1. Single task applications
2. Multitasking applications
==> A task is an operation performed program.
==> An application or program allows to perform one operation at a time is called single task application
or program.
def task1():
print("Inside task1")
def task2():
print("Inside task2")
def task3():
print("Inside task3")
def main():
task1()
task2()
task3()
main()
==> default flow of execution is seq. until task1() execution is completed task2() is not executed.
Multitasking applications
====================
==> an application which allows to perform more than one operation or task concurrently is called
multitasking.
==> In multitasking application each task is execution in a
separate path, this is called thread.
==> threads are used to develop multitasking applications.
==> thread is independent path of execution within program.
==> thread perform operation independent of other operations.
==> threads will be executed concurrently.
==> multitasking applications uses cpu idle time or resources.
==> python provide threading module, to develop multithreading applications.

396
31 Aug 2020
Multitasking applications
====================
==> an application which allows to perform more than one operation or task concurrently is called
multitasking.
==> In multitasking application each task is execution in a
separate path, this is called thread.
==> threads are used to develop multitasking applications.
==> thread is independent path of execution within program.
==> thread perform operation independent of other operations.
==> threads will be executed concurrently.
==> multitasking applications uses cpu idle time or resources.
==> python provide threading module, to develop multithreading applications.
How to create thread?
==> A thread is created by inheriting Thread class
==> A thread is created using callable object.
1. Creating thread by inheriting thread class.
syntax:

class <thread-class-name>(Thread):
def run(self):
statements
==> inherit Thread class and provide implementation or operation by overriding run() method of Thread
class.
==> thread execution is done by calling run method.
Scheduler
========

==> Scheduler is a program, which schedule the execution threads.


==> Operating system schedule the execution threads.
1. Time Slicing
2. FIFO (First In First Out)
==> Scheduling of threads are depends on operating system.

397
from threading import *
# even thread is used for generating even numbers
class EvenThread(Thread):
def run(self):
for n in range(1,20):
if n%2==0:
print("Even :",n)

class OddThread(Thread):
def run(self):
for n in range(1,20):
if n%2!=0:
print("Odd :",n)

def main():
e1=EvenThread()
o1=OddThread()
e1.start()
o1.start()
main()
# creating thread without inheriting Thread class
# create thread object and send as target
# easy to maintain, if any chages in functionality of thread
# not required to modify thread, change only functionlaity.
from threading import *
def even():
for n in range(20):
if n%2==0:
print("Even :",n)
def odd():
for n in range(20):
if n%2!=0:
print("Odd :",n)

398
def main():
t1=Thread(target=even)
t2=Thread(target=odd)
t1.start()
t2.start()
main()
start()
Start the thread’s activity.
run()
Method representing the thread’s activity.
name
A string used for identification purposes only. It has no semantics. Multiple threads may be given the same
name. The initial name is set by the constructor.
getName()
setName()
Old getter/setter API for name; use it directly as a property instead.
from threading import *
class AlphaThread(Thread):
def run(self):
for n in range(65,91):
print(self.getName(),chr(n))

def main():
t1=AlphaThread()
t2=AlphaThread()
t1.name="Naresh"
t2.name="Ramesh"
t1.start()
t2.start()
main()
join(timeout=None) ==> interrupted method
Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called
terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
1thread ==> generating sum 10 numbers

399
2thread ==> use the sum generated 1thread
from threading import *
class SumThread(Thread):
def __init__(self):
super().__init__()
self.s=0
def run(self):
for n in range(1,20):
self.s=self.s+n

class PrintSumThread(Thread):
def __init__(self):
super().__init__()
self.st=SumThread()
def run(self):
self.st.start()
self.st.join()
print("sum is ",self.st.s)

def main():
p=PrintSumThread()
p.start()
main()
from threading import *
class HelloThread(Thread):
def run(self):
for i in range(1,10):
print("Hello")
class ByeThread(Thread):
def __init__(self):
super().__init__()
self.ht=HelloThread()
def run(self):
self.ht.start()

400
self.ht.join()
for n in range(1,10):
print("Bye")
def main():
bt=ByeThread()
bt.start()
main()
Thread Synchornization OR Thread Locking

01 sep 2020
Thread Synchornization OR Thread Locking
====================================
==> synchronization is process a thread acq lock of the object, so that other thread cannot perform operation
until this thread execution is completed.
==> when more than one thread operate on shared resource, when one thread is doing operation not
allowing another thread to peform operation is called synchronization.
==> this allows you to develop thread safe applications.
lock
===
class threading.Lock
The class implementing primitive lock objects. Once a thread has acquired a lock, subsequent attempts to
acquire it block, until it is released; any thread may release it.
acquire(blocking=True, timeout=-1)
Acquire a lock, blocking or non-blocking.
release()
Release a lock. This can be called from any thread, not only the thread which has acquired the lock.
from threading import *
class Bus:
def __init__(self):
self.seats=40
self.l=Lock()
def reservation(self,name,s):
self.l.acquire()

401
for i in range(s):
self.seats=self.seats-1
print(name,"Your seats are reserved")
print(name,"availabl seats are",self.seats)
self.l.release()
class ReserveThread(Thread):
def __init__(self,b,s,name):
super().__init__()
self.bus=b
self.n=s
self.name=name
def run(self):
self.bus.reservation(self.name,self.n)
def main():
bus1=Bus()
t1=ReserveThread(bus1,10,"hemanth")
t2=ReserveThread(bus1,5,"Nilesh")
t3=ReserveThread(bus1,10,"Niyas")
t1.start()
t2.start()
t3.start()
main()

daemon thread
=============

02 Sept 2020
daemon thread
=============

daemon

A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set
before start() is called, otherwise RuntimeError is raised

402
daemon thread is least priority thread.
this thread also called background thread.
this thread execution completed when all user thread execution is completed.

t1 t2
user thread daemon thread

t2.daemon=True
from threading import *
class Thread1(Thread):
def run(self):
for i in range(1,10):
print("Inside Thread1 ",i)
class Thread2(Thread):
def run(self):
for i in range(1,10):
print("Inside Thread2 ",i)
def main():
t1=Thread1()
t2=Thread2()
t1.daemon=True
t1.start()
t2.start()
main()
=====================================================================
Python Database Communication
==> Python is a programming language and every language is used as front end. database can be used as
backend for storing or saving data.
==> There are number of database libraries provided by database vendors inorder to communicate with
database.
python
program =============> python =======> Database
database communication

403
lib
python program ===> mysqlconnector_python ===> mysql database
python program ===> cx_Oracle ===> Oracle database
==> install mysqldatabase
https://dev.mysql.com/downloads/installer/
==> open mysQL 8.0 Command Line Client
How to create database in mysql?
==> Data will be stored inside database in the form of tables.
create database <database name>;
mysql> create database db1;
How to open created database ?
use <database-name>
mysql> use db2
Database changed
==> Every database support one langauge called SQL(Structured Query Language).
DDL (Data Definition Language)
create
alter
drop
DML (Data Manipulation Language)
insert
update
delele
DRL (Data Read Language)
select
TCL (Transaction Control langauge)
commit
rollback
how to create table?
==> inside database the data will be stored inside table.
==> table is collecton rows and columns.
create table <table-name>(<column-name> <data-type>,<column-name> <datatype>,
<column-name> <datatype>,..)
Mysql Datatypes

404
==============
int ==> integer
float ==> float
varchar ==> string
date ==> date
create table student(rollno int(5) primary key,
name varchar(20),
course varchar(20),
fee float(10,2));
How to insert values into table?
insert command is used to insert a row into database table.
insert into <table-name> values(value1,value2,value3,....)
insert into student values(101,'naresh','python',4000)
How to read data from database table?
select command used to read database database table
select * from <table-name>; ==> completed table data
select <colname>,<colname>,<colname> from <table-name>; ==> read content selected columns.
select * from student;
select rollno,name from student;
To read selected rows we can use where condition.
select * from student where rollno=101;
update command
==> inorder to replace values we use update command.
update <table-name> set <col-name>=<value>,<col-name>=<value>;
update <table-name> set <col-name>=<value> where <condition>;
delete command
=============
==> inorder to delete rows, we use delete command
delete from table-name; ==> this delete all rows
delete from table-name where <condition>; ==> delete selected rows
How python program communicate with mysql database?
==> mysql database provide a library called mysql-connector-python
pip install mysql-connector-python
Basic Steps to communicate with database.

405
1. Open Connection to Database
2. Send SQL statements( This done using cursor)
3. Get the results of SQL statements
4. close cursor
5. close connection
How to open/establish connection to database?
mysql.connector
mysql ==> package
connector ==> package
mysql.connector.connect() ==> connect() is a function, which establish connection to database and return
connection object.

03rd Sept 2020


mysql.connector.connect() ==> connect() is a function, which establish connection to database and return
connection object.

mysql.connector.connect(user="database username",password="database password",database="database


name")
eg:
import mysql.connector
def main():
cn=mysql.connector.connect(user="root",password="root",database="db2")
print("connection established")
main()
cursor
=====
==> cursor is method of MySQLConnection, this method retur/create MySQLCursor object. This object is
used to send SQL statements(DML,DDL,DRL,..).
==> MySQLCursor provide the following methods for sending SQL statements.
1. execute
2. executemany
execute()
=======

406
This method executes the given database operation (query or command). The parameters found in the tuple
or dictionary params are bound to the variables in the operation. Specify variables using %s or %(name).

syntax: execute(command/operation,params=(value,value,value,..))

# write a program insert values into student table


# write a program to store data into stuent table or register register

import mysql.connector
def main():
cn=mysql.connector.connect(user="root",password="root",database="db2")
c=cn.cursor()
cmd="insert into student values(%s,%s,%s,%s)"
rno=int(input("Enter rollno"))
name=input("Enter name")
course=input("Enter course")
fee=float(input("Enter fee"))
c.execute(cmd,params=(rno,name,course,fee))
r=c.rowcount
print(r)
cn.commit()
cn.close()
main()
===============================================================
import mysql.connector
def main():
cn=mysql.connector.connect(user="root",password="root",database="db2")
c=cn.cursor()
cmd="insert into student values(%s,%s,%s,%s)"
ans="yes"
while ans!="no":
rno=int(input("Enter rollno"))
name=input("Enter name")
course=input("Enter course")

407
fee=float(input("Enter fee"))
c.execute(cmd,params=(rno,name,course,fee))
r=c.rowcount
print(r)
ans=input("Continue yes/no")
cn.commit()
cn.close()
main()
=====================================================================
# write a program to update course and fees of student
import mysql.connector
def main():
cn=mysql.connector.connect(user="root",password="root",database="db2")
c=cn.cursor()
cmd="update student set course=%s,fee=%s where rollno=%s"
rno=int(input("Enter rollno"))
course=input("Enter new course")
f=float(input("Enter Fee"))
c.execute(cmd,(course,f,rno))
rc=c.rowcount
if rc==0:
print("no rows are updated")
else:
print("details are updated")
cn.commit()
cn.close()
main()

====================================================================
# write a program to delete row from database table

import mysql.connector
def main():
cn=mysql.connector.connect(user="root",password="root",database="db2")

408
c=cn.cursor()
cmd="delete from student where rollno=%s"
rno=int(input("Enter rollno"))
c.execute(cmd,params=(rno,))
rc=c.rowcount
if rc==0:
print("invalid rollno")
else:
print("student deleted from databse table")
cn.commit()
cn.close()
main()
=====================================================================
Reading data from database table
============================

==> select command read data from databse table and store result into cursor.
==> to read/fetch this data cursor provide the following methods.
1. fetchone()
2. fetchmany(n)
3. fetchall()
fetchone()
==> This method retrieves the next row of a query result set and returns a single sequence, or None if no
more rows are available
import mysql.connector
def main():
cn=mysql.connector.connect(database="db2",user="root",password="root")
c=cn.cursor()
cmd="select * from student"
c.execute(cmd)
row1=c.fetchone()
row2=c.fetchone()
row3=c.fetchone()
row4=c.fetchone()

409
print(row1)
print(row2)
print(row3)
print(row4)
main()

04th Sept 2020


fetchall()
=======
==> fetch all rows from cursor.
==> this method return list of tuples where each tuple in list is one row.
import mysql.connector
def main():
cn=mysql.connector.connect(database="db2",user="root",password="root")
c=cn.cursor()
cmd="select * from student"
c.execute(cmd)
rows=c.fetchall()
print(rows)
for row in rows:
rno,name,course,fee=row
print(rno,name,course,fee)
c.close()
main()

fetchmany(n)
===========
==> this required n value which is number of rows.
==> this method also return list of tuples where each tuple is one row.

import mysql.connector
def main():
cn=mysql.connector.connect(database="db2",user="root",password="root")

410
c=cn.cursor()
cmd="select * from student"
c.execute(cmd)
rows=c.fetchmany(2)
print(rows)

cn.close()
main()
AddressBook
===========
person_table
===========
name ==> varchar(20) ==> primary key
hno ==> varchar(15)
street ==> varchar(20)
city ==> varchar(20)
state ==> varchar(20)
phoneno ==> varchar(12)
*****Address Book****
1. Adding Address
2. Updating Address
3. Delete Address
4. Display Address
5. View All Addresses
6. Exit
Enter your option :
Communicating with Oracle Database
===============================
==> python uses library called cx_Oracle.
==> this library is provided oracle vendor.
==> using cx_Oracle we can able to communicate oracle database.
pip install cx_Oracle
Build one case study based on cursors and sql concepts
Already discussed in class (some photos are in mobile)

411
05th Sept 2020
Jupyter Notebook
=============
Q: What is jupyter notebook?
==> jupyter notebook is a IDE.
==> jupyter notebook is a web application which allow create documents which contain live code
,equations, visualizations and text.
==> install anacond
==> with anaconda is python distribution which is used for developing datascience related applications or
projects.
==> when anaconda is installed, with this will get,
python software, jupyter,spyder ide's
==> all datascience related tools(numpy,pandas,matplotlib,....)
numpy
======
Q: What is numpy?
==> numpy stands for numerical python.
==> numpy is an open source library.
==> numpy library provide multidim array objects.

numpy is used for,


1. Math and logical operations on arrays
2. Operations related to linear algebra.
3. Fourier Transformation

Q: What is difference between list and numpy array?

==> list is not array. it is collection where group all the objects. becoz list does not have dim. list can hold
difference types of data(hetrogenious). it is dynamic in size.

==> array is a collection of similer type data elements. array is having dim.

412
in array data is stored as scalar type(value).

==> list data is stored as objects, it occupy more space. it is not eff.
==> in array data stored is as value but not as objects, it is more eff.
How to create numpy array?
array()
=====
==> array() is predefined function which create an ndarray object.
==> ndarray is class.
==> the array created in numpy is represented as ndarray object.
array(object,dtype)
object ==> it is an array or any sequence.
dtype ==> datatype which descibe datatype of array object.
import numpy as np
a1=np.array([10,20,30,40,50])
print(a1)
print(type(a1))
[10 20 30 40 50]
<class 'numpy.ndarray'>
=========================================
a2=np.array([[10,20],[30,40]])
print(a2)
print(type(a2))
[[10 20]
[30 40]]
<class 'numpy.ndarray'>
==============================================
numpy datatypes
signed integer datatypes : +ve and -ve
int8 ==> -128 to +127
int16 ==> -32768 to +32767
int32
int64
unsigned integer datatype : +ve

413
uint8
uint16
uint32
uint64
float ==> real numbers or floating point number
float16
float 32
float64
complex ==> complex numbers
=============================================================
a3=np.array([10,20,30,40,50],dtype=np.int8)
print(a3)
[10 20 30 40 50]
=======================================================
a4=np.array([200,300,400,500],dtype=np.int8)
print(a4)
[ -56 44 -112 -12]
========================================================
a5=np.array([1.5,2.5,3.5],dtype=np.float)
print(a5)
[1.5 2.5 3.5]
========================================================
a6=np.array([10,20,30,40,50],dtype=np.float)
print(a6)
[10. 20. 30. 40. 50.]
==========================================================
a7=np.array(['naresh','suresh','rajesh'])
print(a7)
print(a7.dtype)
==========================================================
dtype() funcion is used create user defined datatype.
dtype([(fieldname,datatype),(fieldname,datatype),(fieldname,datatype)])
emptype=np.dtype([('empno','i1'),('ename','S20'),('salary','f4')])
emparray=np.array([(101,'suresh',5000.0),(102,'kishore',8000.0)],dtype=emptype)

414
print(emparray)
[(101, b'suresh', 5000.) (102, b'kishore', 8000.)]
=====================================================================
shape
=====
==> shape is a property of numpy array.
==> it is a property or attribute of numpy array object.
==> this attribute return dim of array of object.
==> it return dim as tuple.
array1=np.array([10,20,30,40,50])
array2=np.array([[10,20,30],[40,50,60]])
print(array1)
print(array2)
print(array1.shape)
print(array2.shape)
==> it is used to modify or read shape of array.
array3=np.array([10,20,30,40,50,60,70,80,90])
print(array3)
array3.shape=(3,3)
print(array3)
reshape()
========
==> reshape function modify shape and return modification as new array.
array4=np.array([10,20,30,40,50,60,70,80,90])
print(array4)
array5=array4.reshape(3,3)
print(array4)
print(array5)
ndim
====
==> this attribute return number of array dim.
array6=np.array([10,20,30,40,50])
print(array6)
print(array6.ndim)

415
array7=np.array([[10,20],[30,40]])
print(array7)
print(array7.ndim)
itemsize
=======
This attribute return the size of each item of array in bytes.
array8=np.array([10,20,30,40,50],dtype=np.int8)
print(array8)
print(array8.itemsize)
array9=np.array([1.5,2.5,3.5],dtype=np.float16)
print(array9)
print(array9.itemsize)
Indexing ans slicing
================
==> indexing allows to read only one value.
==> slicing allows to read more than one value.
==> array always follows zero based index.

07th Sept 2020


Indexing and slicing
================
==> indexing allows to read only one value.
==> slicing allows to read more than one value.
==> array always follows zero based index.
import numpy as np
a=np.array([10,20,30,40,50])
print(a[0],a[1],a[2],a[3],a[4])
a=np.array([[1,2,3],[4,5,6]])
print(a[0])
print(a[1])
print(a[0][0],a[0][1])
print(a[1][0],a[1][1])
a=np.array([1.5,2.5,3.5,4.5,5.5,6.5])

416
print(a)
print(a[1:])
print(a[1::2])
print(a[-1::-1])
... is called ellipsis operator which is used to read row or column.
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)
print(a[...,1])
print(a[...,0])
print(a[...,2])
print(a[0,...])
print(a[1,...])
print(a[2,...])
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)
print(a[...,1:])
print(a[...,0:2])
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
for row in a:
for col in row:
print(col)
====================================================================
Creating numpy array using other functons
1. empty() ==> this function create ndarray without init, with the give shape
a=np.empty([3,3],dtype=np.int)
print(a)
b=np.empty([2,3],dtype=np.int)
print(b)
==> it will create an array with unknown value.
2. zeros() ==> this function create ndarray with zero values, with given shape
a=np.zeros([3,3],dtype=np.int)
print(a)
b=np.zeros([2,4])
print(b)

417
3. ones() ==> this function create ndarray with 1 values, with given shape.
a=np.ones([3,3])
b=np.ones([3,3],dtype=np.int)
print(a)
print(b)
4. arange() ==> this function create ndarray object using range.
arange(start,stop,step,dtype=<type>)
a=np.arange(1,11)
print(a)
a.shape=(2,5)
print(a)
a.shape=(5,2)
print(a)
b=np.arange(1,11,2)
print(b)
b.shape=(5,1)
print(b)
5. linspace() : it is similer to arange(), in the place of step, we define number of elements or values. This
linespace function create ndarray object using start and stop evenly it generate values.
a=np.linspace(1,50,6)
print(a)
b=np.linspace(1,10,6)
print(b)
a.shape=(2,3)
b.shape=(3,2)
print(a)
print(b)
5. logspace() :
logspace(start,stop,num,base=10)
==> this function return ndarray object with start,stop and number of values.
==> it generate elements using log. default base 10.
a=np.logspace(1,50,5)
print(a)
=====================================================================

418
broadcasting
==> broadcasting is process of converting result martix into specific shape when perform arithmetic
operations.
==> if two arrays are with same shape, it does not perform broadcasting.
matrix1=np.array([[1,2,3],[4,5,6]])
matrix2=np.array([[5,6,7],[8,9,5]])
matrix3=matrix1+matrix2
print(matrix1)
print(matrix2)
print(matrix3)
[1,2,3 [5,6,7 [6,8,10
4,5,6] + 8,9,5] = 12,14,11]
matrix1=np.array([[1,2,3],[4,5,6]])
matrix2=np.array([1,2,3])
matrix3=matrix1+matrix2
print(matrix1)
print(matrix2)
print(matrix3)
output:
[[1 2 3]
[4 5 6]]
[1 2 3]
[[2 4 6]
[5 7 9]]

08th Sept 2020


Arithmetic Operations of numpy arrays
================================

import numpy as np

419
matrix1=np.array([[1,2,3],[4,5,6]])
matrix2=np.array([[4,5,6],[7,8,9]])
matrix3=matrix1+matrix2
print(matrix1)
print(matrix2)
print(matrix3)
matrix4=matrix1.__add__(matrix2)
print(matrix4)
==============================================================

matrix1=np.array([[1,2,3],[4,5,6]])
matrix2=np.array([[4,5,6],[7,8,9]])
matrix3=matrix1+matrix2
matrix4=matrix1-matrix2
matrix5=matrix1*matrix2
print(matrix1)
print(matrix2)
print(matrix3)
print(matrix4)
print(matrix5)
===============================================================
The following opertions belongs to string (OR) vectorized strings
add() ==> return concat of strings. it will return array by concat element wise.

array1=np.array(['abc','xyz','pqr'])
array2=np.array(['mno','bca','wqe'])
array3=np.char.add(array1,array2)
print(array1)
print(array2)
print(array3)

np.char.add ==> add() function of char, which concat array of strings.

upper() ==> return all the elements/string of array into uppercase

420
lower() ==> return all the elements/string of array into lowercase
title() ==> return all the elements/string of array convert into title case
capitalize() ==> return all the elementsstring of array convert into capitalize, first letter word is converted
uppercase.

array1=np.array(['java','python','oracle','.net'])
array2=np.char.upper(array1)
print(array1)
print(array2)
array3=np.char.lower(array2)
print(array3)
array4=np.char.capitalize(array2)
print(array4)
array5=np.array(['python language','oracle database'])
array6=np.char.title(array5)
print(array5)
print(array6)
====================================================================
Adding and removing elements from numpy array
append() ==> append the values at the end of array
nump.append(array,values,axis)
array ===> input array
values ==> list of values
axis ==> axis is row or col ==> axis-0 or axis-1
array and values are required arguments.
array1=np.array([10,20,30,40,50])
print(array1)
array2=np.append(array1,[60,70,80])
print(array2)
array3=np.array([[1,2,3],[4,5,6]])
array4=np.append(array3,[[7,8,9]],axis=0)
print(array3)
print(array4)
array5=np.append(array3,[[9,8,7],[1,2,3]],axis=1)

421
print(array5)
==============================================================
numpy.delete()
=============
numpy.delete(arr, obj, axis=None)
Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those
entries not returned by arr[obj].

09th sep 2020


numpy.where()
============

==> Return elements chosen from x or y depending on condition.


==> Reading elements from numpy array based on condition.

import numpy as np
def main():
array1=np.array([10,20,30,40,50,60,70,80,90,100])
print(array1)
array2=np.where(array1<=50)
print(array2)
array3=array1.take(array2)
print(array3)
main()

numpy.genfromtxt
===============

Load data from a text file, with missing values handled as specified.

import numpy as np
def main():
a=np.genfromtxt("d:\\studentdata.csv",dtype=None,skip_header=1,delimiter=",")

422
print(a)
for row in a:
print(row[0],row[1],row[2],row[3])
main()
numpy.tofile()
===========
Write array to a file as text or binary (default).

import numpy as np
def main():
array1=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(array1)
array1.tofile("file1",sep=",")
print("array is stored inside the file")
array2=np.loadtxt("file1",delimiter=",",dtype=np.int8)
print(array2)
array2.shape=(3,3)
print(array2)
main()

numpy.random
============
import numpy as np
def main():
a1=np.random.random(5)
print(a1)
print(a1[0],a1[1],a1[2],a1[3],a1[4])
a2=np.random.randint(10,20,(3,3))
print(a2)
a3=np.random.normal(0,1,5)
print(a3)
main()
Pandas
=======

423
pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool/library,
built on top of the Python programming language.
Pandas is a high-level data manipulation tool developed by Wes McKinney.

Pandas comes with 3 data structures.

1. Series (1-D)
2. DataFrame (2-D)
3. Panel (3-D)

10th Sep 2020


Pandas
======
==> Pandas is an open source python library or a tool which is used for data manipulation and analysis.
This is done by using data structures provided by pandas.
==> Pandas is developed on the top of numpy.
==> The name pandas is derived from the word panel data -- which represent multidim data.
==> The pandas lib is written in python language. This lib is developed in the year 2008 by the person
named McKinny. He Developed this for data analysis.
==> Pandas provide 3 data structures.
1. Series 1-D
2. DataFrame 2-D
3. Panel - 3-D
Features
========
1. It allows to load data from different sources using different formats.
==> CSV format (Comma Sep Values).
==> JSON
==> Excel or another database
2. Allows customized indexes.
3. Group by and Aggregate Operations
4. Label based slicing
5. Time Series functionality

424
6. Provide the functions for finding missing data
7. Operations for inserting and removing data rows and columns.
==> Pandas does not comes with python software.
builtins,sys,os,tkinter,io,.... default modules comes with python softwares.
==> This is third party lib. to install this.
pip install pandas
Q: What is data structure?
==> data structure define set of rules and reg for organizing of data in memory.
==> by following these rules and reg we can solve given problem easy.
Series
======
==> Series is one dim labeld array. Series can hold
any type data (integer,float,complex,string,object,...)
==> The axis labels are called index.
==> Series allows homgenious data(similer type).
==> Series size is immutable(the size of series cannot incr or descr after creation).
==> Data stored inside Series are mutable.
==> Series is a predefined datatype which is used to represent Series object.
==> Series can be created in different ways.
1. array
2. dict
3. scalar values or constants or literals.
import pandas as pd
# creating empty Series
s=pd.Series()
print(s)
==> If the datatype is not defined at the time creating Series, the default datatype is Float.
creating series using ndarray
========================
=> we can create series using numpy array.
import pandas as pd
import numpy as np
data=np.array([10,20,30,40,50])
s=pd.Series(data) # creating Series using ndarray

425
print(s)
print(data)
data=np.array(['naresh','suresh','kishore'])
s=pd.Series(data)
print(s)
==================================================================
import pandas as pd
import numpy as np
data=np.array([10,20,30,40,50])
s=pd.Series(data) # creating Series using ndarray
print(s)
print(data)
data=np.array(['naresh','suresh','kishore'])
s=pd.Series(data,index=['name1','name2','name3'])
print(s)
sales_data=np.array([10000,20000,30000,40000])
s=pd.Series(sales_data,index=[2016,2017,2018,2019])
print(s)
creating Series using dictionary
==========================
in dictionary key is customized index, which is mapped with value
import pandas as pd
dict={'java':4000,'python':5000,'C++':3000}
s1=pd.Series(dict)
print(s1)
s2=pd.Series(dict,index=['C++','java','python','oracle'])
print(s2)
==> Missing element/value is defined with NaN( Not a Number)
import pandas as pd
dict1={1:1000,2:2000,3:4000,5:5000}
s1=pd.Series(dict1)
print(s1)
s2=pd.Series(dict1,index=[10,20,30,40,50])
print(s2)

426
Creating Series using Scalar value
=============================
==> Pandas allows to create Series using Scalar value.
==> Scalar value is an individual value.
==> If index is defined this value repeated to match with length
of index.
import pandas as pd
s=pd.Series(45,index=[1,2,3,4,5])
print(s)
Accessing elements/data from Series
===============================
==> Reading elements from Series is done in different ways.
1. Using its positions
2. Using its labels/index
3. Using slicling
==> positions are default index, every element pos starts at 0.
==> custome index is called labels
import pandas as pd
import numpy as np
s1=pd.Series(np.array([100,200,300,400,500]))
print(s1)
print(s1[0],s1[1],s1[2],s1[3],sep=',')
s2=pd.Series(np.array([100,200,300,400,500]),index=['a','b','c','d','e'])
print(s2)
print(s2['a'],s2['b'],s2['c'],sep=',')
print(s2[0],s2[1],s2[2],sep=',')
#print(s2['f'])
#print(s2[10])
import pandas as pd
import numpy as np
s=pd.Series(np.array([100,200,300,400,500]),index=[0,1,2,3,4])
print(s[0],s[1],s[2])
Inoder to read more than one value we use slicing.
import pandas as pd

427
import numpy as np
s=pd.Series(np.array([10,20,30,40,50]))
print(s)
print(s[:3])
print(s[-3:])
print(s[2:4])
print(s[-1::-1])
reading more than one value using pos and indexes.
these pos or index are represented as list.
import numpy as np
import pandas as pd
s=pd.Series(np.array([10,20,30,40,50]),index=['a','b','c','d','e'])
print(s)
print(s[['a','b','e']])
print(s[[0,1,2]])
Binary Operations of Series
======================
==> Series provide the following methods to perform binary opeations.
add() ==> This method is for adding two series
sub() ==> This method is for subtract two series
mul() ==> This method is for multiplying series
sum() ==> This return sum of elements of series
prod() ==> This return product of values of elements
mean() ==> return the mean values.
div() ==> This method is used to divide two series
count() ==> return the length of series
combine_first() ==> combine two series into one
import pandas as pd
s1=pd.Series([1,2,3,4,5])
print(s1)
s2=pd.Series([6,7,8,9,10])
print(s2)
s3=s1.add(s2)
print(s3)

428
s4=s2.sub(s1)
print(s4)
s5=s1.mul(s2)
print(s5)
sr1=pd.Series([1,2,3])
sr2=pd.Series([4,5,6,7,8])
sr3=sr1.add(sr2,fill_value=0)
print(sr3)
sr4=sr1.add(1)
print(sr4)
import pandas as pd
sales_2018=pd.Series([1000,2000,3000,4000,5000,6000],index=['jan','feb','mar','apr','may','jun'])
sales_2019=pd.Series([4000,5000,6000,7000,8000,9000],index=['jan','feb','mar','apr','may','jun'])
total_sales=sales_2018.add(sales_2019)
print(sales_2018)
print(sales_2019)
print(total_sales)
diff_sales=sales_2019.sub(sales_2018)
print(diff_sales)
sales_2018.combine_first(sales_2019)
print(sales_2018)
DataFrame
=========
==> DataFrame is 2D array.
==> DataFrame allows represent data in table format
==> DataFrame is collection of rows and columns.
==> DataFrame allows custom labels for rows and columns
==> DataFrame is an imp data structure of pandas, it allows
organize data in rows and columns.
How to create DataFrame?
==> DataFrame can be created using the following methods.
1. Lists
2. dict
3. Series

429
4. numpy arrays
5. existing DataFrame
==> Pandas provide DataFrame type/class, which can be used to create DataFrame.
How to create DataFrame using lists
==============================
import pandas as pd
# creating empty dataframe
df1=pd.DataFrame()
print(df1)
# creating dataframe with one column
list1=[10,20,30,40,50]
df2=pd.DataFrame(list1)
print(df2)
# creating dataframe with multiple columns
list_courses=[['python',4000],['java',2000],['oracle',1000]]
df3=pd.DataFrame(list_courses,columns=['coursename','fees'],dtype=float)
print(df3)
# creating dataframe using dictionary
dict1={'coursename':['python','oracle','java','c','c++'],'fee':[4000,1000,2000,1000,1500]}
df4=pd.DataFrame(dict1,columns=['coursename','fee'])
print(df4)
# creating dataframe using Series
s1=pd.Series(['python','oracle','java'],index=['a','b','c'])
s2=pd.Series([4000,1000,2000],index=['a','b','c'])
dict1={'courses':s1,'fee':s2}
df5=pd.DataFrame(dict1)
print(df5)
# creating dataframe using Series
s1=pd.Series(['python','oracle','java','c','c++'])
s2=pd.Series([4000,1000,2000,1000,1500,3000,2000])
dict1={'courses':s1,'fee':s2}
df5=pd.DataFrame(dict1)
print(df5)
import pandas as pd

430
df=pd.read_csv("d:\\product.csv")
print(df)
Manipulating rows and columns
==========================
selecting column
=============
==> column is identified with the name.
==> column can be read using column name.
dataframe['column-name']
import pandas as pd
df=pd.read_csv("/content/employee.csv")
print(df)
print(df['Empno'],df['Ename'])
adding column
============
==> the new column can be added with the following syntax.
dataframe['column-name']=[column values are created using series or dict]
dict1={'coursename':['python','oracle','java','c','c++'],'fee':[4000,1000,2000,1000,1500]}
df4=pd.DataFrame(dict1,columns=['coursename','fee'])
print(df4)
df4['duration']=pd.Series([1,2,3,4,5])
print(df4)
df4['col1']=pd.Series(['one','two','three','four','five'])
print(df4)

Project: Bank Application

import tkinter as tk
from tkinter import messagebox
from time import gmtime, strftime

431
def is_number(s):
try:
float(s)
return 1
except ValueError:
return 0

def check_acc_nmb(num):
try:
fpin=open(num+".txt",'r')
except FileNotFoundError:
messagebox.showinfo("Error","Invalid Credentials!\nTry Again!")
return 0
fpin.close()
return

def home_return(master):
master.destroy()
Main_Menu()

def write(master,name,oc,pin):

if( (is_number(name)) or (is_number(oc)==0) or (is_number(pin)==0)or name==""):


messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
master.destroy()
return

f1=open("Accnt_Record.txt",'r')
accnt_no=int(f1.readline())
accnt_no+=1
f1.close()

432
f1=open("Accnt_Record.txt",'w')
f1.write(str(accnt_no))
f1.close()

fdet=open(str(accnt_no)+".txt","w")
fdet.write(pin+"\n")
fdet.write(oc+"\n")
fdet.write(str(accnt_no)+"\n")
fdet.write(name+"\n")
fdet.close()

frec=open(str(accnt_no)+"-rec.txt",'w')
frec.write("Date Credit Debit Balance\n")
frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S] ",gmtime()))+" "+oc+"
"+oc+"\n")
frec.close()

messagebox.showinfo("Details","Your Account Number is:"+str(accnt_no))


master.destroy()
return

def crdt_write(master,amt,accnt,name):

if(is_number(amt)==0):
messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
master.destroy()
return

fdet=open(accnt+".txt",'r')
pin=fdet.readline()
camt=int(fdet.readline())
fdet.close()
amti=int(amt)
cb=amti+camt

433
fdet=open(accnt+".txt",'w')
fdet.write(pin)
fdet.write(str(cb)+"\n")
fdet.write(accnt+"\n")
fdet.write(name+"\n")
fdet.close()
frec=open(str(accnt)+"-rec.txt",'a+')
frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S] ",gmtime()))+" "+str(amti)+"
"+str(cb)+"\n")
frec.close()
messagebox.showinfo("Operation Successfull!!","Amount Credited Successfully!!")
master.destroy()
return

def debit_write(master,amt,accnt,name):

if(is_number(amt)==0):
messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
master.destroy()
return

fdet=open(accnt+".txt",'r')
pin=fdet.readline()
camt=int(fdet.readline())
fdet.close()
if(int(amt)>camt):
messagebox.showinfo("Error!!","You dont have that amount left in your
account\nPlease try again.")
else:
amti=int(amt)
cb=camt-amti
fdet=open(accnt+".txt",'w')
fdet.write(pin)
fdet.write(str(cb)+"\n")

434
fdet.write(accnt+"\n")
fdet.write(name+"\n")
fdet.close()
frec=open(str(accnt)+"-rec.txt",'a+')
frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S] ",gmtime()))+" "+"
"+str(amti)+" "+str(cb)+"\n")
frec.close()
messagebox.showinfo("Operation Successfull!!","Amount Debited Successfully!!")
master.destroy()
return

def Cr_Amt(accnt,name):
creditwn=tk.Tk()
creditwn.geometry("600x300")
creditwn.title("Credit Amount")
creditwn.configure(bg="orange")
fr1=tk.Frame(creditwn,bg="blue")
l_title=tk.Message(creditwn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
l1=tk.Label(creditwn,relief="raised",text="Enter Amount to be credited: ")
e1=tk.Entry(creditwn,relief="raised")
l1.pack(side="top")
e1.pack(side="top")
b=tk.Button(creditwn,text="Credit",relief="raised",command=lambda:crdt_write(creditwn,e1.g
et(),accnt,name))
b.pack(side="top")
creditwn.bind("<Return>",lambda x:crdt_write(creditwn,e1.get(),accnt,name))

def De_Amt(accnt,name):
debitwn=tk.Tk()

435
debitwn.geometry("600x300")
debitwn.title("Debit Amount")
debitwn.configure(bg="orange")
fr1=tk.Frame(debitwn,bg="blue")
l_title=tk.Message(debitwn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
l1=tk.Label(debitwn,relief="raised",text="Enter Amount to be debited: ")
e1=tk.Entry(debitwn,relief="raised")
l1.pack(side="top")
e1.pack(side="top")
b=tk.Button(debitwn,text="Debit",relief="raised",command=lambda:debit_write(debitwn,e1.ge
t(),accnt,name))
b.pack(side="top")
debitwn.bind("<Return>",lambda x:debit_write(debitwn,e1.get(),accnt,name))

def disp_bal(accnt):
fdet=open(accnt+".txt",'r')
fdet.readline()
bal=fdet.readline()
fdet.close()
messagebox.showinfo("Balance",bal)

def disp_tr_hist(accnt):
disp_wn=tk.Tk()
disp_wn.geometry("900x600")

436
disp_wn.title("Transaction History")
disp_wn.configure(bg="orange")
fr1=tk.Frame(disp_wn,bg="blue")
l_title=tk.Message(disp_wn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
fr1=tk.Frame(disp_wn)
fr1.pack(side="top")
l1=tk.Message(disp_wn,text="Your Transaction
History:",padx=100,pady=20,width=1000,bg="blue",fg="orange",relief="raised")
l1.pack(side="top")
fr2=tk.Frame(disp_wn)
fr2.pack(side="top")
frec=open(accnt+"-rec.txt",'r')
for line in frec:
l=tk.Message(disp_wn,anchor="w",text=line,relief="raised",width=2000)
l.pack(side="top")
b=tk.Button(disp_wn,text="Quit",relief="raised",command=disp_wn.destroy)
b.pack(side="top")
frec.close()

def logged_in_menu(accnt,name):
rootwn=tk.Tk()
rootwn.geometry("1600x500")
rootwn.title("UNITED BANK-"+name)
rootwn.configure(background='orange')
fr1=tk.Frame(rootwn)
fr1.pack(side="top")
l_title=tk.Message(rootwn,text="SIMPLE BANKING\n
SYSTEM",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor
="center")
l_title.config(font=("Courier","50","bold"))

437
l_title.pack(side="top")
label=tk.Label(text="Logged in as:
"+name,relief="raised",bg="black",fg="white",anchor="center",justify="center")
label.pack(side="top")
img2=tk.PhotoImage(file="credit.gif")
myimg2=img2.subsample(2,2)
img3=tk.PhotoImage(file="debit.gif")
myimg3=img3.subsample(2,2)
img4=tk.PhotoImage(file="balance1.gif")
myimg4=img4.subsample(2,2)
img5=tk.PhotoImage(file="transaction.gif")
myimg5=img5.subsample(2,2)
b2=tk.Button(image=myimg2,command=lambda: Cr_Amt(accnt,name))
b2.image=myimg2
b3=tk.Button(image=myimg3,command=lambda: De_Amt(accnt,name))
b3.image=myimg3
b4=tk.Button(image=myimg4,command=lambda: disp_bal(accnt))
b4.image=myimg4
b5=tk.Button(image=myimg5,command=lambda: disp_tr_hist(accnt))
b5.image=myimg5

img6=tk.PhotoImage(file="logout.gif")
myimg6=img6.subsample(2,2)
b6=tk.Button(image=myimg6,relief="raised",command=lambda: logout(rootwn))
b6.image=myimg6

b2.place(x=100,y=150)
b3.place(x=100,y=220)
b4.place(x=900,y=150)
b5.place(x=900,y=220)
b6.place(x=500,y=400)

438
def logout(master):

messagebox.showinfo("Logged Out","You Have Been Successfully Logged Out!!")


master.destroy()
Main_Menu()

def check_log_in(master,name,acc_num,pin):
if(check_acc_nmb(acc_num)==0):
master.destroy()
Main_Menu()
return

if( (is_number(name)) or (is_number(pin)==0) ):


messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
master.destroy()
Main_Menu()
else:
master.destroy()
logged_in_menu(acc_num,name)

def log_in(master):
master.destroy()
loginwn=tk.Tk()
loginwn.geometry("600x300")
loginwn.title("Log in")
loginwn.configure(bg="orange")
fr1=tk.Frame(loginwn,bg="blue")
l_title=tk.Message(loginwn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
l1=tk.Label(loginwn,text="Enter Name:",relief="raised")

439
l1.pack(side="top")
e1=tk.Entry(loginwn)
e1.pack(side="top")
l2=tk.Label(loginwn,text="Enter account number:",relief="raised")
l2.pack(side="top")
e2=tk.Entry(loginwn)
e2.pack(side="top")
l3=tk.Label(loginwn,text="Enter your PIN:",relief="raised")
l3.pack(side="top")
e3=tk.Entry(loginwn,show="*")
e3.pack(side="top")
b=tk.Button(loginwn,text="Submit",command=lambda:
check_log_in(loginwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
b.pack(side="top")
b1=tk.Button(text="HOME",relief="raised",bg="black",fg="white",command=lambda:
home_return(loginwn))
b1.pack(side="top")
loginwn.bind("<Return>",lambda
x:check_log_in(loginwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))

def Create():

crwn=tk.Tk()
crwn.geometry("600x300")
crwn.title("Create Account")
crwn.configure(bg="orange")
fr1=tk.Frame(crwn,bg="blue")
l_title=tk.Message(crwn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
l1=tk.Label(crwn,text="Enter Name:",relief="raised")

440
l1.pack(side="top")
e1=tk.Entry(crwn)
e1.pack(side="top")
l2=tk.Label(crwn,text="Enter opening credit:",relief="raised")
l2.pack(side="top")
e2=tk.Entry(crwn)
e2.pack(side="top")
l3=tk.Label(crwn,text="Enter desired PIN:",relief="raised")
l3.pack(side="top")
e3=tk.Entry(crwn,show="*")
e3.pack(side="top")
b=tk.Button(crwn,text="Submit",command=lambda:
write(crwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
b.pack(side="top")
crwn.bind("<Return>",lambda x:write(crwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
return

def Main_Menu():

rootwn=tk.Tk()
rootwn.geometry("1600x500")
rootwn.title("UNITED Bank")
rootwn.configure(background='orange')
fr1=tk.Frame(rootwn)
fr1.pack(side="top")
bg_image = tk.PhotoImage(file ="pile1.gif")
x = tk.Label (image = bg_image)
x.place(y=-400)
l_title=tk.Message(text="SIMPLE BANKING\n
SYSTEM",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor
="center")
l_title.config(font=("Courier","50","bold"))

441
l_title.pack(side="top")
imgc1=tk.PhotoImage(file="new.gif")
imglo=tk.PhotoImage(file="login.gif")
imgc=imgc1.subsample(2,2)
imglog=imglo.subsample(2,2)

b1=tk.Button(image=imgc,command=Create)
b1.image=imgc
b2=tk.Button(image=imglog,command=lambda: log_in(rootwn))
b2.image=imglog
img6=tk.PhotoImage(file="quit.gif")
myimg6=img6.subsample(2,2)

b6=tk.Button(image=myimg6,command=rootwn.destroy)
b6.image=myimg6
b1.place(x=800,y=300)
b2.place(x=800,y=200)
b6.place(x=920,y=400)

rootwn.mainloop()

Main_Menu()

Project: Employee Record


#Employee Record System
from tkinter import*
from tkinter import messagebox
from openpyxl import load_workbook
import xlrd
import pandas as pd

442
root=Tk() #Main window
f=Frame(root)
frame1=Frame(root)
frame2=Frame(root)
frame3=Frame(root)
root.title("Simple Employee Record System")
root.geometry("830x395")
root.configure(background="Black")

scrollbar=Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)

firstname=StringVar() #Declaration of all variables


lastname=StringVar()
id=StringVar()
dept=StringVar()
designation=StringVar()
remove_firstname=StringVar()
remove_lastname=StringVar()
searchfirstname=StringVar()
searchlastname=StringVar()
sheet_data=[]
row_data=[]

def emp_dict(*args): #To add a new entry and check if entry already exist in excel sheet
#print("done")
workbook_name="sample.xlsx"
workbook=xlrd.open_workbook(workbook_name)
worksheet=workbook.sheet_by_index(0)

wb=load_workbook(workbook_name)
page=wb.active

p=0

443
for i in range(worksheet.nrows):
for j in range(worksheet.ncols):
cellvalue=worksheet.cell_value(i,j)
print(cellvalue)
sheet_data.append([])
sheet_data[p]=cellvalue
p+=1
print(sheet_data)
fl=firstname.get()
fsl=fl.lower()
ll=lastname.get()
lsl=ll.lower()
if (fsl and lsl) in sheet_data:
print("found")
messagebox.showerror("Error","This Employee already exist")
else:
print("not found")
for info in args:
page.append(info)
messagebox.showinfo("Done","Successfully added the employee record")

wb.save(filename=workbook_name)

def add_entries(): #to append all data and add entries on click the button
a=" "
f=firstname.get()
f1=f.lower()
l=lastname.get()
l1=l.lower()
d=dept.get()
d1=d.lower()
de=designation.get()
de1=de.lower()
list1=list(a)

444
list1.append(f1)
list1.append(l1)
list1.append(d1)
list1.append(de1)
emp_dict(list1)

def add_info(): #for taking user input to add the enteries


frame2.pack_forget()
frame3.pack_forget()
emp_first_name=Label(frame1,text="Enter first name of the employee: ",bg="red",fg="white")
emp_first_name.grid(row=1,column=1,padx=10)
e1=Entry(frame1,textvariable=firstname)
e1.grid(row=1,column=2,padx=10)
e1.focus()
emp_last_name=Label(frame1,text="Enter last name of the employee: ",bg="red",fg="white")
emp_last_name.grid(row=2,column=1,padx=10)
e2=Entry(frame1,textvariable=lastname)
e2.grid(row=2,column=2,padx=10)
emp_dept=Label(frame1,text="Select department of employee: ",bg="red",fg="white")
emp_dept.grid(row=3,column=1,padx=10)
dept.set("Select Option")
e4=OptionMenu(frame1,dept,"Select Option","IT","Operations","Sales")
e4.grid(row=3,column=2,padx=10)
emp_desig=Label(frame1,text="Select designation of Employee: ",bg="red",fg="white")
emp_desig.grid(row=4,column=1,padx=10)
designation.set("Select Option")
e5=OptionMenu(frame1,designation,"Select Option","Manager","Asst Manager","Project
Manager","Team Lead","Senior Tester",
"Junior Tester","Senior Developer","Junior Developer","Intern")
e5.grid(row=4,column=2,padx=10)
button4=Button(frame1,text="Add entries",command=add_entries)
button4.grid(row=5,column=2,pady=10)

445
frame1.configure(background="Red")
frame1.pack(pady=10)

def clear_all(): #for clearing the entry widgets


frame1.pack_forget()
frame2.pack_forget()
frame3.pack_forget()

def remove_emp(): #for taking user input to remove enteries


clear_all()
emp_first_name=Label(frame2,text="Enter first name of the employee",bg="red",fg="white")
emp_first_name.grid(row=1,column=1,padx=10)
e6=Entry(frame2,textvariable=remove_firstname)
e6.grid(row=1,column=2,padx=10)
e6.focus()
emp_last_name=Label(frame2,text="Enter last name of the employee",bg="red",fg="white")
emp_last_name.grid(row=2,column=1,padx=10)
e7=Entry(frame2,textvariable=remove_lastname)
e7.grid(row=2,column=2,padx=10)
remove_button=Button(frame2,text="Click to remove",command=remove_entry)
remove_button.grid(row=3,column=2,pady=10)
frame2.configure(background="Red")
frame2.pack(pady=10)

def remove_entry(): #to remove entry from excel sheet


rsf=remove_firstname.get()
rsf1=rsf.lower()
print(rsf1)
rsl=remove_lastname.get()
rsl1=rsl.lower()
print(rsl1)
workbook_name="sample.xlsx"
path="sample.xlsx"

446
wb = xlrd.open_workbook(path)
sheet = wb.sheet_by_index(0)

for row_num in range(sheet.nrows):


row_value = sheet.row_values(row_num)
if (row_value[1]==rsf1 and row_value[2]==rsl1):
print(row_value)
print("found")
file="sample.xlsx"
x=pd.ExcelFile(file)
dfs=x.parse(x.sheet_names[0])
dfs=dfs[dfs['First Name']!=rsf]
dfs.to_excel("sample.xlsx",sheet_name='Employee',index=False)
messagebox.showinfo("Done","Successfully removed the Employee record")
clear_all()

def search_emp(): #can implement search by 1st name,last name,emp id, designation
clear_all()
emp_first_name=Label(frame3,text="Enter first name of the employee",bg="red",fg="white") #to take
user input to seach
emp_first_name.grid(row=1,column=1,padx=10)
e8=Entry(frame3,textvariable=searchfirstname)
e8.grid(row=1,column=2,padx=10)
e8.focus()
emp_last_name=Label(frame3,text="Enter last name of the employee",bg="red",fg="white")
emp_last_name.grid(row=2,column=1,padx=10)
e9=Entry(frame3,textvariable=searchlastname)
e9.grid(row=2,column=2,padx=10)
search_button=Button(frame3,text="Click to search",command=search_entry)
search_button.grid(row=3,column=2,pady=10)

frame3.configure(background="Red")
frame3.pack(pady=10)

447
def search_entry():
sf=searchfirstname.get()
ssf1=sf.lower()
print(ssf1)
sl=searchlastname.get()
ssl1=sl.lower()
print(ssl1)
path="sample.xlsx"
wb = xlrd.open_workbook(path)
sheet = wb.sheet_by_index(0)

for row_num in range(sheet.nrows):


row_value = sheet.row_values(row_num)
if (row_value[1]==ssf1 and row_value[2]==ssl1):
print(row_value)
print("found")
messagebox.showinfo("Done","Searched Employee Exist")
clear_all()
#else:
if(row_value[1]!=ssf1 and row_value[2]!=ssl1):
print("Not found")
messagebox.showerror("Sorry","Employee Record does not Exist")
clear_all()

#Main window buttons and labels

label1=Label(root,text="SIMPLE EMPLOYEE RECORD SYSTEM")


label1.config(font=('Italic',16,'bold'), justify=CENTER, background="Orange",fg="Yellow",
anchor="center")
label1.pack(fill=X)

label2=Label(f,text="Select an action: ",font=('bold',12), background="Black", fg="White")

448
label2.pack(side=LEFT,pady=10)
button1=Button(f,text="Add", background="Brown", fg="White", command=add_info, width=8)
button1.pack(side=LEFT,ipadx=20,pady=10)
button2=Button(f,text="Remove", background="Brown", fg="white", command=remove_emp, width=8)
button2.pack(side=LEFT,ipadx=20,pady=10)
button3=Button(f,text="Search", background="Brown", fg="White", command=search_emp, width=8)
button3.pack(side=LEFT,ipadx=20,pady=10)
button6=Button(f,text="Close", background="Brown", fg="White", width=8, command=root.destroy)
button6.pack(side=LEFT,ipadx=20,pady=10)
f.configure(background="Black")
f.pack()

root.mainloop()

449

You might also like