0% found this document useful (0 votes)
4 views233 pages

Python Complete Book

This document provides a comprehensive guide on Python installation, file creation, naming conventions, keywords, identifiers, tokens, and variables. It includes step-by-step instructions for downloading Python, using IDLE, and understanding the rules for naming and declaring variables. Additionally, it covers various types of tokens in Python programming, such as literals, constants, keywords, identifiers, and operators.

Uploaded by

anapatisahasra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views233 pages

Python Complete Book

This document provides a comprehensive guide on Python installation, file creation, naming conventions, keywords, identifiers, tokens, and variables. It includes step-by-step instructions for downloading Python, using IDLE, and understanding the rules for naming and declaring variables. Additionally, it covers various types of tokens in Python programming, such as literals, constants, keywords, identifiers, and operators.

Uploaded by

anapatisahasra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python

Notes
By

Venkat Reddy
(Python Trainer)

2nd Floor, Sri Sai Arcade, Beside Aditya Trade Centre, Ameerpet,
Hyderabad- Telengana State, PIN-500 038. INDIA
IND: +91 9100920092 , +91 9100940094
Python Download and Installation
Open [Link] website in web
browser.
Select "Downloads" and click on Python 3.8.2
Button.

Once you download you can see a icon like

Double click on the icon to install the python.


1st Screen

PythonwithVenkat@[Link] [Link] Page 1


Note: Add Python3.8 to path check box must be
checked. If thisoption is not available simply click on
Install Now.
2nd Screen

3rd Screen

Congrats you have Installed Python Successful.

PythonwithVenkat@[Link] [Link] Page 2


Steps to Create a python File and run
Note: I am Using Python IDLE
1. IDLE stands for Integrated Development and
Learning Environment or Language
Environment.
2. In your computer open "start" menu and search for
"IDLE" and open.

3. In IDLE menu select "File" and "New File" and write


theprogram into the new file

4. Save the above file, (While saving we can give any


name but the extension must be ".py" only)

Note: Save the python files properly into a particular


location.
".py" stands for Python File.

PythonwithVenkat@[Link] [Link] Page 3


5. To run the above program press "F5" (Function key
fromkeyboard)
6. Output of the above program

Note:
Python Installation Process :
[Link]

PythonwithVenkat@[Link] [Link] Page 4


Naming Styles

Type Naming Convention Examples


Function Use a lowercase word or words. function,
Separate words by underscores to
my_function
improve readability.
Variable Use a lowercase single letter, word, x,
or words. Separate words with
var, my_variable
underscores to improve readability.

Class Start each word with a capital Model,


letter. Do not separate words with
MyClass
underscores. This style is called
camel case.

Method Use a lowercase word or words. class_method,


Separate words with underscores to
method
improve readability.

Constant Use an uppercase single letter, CONSTANT,


word, or words. Separate words
MY_CONSTANT,
with underscores to for readability.
MY_LONG_CONSTAN
T

Module Use a short, lowercase word or [Link],


words. Separate words with
my_module.py
underscores to improve readability.

Package Use a short, lowercase word or package,


words. Do not separate words with
mypackage
underscores.

PythonwithVenkat@[Link] [Link] Page 5


Keywords
Keywords are reserved words by python do define the syntax of aprogram.

In python as per 3.9 version we have 36 keywords.

Out of 36 keywords 3 keywords like False, True and None will begin with
capital letter and rest of the 33 keywords will begin with smallletter.

Note: Keywords may change from version to version.

To view list of Keywords in python IDLE type the program as,

import keyword
print([Link])

save the above program and run it.

Identifier
Identifier is a name given to an entity like Class, Function (or)Method
and Variable.

To define an identifier we have to follow the below given rules.

1) Identifier must begin with an alphabet or an underscore ( _ ).


2) Identifier can contain
i) Capital or Small Alphabets ( a to z or A to Z)
ii) Digits from 0 to 9
iii) Only One special that is underscore ( _ ).
3) Identifier should not match with keywords.
4) Identifier should not be separated with white space.

PythonwithVenkat@[Link] [Link] Page 6


Chapter-2
Tokens

PythonwithVenkat@[Link] [Link] Page 7


Tokens

Smallest part of programming or an individual part of programming is


called token
Python Program is a combination of Tokens
Tokens are the various program elements which are used to develop
Python Program.
Different types of tokens are:
1. Literals
2. Constants
3. Keywords
4. Identifiers
5. Operators

1. Literals

Literal is a value, which can be modified

Types of Literals:

I. Integer Literal : Ex:- 10, 200, -500 , etc..


II. Floating point : Ex:- 2.5, 62.54, - 2.546
III. String Literal : Ex:- “Python”, “Venkat Tech”
IV. Boolean Literal : Ex:- True, False

Identify Literal type


i) 25 ii) 2.76 iii) ‘x’
iv) “Venkat Technology” v) 3.4e vi) True
vii) 3.545454 viii) 7-1/4a ix) 02-Nov-1989
x) false

2. Constant

Constant is a value, which cannot be modified


Ex:- PI = 3.141
MAX_MARKS = 100

PythonwithVenkat@[Link] [Link] Page 8


3. Keywords

Keywords are the Predefined words given by Python


Keywords are used to create programming syntax
In Python, we have 35 keywords
>>>import keyword
>>> print([Link])
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not',
'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

4. Identifiers
The name in python program is called as identifier
It can be variable name or function name or method name or class
name or module name or package name
1) Identifiers can have alphabets, digits and underscore. The other
characters are not allowed

Ex: id1 ---- Valid id@1 ---- Invalid

Id_1 ---- Valid customer_name$ ---- Invalid


2) It doesn’t accept any spaces

Ex: - Customer name ---- Invalid


3) Identifier should start with either an alphabet or underscore but
not digit

Ex: _id1 = 100 ---- valid 1_id =100 ---- Invalid

Id_1 = 100 ---- valid


4) Don’t use keywords as Identifier

Ex: for = 101 ---- Invalid

Id = 101 ---- Valid


5. Operators
An operator is used to perform operation on operands
An operand may be literal or variable

PythonwithVenkat@[Link] [Link] Page 9


Ex:-
a+b ‘+’ is Operator, a, b are operands
m*n ‘*’ is Operator

Case Study:

1) Identify the Tokens in following Program

PI = 3.14

r = 5.2

area = circle_Area()

print(area)

def circle_Area():

a = PI * r * r

return a

Keyword Identifiers Constant Literals Operators

PythonwithVenkat@[Link] [Link] P a g e 10
Chapter-3
Variables

PythonwithVenkat@[Link] [Link] P a g e 11
Variables and data types
Variable:
Name of the memory location is called variable
Variable is used to store the data

Rules to declare variables:


1. Variable name must begin with an alphabet or an underscore.
2. Variable name must not consists of spaces
3. Variable name must not consist of special characters except
underscore.
4. Variable name must not be a keyword.

Initialization:
Assigning value to variable is called as Initialization
We can Assign data in variables by using Assignement Operator(=)
Assigning value means storing data in variables
Syntax:

 For assignment operator left side always Variable and right side
always value
 Right side data will store into left side variable
Ex:-
age = 25
cost = 750.35
ename = “Vishnu”
gender = ‘m’
height = 5.2

PythonwithVenkat@[Link] [Link] P a g e 12
Syntax2:

Ex:- a = 20
b = a
c = a+b
Identify the Invalid Variables
Ex:- a = 20
min balance = 5000
account_number = 100012
pin = 1234
course-name = “Java”
p+id = 121
emp_name = “Vishnu”
20 = a
_eid = 1001
What will happen when we modify the variable value?
Ans: Whenever we modify the variable value then its previous value is
erased and new value is stored in variable
bill = 500
bill = 650
Now value of bill is : 650
Programs:
1) a = 10
a = 20
What is the value of a = ?

PythonwithVenkat@[Link] [Link] P a g e 13
2) bill = 250.50
discountAmount = 50

bill = bill + discountAmount


i) Identify number of variables in above Program

ii) Identify the Variable names in above program

iii) At end of Program what is the value of bill


3) Identify In-valid declarations
i) x = 10 ii) a, b = 5, 10 iii) p, q, r = 2,6,9,7
iv) 25 = m
v) p=5
q = 10
p+q=r

PythonwithVenkat@[Link] [Link] P a g e 14
Given syntax is correct or not?
1. x = 10
2. age = 25
3. gender = M
4. rollno_ = 200
5. mno = 8074864650
6. pin no=1234
7. marks = 65.3
8. salary = 25478.35
9. pnr@no=1234567895
10. email=pythonwithvenkat@[Link]
11. phno = 8074864650
12. channelname = “pythonwithvenkat”
13. pnr_status=true
14. interest$rate = 8.2f
15. creditcard1
16. $aadharno
17. break = 10
18. Break = 10
19. 3000 = x

PythonwithVenkat@[Link] [Link] P a g e 15
1. a = 5 2. a = 5
print("a") print(a)

Output:- Output:-

3. a = 5 4. a = 5
b=6 b=6
print("a+b") print("a"+b)

Output:- Output:-

5. a = 5 6. a = 15
b=6 b=6
c=a-b
print(a+b) print(c)

Ouptut:- Output:-

7. a=5 8. a = 5
b=6 b=6
c=a+b c=a+b
print("Sum is : ",c) print(c,"is Your Result")

Output:- Output:-

9. a = 5 10. a = 5
b=6 b=6
c=a+b c=a+b
print("Sum ",c,"is your print(a,"and",b,"sum is",c)
Result")
Output:-
Output:-
11. cost = 2500 12. a = 10
discount = 10 b = 20
discountAmt = (cost /100) * a= a+b
discount b= a-b
print(discountAmt) a= a–b
print(a, “\t”, b)
Output:- Output:-

PythonwithVenkat@[Link] [Link] P a g e 16
13. a = 20 14. a = 2
a = "Venk@t Reddy" b=a
print(a) print(b)

Output:- Output:-

15. n1 = "Venkat" 16. a = "7"


n2 = "Satyha Technology" b = "9"
fname= n1+"-"+n2 c=a+b
print(fname) print(c)

Output:- Output:-

17. a = 7 20. a = 7
b=5 b=5
a=a*b c=a
b = a // b a=b
a = a // b b=c
print(a,"\t",b) print(a,"\t",b)

Output:- Output:-

21. n = 12 22. c1 = "Core"


sum = 0 c2 = " Advanced"
r = n % 10 c3 = " Python"
n = n // 10 c4 = c1 + c3 + c2 + c3
sum = sum + r print(c4)
r = n % 10
n = n // 10 Output:-
sum = sum + r
print(n,"\t",sum)

Output:-

23. a = 5 24. p = 5
b=7 q=3
a,b = b,a r=7
print(a,"\t",b) print(p,"\t",q,"\t",r)

Output:- Output:-

PythonwithVenkat@[Link] [Link] P a g e 17
25. p = 5 26. p = 5
q=3 q=3
r=7 r=7
print(p,q,r) print(p,q,r,sep=",")

Output:- Output:-
27. p = 5 28. p = 5
q=3 q=3
r=7 r=7
print(p,q,r,sep="$") print(p,q,r,sep="-->")

Output:- Output:-

29. p = 5 30. p = 5
q=3 q=3
r=7 print(p,end="\t")
print(p,q,r,sep="V") print(q)

Output: Output:-

31. p = 5 32. p = 5
q=3 q=3
print(p) print(p,end="-")
print(q) print(q)

Output:- Output:-

33. a = 2.523649 34. a = 8


print(a) print("%d"%a)

Output:- Output:-

35. a = 8 36. a = 8
b=4 b=4
print("%d%d"%(a,b)) print("%d\t%d"%(a,b))

Output:- Output:-

37. a = 41.756 38. a = 41.756


print("%f"%a) print("%.2f"%a)
Output:- Output:-

PythonwithVenkat@[Link] [Link] P a g e 18
39. a = 41.756 40. a = 41.756
print("%.4f"%a) print("%d"%a)

Output:- Output:-

41. a = 6 42. a = 6
print("A value is b=3
:{0}".format(a)) print("{0}\t{1}".format(a,b))
Output:-
Output:-

43. a = 6 44. a = 6.43


b=3 print("a={0}".format(a))
print("a={0}\tb={1}".format(b,a
)) Output:-

Output:-
1. Consider a is 5 and b is 3, store a in b, print a and b?
2. Consider a is 3 b is 2.5 print a and b?
3. Consider a is 2.3, b is 5, store sum of a,b in c, print c?
4. Consider a is "Venkat" b is "tech" store fullname in c, print c?
5. Consider a is 2, b is 5, store a and b in c, then print c?
6. Consider a is 2.3, b is 9, store a in b, print b?
7. Consider a is 5, b is 3, store sum of a,b in c,display o/p as sum is 8
8. Consider x is ‘a’, y is 5, store x in y, print x, y?
9. Consider x is 2.3, y is 3, store sum of x,y in z, print z?
10. Consider a is ‘x’, b is ‘y’, store a and b in c, print c?
11. Consider x is 5, y is 2, x divide by y store in z, print z?
12. Consider x is 5, product of x and x store in y, print y?
13. Consider x is 3, cube of x, store in y, print x,y?
14. Consider x is 3, square of x store in s,cube of x store in c print s,c?
15. Consider x is 5 , y is 3, store product of x and y in z, and sum of
x,y,z store in p, print p?

PythonwithVenkat@[Link] [Link] P a g e 19
16. Consider principlevalue is 1000/- , rateofintreset is 15%, timeperiod is
5years, Display totalamount based on simpleintrest?
17. Consider calices degree is 60 Display Foreignheat
18. Program to calculate total salary of employee.
Consider basicsalary as 10000, 30% basicsalary is hra.10%
basicsalary is da.
19. Consider 3 subject marks as 60,70,80 Display total,percentage
20. Program to calculate grosssalary and netsalary of employee.
Consider basicsalary as 10,000
30% basicsalary is hra.
10% basicsalary is da.
sum of basicsalary,da,hra is grosssalary.
deductions:
providentfund of employee is 2000.
professionaltax of employee is 200.
incometax of employee is 10 percentage of basic salary.
calculatenetsalary
formula: netsalary=grosssalary-deductions.
Display grosssalary and netsalary.
21. productcost is 1000 RS.

gst is 10% of productcost.

Calculate netprice of a product.


22. netprice of a product is 230.

gstamout is 30

calculate originalcost of product .


23. netprice of a product is 440.

gst is 10%

calculate originalcost of product.

formula:

netprice=productcost+percentage of gst on productcost.

Originalcost=(netprice*100)/(100+gst)

PythonwithVenkat@[Link] [Link] P a g e 20
Reading Values at run time:
input( ) function is used to read the values at run time from keyboard.
input( ) function always read data in String format
Syntax:
<variable_name> = input()
Ex :-
1) i=input() Output:- Venkat
print(i) Venkat

2) c=input("Enter a Course : ") Output: Enter a Course : Python


Python
print( c )
3) p = input(“Enter FName : ”) Output:
Enter FName : Venkat
q = input(“Enter LName : ”)
Enter LName : Technologies
r=p+q Venkat Technologies

print( r )
4) p = input(“Enter any no : ”) Output:
Enter any no : 5
q = input(“Enter any no : ”)
Enter any no : 7
r=p+q 57

print( r )

PythonwithVenkat@[Link] [Link] P a g e 21
Chapter-4
Type Casting

PythonwithVenkat@[Link] [Link] P a g e 22
Type Casting:
The process of converting one data type value to another data type
value is called Type casting.
Python provides various inbuilt functions for type conversion
Function Description
int(y) It converts y to an integer.

float(y) It converts y to a floating-point number.


str(y) It converts y to a string.
tuple(y) It converts y to a tuple.
list(y) It converts y to a list.
set(y) It converts y to a set.
dict(y) It creates a dictionary and y should be a
sequence of (key, value) tuples.

PythonwithVenkat@[Link] [Link] P a g e 23
int( )
It is used to convert values from other types to int
Ex1:- a = 10.4
b = int(a)
print(b)
Ex2:- a = “2”
b = int(a)
print(b)
float( )
It is used to convert values from other type to float
Ex1:- a = 10
b = float(a)
print(b)
Ex2:- a = “2.43”
b = float(a)
print(b)
bool( ):
It is used to convert values from other type to bool
Ex1:- a = 10
b = bool(a)
print(b)
Ex2:- a = 0
b = bool(a)
print(b)

PythonwithVenkat@[Link] [Link] P a g e 24
str( ) :
It is used to convert values from other type to String
Ex1:- a = 10
b = str(a)
print(b)
Ex2:- a = 1.4
b = str(a)
print(b)
chr( )
It is used to convert values from other type to character type
Ex1:- a = 97
b = chr(a)
print(b)

PythonwithVenkat@[Link] [Link] P a g e 25
Chapter-5
Operators

PythonwithVenkat@[Link] [Link] P a g e 26
Operators:

Operator is used to perform operation on operands

Types of operators:

PythonwithVenkat@[Link] [Link] P a g e 27
1. Arithmetic Operators
2. Assignment Operator
3. Relational Operators
4. Logical Operators
5. Membership Operators
6. Identity Operators

1) Arithmetic Operators:
Arithmetic operators are used for Numeric calculations (or) Arithmetic
Calculations.
In python, the following are the arithmetic operators:
Operator Operation Example
+ Addition 4+2=6
- Subtraction 4-2=2
* Multiplication 4*2=8
/ Division 4/2=2.0
// Floor Division 4//2=2
% Modulation 4%2=0
** Power 4**2=16

2) Assignment Operator(=)
Assignment operator is used to assign a value to a variable.
It is also called as Right to left operator
Syntax:
<Variable> = <Value>
Example:
p = 100
q = 50
r = p+q
In Python, we can declare multiple variables and store values into all
the variables at the same time.

PythonwithVenkat@[Link] [Link] P a g e 28
Syntax:
Variable1, Variable2, Variable3 = value1, value2, value3
Ex:-
a, b, c = 5, 10, 50
eid, ename, sal = 101, “Lakshmi”, 5000.0
Ex:-
Statement Result
a = 153 % 10
p = 153 // 10
q = 153 / 10
a = 5 + 4 * 3 – 2 ** 3
b = 2**3**2
k = 5.4 // 2
a, b, c = 6, 7
a, b = 5, 8, 2
a , b = 2+4, 5*3
a , b = 2*3, 4*5 Value of : a b c
c =a+b

3) Relational Operators
Relational operators are used for writing Conditions
Relational operators always give Boolean value as a result that
means either True or False
If the condition is true it given True otherwise False.

PythonwithVenkat@[Link] [Link] P a g e 29
Operator Meaning

< Less than

<= Less than or Equal to

== Equal to

!= Not Equal to

> Greater than

>= Greater than or Equal to

Example to Understand Relational Operators:


Consider A value is 9 and B value is 9

Expression Output (or)Result

A<B False

A <= B True

A == B True

A != B False

A>B False

A >= B True

PythonwithVenkat@[Link] [Link] P a g e 30
Ex:- Consider p value is 14 and q value is 7

Condition Result
p>q
p == q
p<q
p=q
p <= q
p >= q
p != q

Ex1: Consider a is -4 now Write the condition to check given number is


Positive or negative

Ex2: Consider m value is 15, write the condition to check given number is
divigible by 5 or not

Ex3: Consider p value is 6 write condition to check given number is Even


or odd

Ex4: Consider x value is 6 and y value is 9, now write the condition to


check big number between x and y

4) Logical Operators:

Logical operators are used for combining multiple conditions


Logical operators always give Boolean value as a result. That means
either True or False
Syntax: (condition1) and (condition2)
 Returns True when all given conditions are True
otherwise False
and
Ex:- consider 3 subject marks of a student
s1 = 90
s2 = 75

PythonwithVenkat@[Link] [Link] P a g e 31
s3 = 30
now check student is pass or fail
Condition : s1>35 and s2>35 and s3>35

Syntax: (condition1) or (condition2)


 Returns True if atlest one condition is True otherwise
False
Ex:- Central Mall announced 20% offer for customers if there
or
bill amount is morethen 5000 or card is HDFC

Condition : billAmount > 5000 or card== ‘HDFC’

Write output for following Conditions

Conditions Output
1) s1 = 80, s2 = 70, s3 = 65
s1>35 and s2>35 and s3>35
2) s1 = 80, s2 = 30, s3 = 65
s1>35 and s2>35 and s3>35
3) s1 = 25, s2 = 20, s3 = 65
s1>35 or s2>35 or s3>35
4) s1 = 25, s2 = 20, s3 = 65
s1>35 or s2>35 or s3>35
5) s1 = 70, s2 = 60, s3 = 20
s1>35 and s2>35 or s3>35
6) s1 = 26, s2 = 60, s3 = 20
s1>35 and s2>35 or s3>35
7) s1 = 26, s2 = 60, s3 = 50
s1>35 and s2>35 or s3>35
8) billamt = 6000

card = “HDFC”

billamt>=5000 and card == “SBI”

PythonwithVenkat@[Link] [Link] P a g e 32
9) billamt = 6000

card = “sbi”
billamt>=5000 and card == “SBI”
10) billamt = 6000

card = “SBI”
billamt>=5000 and card == “SBI”

11) avg = 76
avg>50 and avg<=70

6) Membership Operators:
Membership Operators are “in”, “not in”
Membership operators are used to check whether a value is available
in a sequence like String, list, set, dict, String … or not.
These operators returns either True or False, if value is available
then it returns True otherwise it returns False .
Example1:
data = “Python in Venkat Technology”
s1 = “Python”
s1 in data
Example 2 :
p = [5, 9, 8, 6, 12, 3]
a=6
a in p

PythonwithVenkat@[Link] [Link] P a g e 33
Assignments:
1) What is Operator

2) When to use Operators

3) Identify names of following operators

Operator Name

//

**

<

>=

4) When to use “//”


5) When to use “/”
6) When to use “%”
7) When to use “**”

PythonwithVenkat@[Link] [Link] P a g e 34
8) Find out the results
i) 7/4 = ii) 16 // 3 =
iii) 9%2 = iv) 4/7 =
v) 3 // 16 = vi) 2%9 =
vii) 5.0 / 2 = viii) 5.0 // 2 =

9) What is Expression
10) Find out the result
i) 5+3*2 ii) (5+3) *2
iii) 12//5*2 iv) 6+2*3//2+3
v) 6 + 4 % 2 *25 +5 vi) 10-15*3//2*5+4
vii) 3**2 viii) 3**2**3

11) When to check operator Precedence

12) How to evaluate expression If we have same precedence

PythonwithVenkat@[Link] [Link] P a g e 35
Chapter-6
Statements and Types

PythonwithVenkat@[Link] [Link] P a g e 36
Statements

Python programs are collection of Statements, statements is an


executable part of the program it will do some action.
Statements are different types, they are
 Expression Statements.
 Compound Statements.
 Selection Statements.
 Iterative Statements.
 Jump Statements.

Expression Statements:
Expression can be any operation like Arithmetic operation or Logical
Operation.
It is combination of variables, Constants, operators, Function Calls
E.g.:- x = x + 10
10 > 15
a != b

PythonwithVenkat@[Link] [Link] P a g e 37
Compound Statement:
Compound statement is combination of several expression
statements.
Compound statement is also called as Block Statement
Eg:
def fun1( ):
x = 10
y = 20
z = x+y

Selection Statements :
selection Statements are used in decisions making situations
Eg:- if, if-else, elif, …

Iterative Statements:
If we want to Execute a part of program many times we will use loops
E.g.:- while, for …

Jump Statements:
Jump statements are useful for Transfer the Control one part of
program to other part of Program

E.g.:- break, continue, pass …

Note: All these Selection and Iterative and Jump Statements are Keywords
and all are Lower Case Characters

PythonwithVenkat@[Link] [Link] P a g e 38
Chapter-7
Conditional Statements

PythonwithVenkat@[Link] [Link] P a g e 39
Control Flow Statements:
Control flow is the order in which the program’s code executes

Conditional Statements
Decision-making helps in deciding the flow of execution of the program
It simply decides whether a particular code block will be executed or
not on the basis of the condition provided in the if statement. If the condition
true, then the code block is executed, and if it’s false then the code block is
not executed.

PythonwithVenkat@[Link] [Link] P a g e 40
If statement:
If statement can be used to execute a group of statements based on
the result of a condition

Syntax:
If(codition):
Statement-1
Statement-2
Flow chart:

PythonwithVenkat@[Link] [Link] P a g e 41
Ex:
a = 5
if(a>0):
print(“Given Number is +ve Number”)
print(“Thank you”)

1) n = 5 2) n = 4
if(n%2==0): if(n%2==0):
print("Even") print("Even")
print("Thank you") print("Thank you")

Output:- Output:-
3) n = 5 4) n = -5
if(n > 0 ): if(n<0):
print("+ve") print("-ve")
print("Thank you") print("Thank you")

Output:- Output:-

PythonwithVenkat@[Link] [Link] P a g e 42
5) n = 0 6) if( 0 ):
if(n > 0 ):
print("+ve") print("Hello")
print("Thank you")
Output:- print("Thank u")

Output:-
7) if( 5 ): 8) s1 = 43

print("Hello") s2 = 57

print("Thank u") if(s1>=35 and s2 >=35):


Output:-
print("PASS")

print(“Thank you”)
Output:

9) s1 = 25 10) billAmt = 5600

s2 = 57 card = 'ICICI'

if(s1>=35 and s2 discount = 0


>=35):
if(card == 'ICICI' or
print("PASS") billAmt>=5000):

print(“Thank you”) discount = 20


Output:
print(discount)
Output:

Multiple if:-
1. x=5 2. x = 3
if(x>0): if(x>0):
print("+Ve Number") x=x-5
if(x<0): if(x<0):
print("-ve Number") x=x+3
print(x)
Output:-
Output:-

PythonwithVenkat@[Link] [Link] P a g e 43
3. d = 10 4. g = 'm'
c = 500 if(g=='m'):
b = "Venkat" print("Male")
if(c>=500): if(g=='f'):
d = d + 10 print("Female")
if(b=="Venkat"):
d = d + 20
print(d) Output:

Output:-

If- else:
If else is used to execute group of statements based on a
condition, if the condition is true then it will execute if-block
otherwise it will execute else-block

When to use if-else

PythonwithVenkat@[Link] [Link] P a g e 44
Syntax:
if(condition):
Statement-1
else:
Statement-2
Flow-Chart:

Ex:-
n = 10
if(n>0):
print("Given Number is +ve")
else:
print("Given Number is -ve")
Output:

1) n = 5 2) n = 5

if(n%2==0): if(n%2==0):

print(" Even ") print("Even")

else: else:

print(" ODD ") print("ODD")

PythonwithVenkat@[Link] [Link] P a g e 45
print(" Thank you ") print("Thank you")
Output:
Output:

3) n = 5 4) n = -3

if(n>0): if(n>0):

print(" +ve ") print(" +ve ")

else: else:

print(" – ve ") print(" – ve ")

print("Thank you") print("Thank you")

Output: Output:
5) n = 0 6) s1 = 52

if(n>0): s2 = 36

print(" +ve ") if(s1>=35 and s2>35):

else: print(" PASS ")

print(" – ve ") total = s1 + s2

else:

print("Thank you") print(" FAIL ")


Output:-
print(" All The Best ")

print("Thank you")
Output:

PythonwithVenkat@[Link] [Link] P a g e 46
7) s1 = 52 8) a,b,c =4,6,2
if(a>3 and b>5 and c>6 ):
s2 = 35 print(" Venkat Technology")
else:
if(s1>=35 and s2>35): print("Venkat Reddy")
print(" PASS ")

total = s1 + s2 Output:-

else:

print(" FAIL ")

print(" All The Best ")

print("Thank you")
Output:
9) uname = "Venkat Reddy" 10) x = 5
pwd = "Python" y=8
if(uname=="Venkat Reddy" or if(x>y):
pwd=="Venkat"): print("x is big")
print(" Valid User ") else:
else: print("y is big")
print("Invalid User") Output:
Output:-

11) x = 5 12) a = 2
y=5 b=3
if(x>y): c=4
print("x is big") if(a>1 and b>2 or c>5):
else: print("Hai")
print("y is big") else:
Output:- print("Bye")

Output:

13) a = 2 14) p = 6
b=1 if(not p):
c=4 print("Venkat Reddy")
if(a>1 and b>2 or c>5): else:
print("Hai") print("Venkat Technology")

PythonwithVenkat@[Link] [Link] P a g e 47
else: Output:-
print("Bye")

Output:-

15) billAmt = 4500 16)if(true):


card = 'SBI' print("Hai")
if(billAmt>5000 or card=="SBI"): else:
print("Eligible for Discount") print("Bye")
else:
print("Not Eligible") Output:
Output:

Elif : elif statement in Python is used when you need to choose one
between more than two alternatives.

Flow-Chart:

PythonwithVenkat@[Link] [Link] P a g e 48
Syntax:
if(condition):
Statement -1
elif(condition):
Statement -2
else:
Statement -3

1. x=5 2. x=5
if(x>0): if(x>0):
print("+ve Number") print("+ve Number")
elif(x<0): elif(x<0):
print("-ve Number") print("-ve Number")
else: elif(x==0):
print("Zero") print("Zero")

Output: Output:

3. x=5 4. x=5
if(x>0): if(x>0):
print("+ve Number") print("+ve Number")
elif(x<0): print(x)
print("-ve Number") elif(x<0):
print(x) print("-ve Number")
else(x==0): else:
print("Zero") print("Zero")

Output:- Output:

5. x=5 6. x=5
if(x>0): if(x>0):
print("+ve Number") print("+ve Number")
print(x) elif(True):
elif(x<0): print("-ve Number")
print("-ve Number") else:
else: print("Zero")
print("Zero")

Output:- Output:-

PythonwithVenkat@[Link] [Link] P a g e 49
7. x = -5 8. x = -2
if(x>0): if(x>0):
print("+ve Number") print("+ve Number")
else: elif(x<0):
print("Zero") print("Zero")
elif(x<0): else:
print("-ve Number") print("-ve Number")

Ouput:- Output:-

9. item = "Idly" 10. c = 'r'


if(item=="Dosa"): if(c=='b' or c =='B'):
cost = 30 print('BLUE')
elif(item=="Puri"): elif(c=='g' or c=='G'):
cost = 45 print('GREEN')
elif(item =="Idly"): elif(c=='r' or c=='R'):
cost = 25 print('RED')
else:
cost = 50
print(cost)

Output:- Output:-

Nested if:
If Statement presents inside of another if statement then it is called
as nested-if.
Code Snippets of "Nested-if":

1. if(True): 2. if(False):
if(False): if(False):
print("Hai") print("core Python")
else: else:
print("Bye") print("Adv Python")
else:
Output:-

PythonwithVenkat@[Link] [Link] P a g e 50
print("Venkat
Technology")

Output:-

3. x = -2 4. x = 2
if(x!=0): if(x!=0):
if(x>0): if(x>0):
print("+ve Number") print("+ve Number")
else: else:
print("-ve Number") print("-ve Number")
else: else:
print("Zero") print("Zero")

Output:
Output:
5. x = 0 6. x = 15
if(x!=0): if(x!=0):
if(x>0): if(x%2==0):
print("+ve Number") print("2 Divigible")
else: elif(x%3==0):
print("-ve Number") print("3 Divigible")
else: elif(x%5==0):
print("Zero") print("5 Divigible")
else:
print("Zero")
Output:

Output:-

PythonwithVenkat@[Link] [Link] P a g e 51
Chapter-8
Looping Statements

PythonwithVenkat@[Link] [Link] P a g e 52
Looping Statements:
Looping Statements are used for executing a group of statements
multiple times.

Types of Loops:
1) for loop
2) while loop

1) for loop:
"for loop" is a repetition process which is used to execute group of
statements repeatedly within the given range.

Syntax:
for variable in range()/str/sequence:
statement1
statement2
.......

we can repeat the statements according to our requirement with the


help of range() function. The range() can be used in following ways

i) range(endvalue): This range() will begin from 0 and continues upto the
specified "endvalue-1"

ii) range(startvalue, endvalue): This range() will begin from the specified
"startvalue" and continues upto the specified "endvalue-1"

iii) range(startvalue, endvalue, stepvalue): This range() will begin from the
specified "startvalue" and continues upto the specified "endvalue-1" and it
will increase or decrease with the specified "stepvalue"

Note: If we don't specify the "stepvalue" then the default "stepvalue" is 1.

PythonwithVenkat@[Link] [Link] P a g e 53
Examples:
i) for i in range(10):
print(i)

output:
0
1
2
3
4
5
6
7
8
9

ii) for j in range(1,10):


print(j)

output:
1
2
3
4
5
6
7
8
9

iii) for j in range(1,10,2):


print(j)

output:
1
3
5
7
9

PythonwithVenkat@[Link] [Link] P a g e 54
iv) for j in range(10,0,-1):
print(j)

output:
10
9
8
7
6
5
4
3
2
1
2) while loop:
"while loop" is executing group of statements repeatedly based on
the condition.
Syntax:
while <condition>:
statement(s)

Example: Displaying a message for 10 times


i=1
while i<=10:
print("Venkat Technologies")
i=i+1
output:
"Venkat Technologies" is displayed for 10 times
Note: If you know number of iterations then use for-loop otherwise use
While-loop
For - Loops
Find out Outputs
1) for i in range(1,5,1): 2) for i in range(10):
print(i,end=" ") print(i,end=" ")
Output: Output:

3) for i in range(2,11,2): 4) for i in range(10,1):

PythonwithVenkat@[Link] [Link] P a g e 55
print(i,end=" ") print(i,end=" ")
Output: Output:

5) for i in range(10,1,-1): 6) for i in range(4,10,-1):


print(i,end=" ") print(i,end=" ")
Output:- Output:-

7) for i in range(4,10,3): 8) for i in range(6,0,-2):


print(i,end=" ") print(i,end=" ")
Output:- Output:
9) for i in range(10): 10) sum = 0
if(i%2!=0): for i in range(1,6):
print(i,end=" ") if(i%2==0):
Output:- sum=sum+i
print( i )
Output:-

11) for i in range(1,6): 12) n = 10


if(i%3==0): count = 0
print(i,end=" ") for i in range(n):
Output: if(n%i==0):

count=count+1
print(count)
Output:

13) n=5 14) x = [2,5,3,6,1,4]


a=1 s=0
for i in range(1,n+1): for i in x:
a=a*i if(i%2==0):
print(a) s=s+i
Output: print(s)

Output:-

15) x = [2,5,3,6,1,4] 16) for i in range(1,5):


s=0 for j in range(1,5):
for i in x: print(j,end=" ")
if(i%2!=0):
s=s+i Output:
print(s)
Output :

PythonwithVenkat@[Link] [Link] P a g e 56
17) for i in range(1,5): 18) for i in range(1,5):
for j in range(1,5): for j in range(1,5):
print(j,end=" ") print(i,end=" ")
print( ) print( )

Output:- Output:-

19) for i in range(1,5): 20) for i in range(1,5):


for j in range(1,i+1): for j in range(1,i+1):
print(i,end=" ") print(j,end=" ")
print( ) print( )

Output: Output:

21) for i in range(1,5): 22) k = 1


for j in range(1,i+1): for i in range(1,5):
print("*",end=" ") for j in range(1,i+1):
print( ) print(k,end=" ")
k +=1
Output:- print( )

Output:-

PythonwithVenkat@[Link] [Link] P a g e 57
For Loop programs
1. W.A.P to print Venkat5 times
2. W.A.P to print 1 to 5 numbers
3. W.A.p to print 100 to 1 numbers
4. W.A.P to print 1 to n Even Numbers
5. W.A.P to print 1 to n Odd Numbers
6. W.A.P to print 1 to n Even and Odd Numbers
Odd Even

==== ====
1 2
2 4
7. W.A.P to print 1 to n, 5 dirigibles
8. W.A.P to print Multiplication Table

5 * 1 =5

5 * 2 =10

.............................................
9. W.A.P to check given number is Prime number or not
10. W.A.P to calculate factorial of a given number

11) Display following Formats

PythonwithVenkat@[Link] [Link] P a g e 58
12) Display Following Formats

13) Display following formats

14) Display following Formats

PythonwithVenkat@[Link] [Link] P a g e 59
While-Loop

1. n = 10 2.n = 10
sum = 0 sum = 0
while(n>0): while(n>0):
r = n % 10 r = n % 10
n = n // 10 n = n // 10
sum = sum + r sum = sum + r**3
print("sum is : ",sum) print("sum is : ",sum)
Output:- Output:-

3. n = 10 4. n = 2
sum = 0 while(n>0):
while(n>0): print(n, end="\t")
r = n % 10 n -= 1
n = n // 10 Output:
sum = sum*10 + r
print("sum is : ",sum)
Output:-

5. n = 6 6. n = 1
while(n<0): while(n<5):
print(n,end="\t") print(n)
n -= 1 n=n-1
print("Thank You") print(“Thank you”)
Output: Output:

7. n = 1 8. for i in range(5):
while(n<=5): while(i<5):
print(n,end= “\t”) print(i,end="\t")
n = n+1 i+=1
print(“Thank You”) print( )
Output:- Output:-

PythonwithVenkat@[Link] [Link] P a g e 60
While loop:
1) W.a.p to Reverse a given number
2) W.a.p to sum of digits in a given number
3) W.a.p to sum of even digits in a given number
4) W.a.p to sum of odd digits in a given numbers0
5) W.a.p to sum of 5 divigibles in a given number
6) W.a.p to sum of prime numbers in a given number
7) W.a.p to find given number is Amstrong Number or not

153 , 371

33*3*3 = 27

5  5 * 5 * 5 = 125

11*1*1 = 1

153
8) W.a.p to find given number is Magic number or not

Consider n value is 9

9  9 * 9 = 81
1 + 8  9

PythonwithVenkat@[Link] [Link] P a g e 61
Identify which loop is required to develop following programs then
develop the programs
1. Print the number from 10 to 1
2. Input any 10 numbers find out no of even numbers and no of odd
numbers
3. Input any 10 numbers find out no of positive numbers and no of
negative numbers
4. Input any 10 numbers find the first biggest and second biggest
number
5. Print sum of prime numbers between 1 to 100
6. Input any 4 digit number and reverse it
a. i/p:- 4325
b. o/p:- 5234
7. Wap to extract the Digits from the given number?
a. i/p:- 4321
b. o/p:- 4 3 2 1
8. Input any 4 digit number and find out the sum of the digits
a. i/p:- 4321
b. o/p: - 4+3+2+1=10
9. Wap to accept a no from console and check whether given no is
Armstrong no or not?
a. 153=13+53+33
10. Wap to accept a no from console and check whether given no
is perfect no or not?
a. Sum of proper divisors
b. i/p:- 6 1+2+3
i. 28 1+2+4+7+14
11. Wap to accept a no from console and check whether given no
is Strong no or not?
a. i/p: - 145
i. 1!+4!+5!
12. Input any 4 digit number and find out the sum of first and last
digit
13. Input any 4 digit number and find out the sum of middle digits
14. wap to print below Fibonacci series
1 1 2 3 5 8 13 21 34 55 89

PythonwithVenkat@[Link] [Link] P a g e 62
15. wap to print
* * * * *
16. wap to print
# # # # #
17. wap to print * # * # * #
18. wap to print # * # * # *
19. wap to print following patterns

1 * A A A

12 ** AA BB BC

123 *** A AA C CC DEF

1234 **** A AAA D DDD GHIJ

12345 ***** A AAAA E EEEE KLMNO

A # * A A

AB # # * * AA BB

ABC # ## * * * A AA C CC

ABCD # ### * * ** A AAA D DDD

ABCDE # #### * * * * * A AAAA E EEEE

A 1

BA 23

CBA 456

DCBA 7 8 9 10

EDCBA 11 12 13 14 15

PythonwithVenkat@[Link] [Link] P a g e 63
Chapter-9
String Handling

PythonwithVenkat@[Link] [Link] P a g e 64
 A String is a sequence of characters enclosed within single quotes or
double quotes.
 str represents String data type.
Single Quoted Strings
s1='Venkat'
Double Quoted Strings
s1="Venkat"
Triple Quoted Strings
By using single quotes or double quotes we cannot represent multi line
string literals. so, Triple Quotations are invented.
s1='''Venkat
tehcnologies'''  Triple single quotes for multi-line string
(or)
s1="""Venkat
tehnologies"""  Triple-double quotes for multi-line string
String Slicing And String Indexing
slice means a piece/part
In Python, Strings follow zero based index.
The index can be either +ve or -ve.
 Positive index means forward direction i.e. from Left to Right
 Negative index means backward direction i.e. from Right to Left

-6 -5 -4 -3 -2 -1

s a t h y a
0 1 2 3 4 5

>>> string1="Sathya"
>>> string1

PythonwithVenkat@[Link] [Link] P a g e 65
'Venkat'
+ve string Indexing:
>>> string1[0]
's'
>>> string1[1]
'a'
>>> string1[2]
't'
>>> string1[3]
'h'
>>> string1[4]
'y'
>>> string1[5]
'a'
-ve String Indexing:
>>> string1[-6]
's'
>>> string1[-5]
'a'
>>> string1[-4]
't‘
>>> string1[-3]
'h'
>>> string1[-2]
'y'
>>> string1[-1]
'a'
>>>
>>> string1="Venkat"

PythonwithVenkat@[Link] [Link] P a g e 66
>>> string1[0:1]
's'
>>> string1[0:2]
'sa'
>>> string1[0:3]
'sat'
>>> string1[0:5]
'sathy'
>>> string1[0:6]
'Venkat'
>>> string1[-6:-1]
'sathy'
>>> string1[-1:-6]  no output
''
>>> string1[-6:5]
'sathy'
>>> string1[-6:6]
'Sathya'
>>> string1[-6:-4]
'sa'
>>> string1[-1:-5]  no output
''
>>> string1[-1:-2]  no output
''

PythonwithVenkat@[Link] [Link] P a g e 67
Working with String Functions
>>> string1="Venkat"
>>> [Link]()
'VENKAT'
>>> string2="VENKAT"
>>> [Link]()
'Venkat'
>>> string1="Venkat"
>>> [Link]()
True
>>> [Link]()
False
>>> string1="VENKAT"
>>> [Link]()
True
>>> [Link]()
False
isnumeric(): String consists of only numeric characters
>>> string1="12345"
>>> [Link]()
True
>>> string2="2apples"
>>> [Link]()
True
>>> string2="apples"
>>> [Link]()
True
>>> string2="2apples"

PythonwithVenkat@[Link] [Link] P a g e 68
>>> [Link]()
True
>>> string4=" "
>>> [Link]()
True
>>> string5=""  no space is given
>>> [Link]()
False
>>> string1="Venkat"
>>> len(string1)
6
>>> book="A Python Book"
>>> [Link]()
True
Note: Every word first letter is capital. Then it is called as title case.
Reversing a string:
>>> string1="Venkat“
>>> string1[::-1]
'ayhtas'
>>> string1[::1]
'Venkat'
String Multiplication
>>> 'Python '*3
'Python Python Python '
String concatenation:
>>> string1="Venkat"
>>> string2="Technologies"
>>> string3=string1+string2
>>> string3

PythonwithVenkat@[Link] [Link] P a g e 69
'VenkatTechnologies'
>>> string4=string1+" "+string2
>>> string4
'Venkat Technologies'

Assignments:
1) What is String

2) How to Access individual characters in a string

3) Given me a real time example for processing individual characters in


strings

4) What’s the index of first character in a string

5) If a string has 10 characters, then what’s the index of last character

6) If we try to access a character which is out of range what happens

7) How can you find length of a string

PythonwithVenkat@[Link] [Link] P a g e 70
8) qualification= “ [Link]”
qualification[0]=’M’

print(qualification)

output:-

9) What is the meaning of immutable

10) Can we apply slicing on strings

11) If we give invalid index in slicing, what happens

String Testing Methods:

12) How to check whether given string contains any symbols or not

13) How to check whether given string contains only alphabet or not

14) How to check whether given string contains only digits or not

15) How to check our string is in lower case or not

PythonwithVenkat@[Link] [Link] P a g e 71
16) How to check our string is in upper case or not

17) How to check our string contains only whitespaces

String Modification methods

18) How to convert our string in to lower case

19) How to convert our string in to upper case

20) How to delete spaces that are available in left side of a string

21) How to delete spaces that are available in right side of a string

22) How to delete spaces that are available in both left side and right
side of a string

Search and Replace methods

23) How to change existing string with a new string

24) How to find a string ends with specific sub-string

PythonwithVenkat@[Link] [Link] P a g e 72
25) How to check whether a given string starts with a specific string or
not

1. s1 = "Hai ' 2. s1 = "Venkat" + "Python"


print(s1) print(s1)

Output:- Output:-

3. s1 = 10 + 20 4. s1 = "10" + "20"
print(s1) print(s1)

Output: Output:-

5. s1 = "10" + 20 6. s1 = "Python"
print(s1) s2 = "Core" + s1
print(s2)
Output:-
Output:
7. s1 = "Venkat" 8. s1 = "Venkat Technology"
for i in s1: print([Link]( ))
print(i, end=" ")
Output:-
Output:-

1. s1 = "Venkat Technology" 2.s2 = "core Python and Adv


print([Link]( )) Python are Python"
c = [Link]("java")
Output:- print(c )
Output:-

3. phno="9898989898" 4. name = "Venkat"


if([Link]()): if([Link]( )):
print("Valid phone number") print("Valid Name ")
else: else:
print("Invalid Ph number") print("Invalid Name")
Output:
Output:
5. userid = "Venkat12#" 6. email ="Venkat@[Link]"
s1 = [Link]('@')
print("User Name is : ",s1[0])

PythonwithVenkat@[Link] [Link] P a g e 73
if([Link]( )):
print("Valid User id") Output:-
else:
print("Invalid User Id ")

Output:-
7. s1="Venkat" 8. s1="Venkat"
print("\n",s1[1:4]) print("\n",s1[ : : -1])

Output:- Output:-

9. s1 = "Venkat Technology" 10. s1 = "Venkat Technology"


print(s1) print(s1[1:10:2])
print(s1[0] )
Output: Output:-
11. s1 = "Venkat Technology" 12. s1 = "Venkat Technology"
print(s1[1:20:3]) print(s1[6:1:-1])

Output: Output:-

13. s2 = "Python java in Venkat 14. s1=["Python","Java",".net"]


Technology " if "Python" in s1:
if("Python" in s2): print("Available")
print("Python is Available ") else:
else: print("Not Available")
print("Python is not
available") Output:-

Output:-
15. hallticket="112234001"
if [Link]("1122"):
print("Starts with your Code")

Output:

PythonwithVenkat@[Link] [Link] P a g e 74
Strings:
1) Write a Program to read String value, then display All even index
positions
Ex:- s1 = “ Venkat Technology”
Output:- na e h o o y
2) Write a Program to check given string is palindrome Or not
Ex1:- s1 = “madam”
Given String is Palindrome
Ex2:- s1 = “sim”
Given String is not Palindrome
3) Read Employee Email id dynamically then display Only employee
name

Ex:- Enter Email id : Venkat@[Link]

User Name is : Venkat


4) Read Group of Employee Email id’s dynamically then Display only
Employee names

Ex:- [“Venkat Reddy@[Link]”, “Venkat@[Link]”, ….]

User Names : Venkat Reddy Venkat


5) Read Group of Employee Email id’s dynamically then Read
company name dynamically, based on company name Display
only User names

Ex:- [“Venkat Reddy@[Link]”, “Vishnu@[Link]”,

“Lakshmi@[Link]”, “avinash@[Link]”]

Enter company name : [Link]

User Names : Venkat Reddy

Lakshmi
Avinash

PythonwithVenkat@[Link] [Link] P a g e 75
Chapter-10
Collections

PythonwithVenkat@[Link] [Link] P a g e 76
 A collection is a Data structure that holds set of objects.
 The purpose of collections is to store the data.
 “A collection is similar to a basket that you can add and remove
items from. In some cases, they are the same types of items, and in
others they are different.”

Types of Collections in Python:-


 list
 Tuple
 Set
 Dictionary
List: - A list can be used for storing a group of elements enclosed
within [ ]
Tuple:- A Tuple can be used for storing a group of elements
enclosed within ( )
Set:- A set can be used for storing a group of elements enclosed
within { }
Dictionary:- A Dictionary can be used for storing a group of
elements in key and value pair format enclosed within { }
List Tuple Set Dictionary
Duplicates Allowed Allowed NotAllowed Key-NotAllowed
Value:- Allowed
Insertion Ordered Ordered UnOrdered Ordered
order
Null Allows Allows Allows Key-not Allowed
Value:- Allowed
Retrieve Index Index NoIndex Key
Data
Syntax [5,6,7,9] (5,6,7,8) {5,6,7,8} {‘empID’:1122}
Data State Mutable Immutable Mutable Key is
Immutable and
value is mutable

PythonwithVenkat@[Link] [Link] P a g e 77
List:-
 A list can be used for storing a group of elements enclosed
within [ ]
 List will allow Duplicate Elements
 List will allow null values
 List will maintain the insertion Order
 List is mutable
 We can retrieve the data from List based on Index

Method Description

insert() Inserts Element to The List

remove() Removes item from the list

index() returns smallest index of element in list

count() returns occurrences of element in a list

pop() Removes element at the given index

reverse() Reverses a List

sort() sorts elements of a list

copy() Returns Shallow Copy of a List

clear() Removes all Items from the List

len() Returns Length of an Object

max() returns largest element

min() returns smallest element

sum() Add items of an Iterable

PythonwithVenkat@[Link] [Link] P a g e 78
Add a single element to the end of the
append() list

extend() Add Elements of a List to Another List


Example to create a list to store five subject marks of the student:
marks=[70,80,60,70,100] Output:
print(marks) [70,80,60,70,100]

append(element): It places the specified element at the end of list.


list1=[3,6,7,2,8,4,6] Output:
print(list1) [3, 6, 7, 2, 8, 4, 6]
[Link](9) [3, 6, 7, 2, 8, 4, 6, 9]
print(list1)

insert(index,element):Inserts Element to The List


list1=[3,6,7,2,8,4,6] Output:
print(list1) [3, 6, 7, 2, 8, 4, 6]
[Link](1,10) [3, 10, 6, 7, 2, 8, 4, 6]
print(list1)

extend(elements): It adds Elements of a List to Another List


l1 = [3,7,2,3] Output:
l2 = [6,4,5,2] [3, 7, 2, 3, 6, 4, 5, 2]
[Link](l2)
print(l1)

count(element) : It returns occurrences of element in a list


l1 = [3,7,2,3,4,6] Output:
c = [Link](3) 2
print(c)

sort( ): sorts elements of a list


n = [5,8,2,8,1,4,6] Output:
[Link]() [1, 2, 4, 5, 6, 8, 8]
print(n)
reverse():Reverses a List
n = [5,8,2,8,1,4,6] Output:
[Link]() [6, 4, 1, 8, 2, 8, 5]

PythonwithVenkat@[Link] [Link] P a g e 79
print(n)

remove(element):Removes item from the list


n = [5,8,2,8,1,4,6] Output:
[Link](2) [5, 8, 8, 1, 4, 6]
print(n) [5, 8, 1, 4, 6]
[Link](8) ValueError
print(n)
[Link](7)
print(n)
pop():Removes element at the given index
n = [5,8,2,8,1,4,6] Output:
[Link]() [5, 8, 2, 8, 1, 4]
print(n) [5, 8, 2, 8, 1]
[Link](5) IndexError
print(n)
[Link](7)
print(n)

Index(element) : returns smallest index of element in list


n = [5,8,2,8,1,4,6] Ouptut:
print([Link](2)) 2
print([Link](7)) ValueError

copy():Returns Shallow Copy of a List


n1 = [5, 2, 8, 3, 1, 6] Output:
n2=[Link]() [5, 2, 8, 3, 1, 6]
print(n1) [5, 2, 8, 3, 1, 6]
print(n2)

len( ): Returns Length of an Object


n1 = [5, 2, 8, 3, 1, 6] Output:
l = len(n1) 6
print(l)

min( ): returns smallest element

PythonwithVenkat@[Link] [Link] P a g e 80
n1 = [5, 2, 8, 3, 1, 6] Output:
l = min(n1) 1
print(l)

max():returns largest element


n1 = [5, 2, 8, 3, 1, 6] Output:
l = max(n1) 8
print(l)

sum( ): Add items of an Iterable


n1 = [5, 2, 8, 3, 1, 6] Output:
l = sum(n1) 25
print(l)

Write Output for following code snippet


1. l1=list(range(5)) 2. l1 =list(range(1,20,4)

print(l1) print(l1)

Ouptut:-
Output:-
3. l1=[ 0 ]*5 4. 11=[ 5, 10, 15, 20, 25, 30 ]
print( l1)
How to find size of list
Output:-

5. n = [ 4, 8, 12, 16, 20 ] 6. list1=[5, 7, 3, 8, 14,22]


n[3] = 40 print(list1[-3])
print(n)
Output : -
Output:-

7. l1= [ 6, 9, 3, 7] 8. l1= [ 4, 9, 12, 34, 22,10]


l2 = [4,12,22] l2=l1[1:3]
l3=l1 + l2 print( l2 )
print(l3)
Output:-
Output:

PythonwithVenkat@[Link] [Link] P a g e 81
9. l1= [ 4, 9, 12, 34, 22,10] 10. l1= [ 4, 9, 12, 34, 22,10]
l2=l1[1:] l2=l1[:1]
print(l2) print(l2)

Output:- Output:-

11. l1= [ 4, 9, 12, 34, 22,10] 12. l1= [ 4, 9, 12, 34, 22,10]
l2=l1[:] l2=l1[-2:]
print(l2) print(l2)

Output: Output:

13. names = [ ] 14. names = [ ]


names[0] = "Venkat Tech" [Link]("Venkat")
print(names) print(names)

Output:- Output:-

15. l1 = [ ] 16. l1=[10,20,30,10,50]


[Link]("S") [Link](10)
[Link]("V") print(l1)
[Link]("R")
print(l1) Output:-

Output:

17. l1 = [5,9,2,4] 18. l1 = [5,'S',2,'V',3,'R']


[Link]() [Link]()
print(l1) print(l1)

Output:- Output:-

19. l1 = [5,7,3,6] 20. l1 = [5,10,15,20]


l2 = l1 l2 = [5,10,15,20]
l1[2] = 12 if(l1==l2):
print(l1) print("Hai")
print(l2) else:
print("Bye")
Output:-
Output:

PythonwithVenkat@[Link] [Link] P a g e 82
21. l1=[[5,10],[15,20]] 22. l1=[[5,10],[15,20]]
print(l1[0]) print(l1[0][1])

Output:- Output:-

23. l1=[[5,10],[15,20]] 24. l1=[[5,10],[15,20]]


print(l1[1][-1]) print(l1[0][2])

Output:- Output:-

25. l1 = [ i for i in range(1,5)] 26. l1 = [ i**i for i in range(1,5)]


print(l1) print(l1)

Output:- Output:-

27. n = [5,8,3,6,1,4] 28. names=["Sangani","Venkat","Redd


l1 = [k for k in n if k%2==0] y"]
print(l1) l1 =[n[0] for n in names]
print(l1)
Output:-
Output:-
29. n = "123Venkat45" 30. l1=[p for p in range(1,10) if
l1 =[k for k in n if [Link]()] p%2==0]
print(l1) print(l1)

Output:- Output:-

31. l1 = [p for p in range(1,5) for q


in
range(1,p+1)]
print(l1)

Output:-

PythonwithVenkat@[Link] [Link] P a g e 83
Tuple:
 A tuple can be used for storing a group of elements
enclosed within ()
 Tuple will allow Duplicate Elements
 Tuple will allow null values
 Tuple will maintain the insertion Order
 Tuple is immutable
 We can retrieve the data from tuple based on Index
Method Description
count() returns occurrences of element in a tuple
index() returns smallest index of element in tuple
len() Returns Length of an Object
max() returns largest element
min() returns smallest element
sorted() returns sorted list from a given iterable
sum() Add items of an Iterable
tuple() Creates a Tuple

Index(element) : returns smallest index of element in list


n = (5,8,2,8,1,4,6) Ouptut:
print([Link](2)) 2
print([Link](7)) ValueError

len( ): Returns Length of an Object


n1 = (5, 2, 8, 3, 1, 6) Output:
l = len(n1) 6
print(l)

min( ): returns smallest element

PythonwithVenkat@[Link] [Link] P a g e 84
n1 = (5, 2, 8, 3, 1, 6) Output:
l = min(n1) 1
print(l)

max():returns largest element


n1 = (5, 2, 8, 3, 1, 6) Output:
l = max(n1) 8
print(l)

sum( ): Add items of an Iterable


n1 = (5, 2, 8, 3, 1, 6) Output:
l = sum(n1) 25
print(l)

Write output for following code spinet


1. t1 = (5, 8, 2, 5, 6, 9) 2. t1 = (5, 8, 2, 5, 6, 9)
print(type(t1)) print(t1[2])
print(t1)

Output:-
Output:-

3. t1 = (5, 8, 2, 5, 6, 9) 4. t1 = (5, 8, 2, 5, 6, 9)
t1[2] = 12 t1[-2] = 12
print(t1) print(t1)

Output:- Output:-

5. t1 = (5) 6. t1 = (5,)
print(type(t1)) print(type(t1))

Output:- Output:-

7. t1 = 5, 8. t1 = 2,6,4,5
print(type(t1)) print(type(t1))

Ouptut:- Output:-

PythonwithVenkat@[Link] [Link] P a g e 85
9. l1 = [5,6,2,4] 10. t1 = (5,6,2,4)
t1 = tuple(l1) l1 = list(t1)
print(t1) print(l1)
Output:- Output:-

11. a,b,c = 10,20,30 12. a,b = 5,7,2,1


print(a,"\t",b,"\t",c) print(a,b)

Output:- Output:-

13. x = 2,5,1 14. x = 2,5,1


p,q,r = x p,q,r,s = x
print(q) print(r)

Output:- Output:-

15. t1 = (i*i for i in range(1,5)) 16. t1 = (i*i for i in range(1,5))


print(t1) for i in t1:
print(i,end="\t")
Ouput:-
Output:-

PythonwithVenkat@[Link] [Link] P a g e 86
Set:
 A set can be used for storing a group of elements enclosed
within {}
 set will not allow Duplicate Elements
 set will allow null values
 set will not maintain the insertion Order
 set is mutable

Method Description
remove() Removes Element from the Set
add() adds element to a set
copy() Returns Shallow Copy of a Set
clear() remove all elements from a set
difference() Returns Difference of Two Sets
discard() Removes an Element from The Set
intersection() Returns Intersection of Two or More Sets
issubset() Checks if a Set is Subset of Another Set
issuperset() Checks if a Set is Superset of Another Set
pop() Removes an Arbitrary Element
symmetric_difference() Returns Symmetric Difference
union() Returns Union of Sets
update() Add Elements to The Set.
len() Returns Length of an Object
max() returns largest element
min() returns smallest element

add( ):- adds single element to a set


n = {4, 7, 2, 9, 3, 5} Output:
[Link](6) {2, 3, 4, 5, 6, 7, 9}

PythonwithVenkat@[Link] [Link] P a g e 87
print(n)

Update( ): Add multiple Elements to The Set.


n = {4, 7, 2, 9, 3, 5} Output:
a = [12, 5, 13] {2, 3, 4, 5, 7, 9, 12, 13}
[Link](a)
print(n)

Adding tuple to set


n = {4, 7, 2, 9, 3, 5} Output:
a = (12, 5, 13) {2, 3, 4, 5, 7, 9, 12, 13}
[Link](a)
print(n)

Adding one set to anther set


n = {4, 7, 2, 9, 3, 5} Output:
a = {12, 5, 13} {2, 3, 4, 5, 7, 9, 12, 13}
[Link](a)
print(n)

pop( ): Removes an Arbitrary Element


n = {4, 7, 2, 9, 3, 5} Output:
[Link]() {3, 4, 5, 7, 9}
print(n)

remove() : Removes Element from the Set


n = {4, 7, 2, 9, 3, 5} Output:
[Link](9) {2, 3, 4, 5, 7}
print(n) KeyError: 6
[Link](6)
print(n)

discard( ): Removes an Element from The Set


n = {4, 7, 2, 9, 3, 5} Output:
[Link](9) {2, 3, 4, 5, 7}
print(n) {2, 3, 4, 5, 7}

PythonwithVenkat@[Link] [Link] P a g e 88
[Link](6)
print(n)

clear():remove all elements from a set


n = {4, 7, 2, 9, 3, 5} Output:
[Link]() set()
print(n)

union():Returns Union of Sets


intersection():Returns Intersection of Two or More Sets
difference(): Returns Difference of Two Sets
symmetric_difference(): Returns Symmetric Difference

p = {5, 9, 2, 4, 1} Output:
q = {3, 2, 5, 1, 6} {1, 2, 3, 4, 5, 6, 9}
a = [Link](q) {1, 2, 5}
print(a) {9, 4}
b = [Link](q) {3, 4, 6, 9}
print(b)
c = [Link](q)
print(c)
d = p.symmetric_difference(q)
print(d)

issuperSet():Checks if a Set is Superset of Another Set


issubSet():Checks if a Set is Subset of Another Set
p = {5, 9, 2, 4, 1} Output:
q = {5, 2, 1} True
a = [Link](q) False
print(a) False
b = [Link](p) True
print(b)
c = [Link](q)

PythonwithVenkat@[Link] [Link] P a g e 89
print(c)
d = [Link](p)
print(d)

copy( ): Returns Shallow Copy of a Set


p = {5, 9, 2, 4, 1} Output:
q = [Link]() {1, 2, 4, 5, 9}
print(q)
len( ): Returns Length of an Object
n1 = {5, 2, 8, 3, 1, 6} Output:
l = len(n1) 6
print(l)

min( ): returns smallest element


n1 = {5, 2, 8, 3, 1, 6} Output:
l = min(n1) 1
print(l)

max():returns largest element


n1 = {5, 2, 8, 3, 1, 6} Output:
l = max(n1) 8
print(l)

sum( ): Add items of an Iterable


n1 = {5, 2, 8, 3, 1, 6} Output:
l = sum(n1) 25
print(l)
1. s1 = {2,5,6,1} 2. s1 = {3,5,6,1,5}
print(s1) print(s1)

Output:- Output:-

3. l1 = [2,6,1,7,6] 4. s1 = set(range(5))
s1 = set(l1) print(s1)

PythonwithVenkat@[Link] [Link] P a g e 90
print(l1) Output:-
print(s1)
Output:-

5. s1 = {3,7,1,4,9} 6. s1 = {3,7,1,4,9}
print(s1[1:3]) print(s1[4:1:-1])

Output:- Output:-

7. s1 = {3,7,1,4,9} 8. s1 = {3,7,1,4,9}
[Link](5) [Link](5,2)
print(s1) print(s1)

Output:- Output:-

9. s1 = {3,7,1,4,9} 10. s1 = { 5, 9 , 3, 6, 4, 2 }
[Link](5,2) Write a code to remove 9
print(s1)

Output:-

11. s1 = set("Venkat Reddy") 12. s1 = {7, 9, 3, 1, 4}


print(s1) s2 = {8, 2, 9, 7, 6}
print([Link](s2))
Output:-
Output:-

13. s1 = {7, 9, 3, 1, 4} 14. s1 = {7, 9, 3, 1, 4}


s2 = {8, 2, 9, 7, 6} s2 = {8, 2, 9, 7, 6}
s3 = print(s1-s2)
s1.symmetric_difference(s2)
print(s3) Output:-

Output:-

PythonwithVenkat@[Link] [Link] P a g e 91
Dictionary:
 A dictionary can be used for storing a group of elements in
key and value pair format and enclosed within {}
 Key will not allow duplicates and value will allow duplicates
 Insertion order
 Key will not allow None
 Dictionary is a mutable object

Method Description
clear() Removes all Items
copy() Returns Shallow Copy of a Dictionary
get() Returns Value of The Key
items() returns view of dictionary's (key, value) pair
keys() Returns View Object of All Keys
popitem() Returns & Removes Element From Dictionary
setdefault() Inserts Key With a Value if Key is not Present
pop() removes and returns element having given key
values() returns view of all values in dictionary
update() Updates the Dictionary
dict() Creates a Dictionary
len() Returns Length of an Object
max() returns largest element
min() returns smallest element
map() Applies Function and Returns a List
sorted() returns sorted list from a given iterable
sum() Add items of an Iterable

PythonwithVenkat@[Link] [Link] P a g e 92
get() :- Returns Value of The Key
d1 = Output:
{101:"Vishnu",102:"Avinash",103:"Lakshmi"} Vishnu
a = [Link](101) None
print(a)
b = [Link](105)
print(b)

update( ):
d1 = Output:
{101:"Vishnu",102:"Avinash",103:"Lakshmi"} {101: 'Vishnu', 102:
d2 = {104:"Leena",102:"Venkat"} 'Avinash', 103: 'Lakshmi'}
print(d1) {104: 'Leena', 102:
print(d2) 'Venkat'}
[Link](d2) {101: 'Vishnu', 102:
print(d1) 'Venkat', 103: 'Lakshmi',
104: 'Leena'}

pop(): removes and returns element having given key


d1 = Output:
{101:"Vishnu",102:"Avinash",103:"Lakshmi"} {101: 'Vishnu', 103:
[Link](102) 'Lakshmi'}
print(d1) keyError
[Link]("Vishnu")
print(d1)
popitem() : Returns & Removes Element From Dictionary
d1 = Output:
{101:"Vishnu",102:"Avinash",103:"Lakshmi"} {101: 'Vishnu', 102:
[Link]() 'Avinash'}
print(d1)

keys( ): Returns View Object of All Keys


d1 = Output:
{101:"Vishnu",102:"Avinash",103:"Lakshmi"} dict_keys([101, 102, 103])
k = [Link]()
print(k)
values():returns view of all values in dictionary

PythonwithVenkat@[Link] [Link] P a g e 93
d1 = Output:
{101:"Vishnu",102:"Avinash",103:"Lakshmi"} dict_values(['Vishnu',
v = [Link]() 'Avinash', 'Lakshmi'])
print(v)

items():returns view of dictionary's (key, value) pair


d1 = Output:
{101:"Vishnu",102:"Avinash",103:"Lakshmi"} dict_items([(101, 'Vishnu'),
i = [Link]() (102, 'Avinash'), (103,
print(i) 'Lakshmi')])

len( ) : Returns Length of an Object


d1 = Output:
{101:"Vishnu",102:"Avinash",103:"Lakshmi"} 3
a = len(d1)
print(a)

sorted():returns sorted list from a given iterable


d1 = Output:
{"Hyd":"Vishnu","Bang":"Avinash","Delhi":"Lakshmi"} ['Bang', 'Delhi',
a = sorted(d1) 'Hyd']
print(a)

Write output for following code snippets


1. d1={ } 2. d1={101:"VenkatReddy",102:"Lakshmi",
print(type(d1)) 103:"Vishnu",04:"Avinash" }
print(d1[101])

Output:- Output :-

3. d1 = dict( ) 4. d1={101:"VenkatReddy",102:"Lakshmi",
print(type(d1)) 101:"Vishnu",04:"Avinash"
}
Output:- print(d1[101])

PythonwithVenkat@[Link] [Link] P a g e 94
Output :-

5. d1={101:"VenkatReddy",102:"La 6. d1={101:"VenkatReddy",102:"Lakshmi"}
kshmi"} d1[103] = "Lakshmi"
d1[102] = "Sangani" print(d1)
print(d1[102])
Output:-
Output:-

7. d1={101:"VenkatReddy",102:"La 8. d1={101:"VenkatReddy",102:"Lakshmi"}
kshmi"} del d1["Lakshmi"]
del d1[102] print(d1)
print(d1)
Output:-
Output:-

9. d1={101:"VenkatReddy",102:"Vis 10. d1={101:"VenkatReddy",102:"Vishnu"}


hnu"} for i in d1:
for i in d1: print(i,"\t",d1[i])
print(i,end ='\t')
Output:-
Output:-

11. d1={101:"VenkatReddy", 12. d1={101:"VenkatReddy",102:"Vishnu"}


102:"Vishnu"} for i in [Link]():
for i in [Link]( ): print(i)
print( i )
Output:-
Output:-

13.d1={101:"VenkatReddy",102:"Vi 14.d1={101:["Venkat",2000.0]}
shnu"} for i in d1:
for i in [Link](): print( i )
print( i ) Output:-
Output:-

15. d1={101:["Venkat",2000.0]} 16. d1={101:["Venkat",2000.0]}


for i, j in [Link](): for i, j in [Link]():
print(i,"\t", j) print(i,end="\t")
for k in j:
Output:- print(k,end='\t')

PythonwithVenkat@[Link] [Link] P a g e 95
Output:-

17. d1={"HR": 18. d1={101:["Venkat",2000.0],


{101:"Venkat",102:"Lakshmi"}} 102:[“Avinash”,5000.0] }
Write a code to display above
data Write code to display only Avinash data

19. d1={"HR": 20. d1={"HR":


{101:"Venkat",102:"Lakshmi"},
{101:"Venkat",102:"Lakshmi"}, “Production”:
“Production”: {201:“Vishnu”,202:“Avinash”} }
{201:“Vishnu”,202:“Avinash”} }
Write a code to display only Vishnu
Write a code to display only HR data
data

PythonwithVenkat@[Link] [Link] P a g e 96
Chapter-11
Functions

PythonwithVenkat@[Link] [Link] P a g e 97
PythonwithVenkat@[Link] [Link] P a g e 98
PythonwithVenkat@[Link] [Link] P a g e 99
PythonwithVenkat@[Link] [Link] P a g e 100
PythonwithVenkat@[Link] [Link] P a g e 101
PythonwithVenkat@[Link] [Link] P a g e 102
PythonwithVenkat@[Link] [Link] P a g e 103
PythonwithVenkat@[Link] [Link] P a g e 104
Chapter-1
OOPS

PythonwithVenkat@[Link] [Link] P a g e 105


OOPS
OOPS stands for Object Oriented Programming System.
OOPS is a Concept which is used to write programs by using classes
and Objects.
Principles of OOPS:-
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Abstraction: Providing essential details and hiding unessential details.


Encapsulation: It is a mechanism of grouping of related variables and
methods in a container.
Inheritance: one class acquires the properties from another class.
Polymorphism: The ability to have many forms.

PythonwithVenkat@[Link] [Link] P a g e 106


OOPS
-------
--> Object Oriented Programming System
--> Abstraction
--> Encapsulation
--> Inheritance
--> Polymorphism

* Any Programming Language follows above 4 then it is called as OOPL


* In OOPL we have to develop progrms by using class and object
* Python is called as OOPL
* python is called as functional Programming language
* python is called as Scripting Languge
---> Python is General Purpose programming Language
* If you are developing desk top related / single user applications then use
functional programming
* If you are developing web Applications then use object oriented
programming

Variable : Variable is a Named memory location, used to store data


function/Methods : used to perform specific operation on data .
--> if you want to develop 1 application with multiple users then we need
oops concepts
classes
objects
class:- class is a collection of variables and methods
object :- Instance (Memory) of a class

OOPL
------
--> Abstraction
--> Encapsulation
--> Inheritance
--> Polymorphism

PythonwithVenkat@[Link] [Link] P a g e 107


Abstarction:
--------------
--> Abstraction is a process of display necessary data and hiding unnecessary data

Encapsulation
----------------
--> It is the process of binding related variables and methods into a single unit
is called as Encapsulation

class :
class is a collection of vairables and methods
where variables can store data and methods can perform specific operations
Inheritance
-------------
--> Inheritance is a process of getting properites from one class to another
class

PolyMorphism
------------------
--> Ploy morphism means Many Forms
2 + 5 ==> 7
"Adv" + "Python" ==> "AdvPython"
"2" + "5" ==> "25"
class
------
--> class is a collection of related variables and methods
--> To define a class we have to use class keyword
Syntax:
--------
class classname :
........................
.......................
.......................
Variables & Methods
---------------------------

PythonwithVenkat@[Link] [Link] P a g e 108


Methods:
------------
--> Method is a collection of statements which performs specific task
calSalary( )
display( )
caltotal( )
--> To define method we have to use def keyword
--> Once we defined methods, we can call for multiple times
In Python we have 2 types of methods
1) Static method
2) Instance Method

1)Static Method
--------------------
--> Static Methods are used to perform operation on static variables
--> To declare static method, we have to use "@staticmethod" decorator
--> To call static methods we have to calss name

Ex:-
class Employee:
@staticmethod
def m1( ): # Static Method
print(" It's Static Method ")

Employee.m1( ) # calling Employee class m1( ) method

2) Instance Method
-----------------------
--> Instance methods are used to perform operations on instance variables
--> In Instance Methods , it will take "self" word as a default argument
--> To call instance methods we have to use object (or) object reference
Ex:
class Employee:
def m1(self): # instance Method
print(" Instance Method ")
print(" In Employee Class ")
e1 = Employee( ) # Object Creation
e1.m1( ) # calling instance method m1 ( )

PythonwithVenkat@[Link] [Link] P a g e 109


Example:

class Amazon:
@staticmethod
def search(productname):
print(" Your Products ")

def buyNow(self):
print(" You can buy now ")

[Link]("Pendrive") # calling static method

a = Amazon( )
a . buyNow( )

Variable:
---------
--> Variable is a named memory location, which is used to store data
--> Variables are classified into 5 types
1) Global Variables
2) Static variables
3) Instance variables
4) Parameters
5) Local Variables

1) Global Variables
--------------------
--> The variables which are declared outside of class is called as global variables
2) Static Variables
---------------------
--> The variables which are declared inside of the class and outside the method is called as
Static variables
--> Static variables will hold common values for all objects
--> static variables it will allocate common memory for all object at once
class Employee:
cmpname = " It vidhya " # static Variables
def show(self):
..............
.............

PythonwithVenkat@[Link] [Link] P a g e 110


3) Instance Variables
---------------------
--> The variables which are declare inside of class and inside of method with self
word
class Employee:
cphno = 8074864650 # static variable
def calSalary(self):
[Link] = 1001 # instance variables
4) Parameters
--------------
--> The variables which are declared at the time of method declaration they are called as
parameters
class Test:
def m1(self, a, b): // a and b are called as Parameters/ arguments
......................
......................
5) Local Variables
---------------------
--> The Varaibles which are declared inside of method is called as local variables
class Test:
def m1(self, a, b): // a and b are called as paramenters/ arguments
c=a+b // c is called as local variables

--> local variables , parameters can access only inside of that method

Methods
--> Static Methods --> @staticmethod
--> Instance Methods --> by default parameter is self
Variables
--> Global variables --> Outside class --> In Entire Application
--> Static variables --> Inside class and outside method --> Inside class
--> Instance Variables--> Inside class , inside method with self word --> Inside class
--> Parameters --> In method declaration with in ( ) --> Inside Method
--> Local Variables --> Inside method --> Inside Method

PythonwithVenkat@[Link] [Link] P a g e 111


class Employee:
cphno = 8074864650 # static variable
@staticmethod
def CreateDBconnection( ): # static method
print("............")
def caladd(self, a,b): # instance method , a,b are parameters
self. eid = 10 # x is instance variable
c=a+b # c, d are local variables
d=a-b
print(c)
print(d)
print(self.x)
def show(self):
print(self.x)

e1 = Employee( ) # e1 is reference variable

--> To Perform operations on static variables then use static methods


--> To Perform operations on instance variables or local variables use instance methods

--> W.a.p to read and display employee information by using calss and object
eid, ename, salary

class Employee:
def read(self):
[Link] = 1001
[Link] = "Vishnu"
[Link] = 20000.0
def show(self):
print("Employee id is : ",[Link])
print("Employee name : ",[Link])
print("Emp Salary is : ",[Link])

e1 = Employee( )
[Link]( )

--> W.a.p to read student data, then display data


read( ) --> clgname, sid, sname, fee
show( ) --> display details

--> W.a.p to read sudent marks then cal total then display
read( ) --> Read s1,s2, s3 marks
calTotal( ) --> cal total marks

PythonwithVenkat@[Link] [Link] P a g e 112


show( ) --> display s1,s2,s3 and total marks

Constructors
----------------
--> Constructor is a special kind of method, which is used to initalize instance variables of
a class
--> Constructor name must be __init__
--> Constructor will take self as a default parameter
--> Constructor is called automatically at the time of object creation
--> Construcotr is called one time for one object
--> Constructor doesn't return any value
--> Constructor are 2 types
1) Default Constructor
2) Parameterized Constructor
1) Default Constructor
----------------------------
class Employee:
def __init__(self):
print(" I am Constructor")
def m1(self):
print(" m1 Method ")
e1 = Employee( )

Ex2:-
class Employee:
def __init__(self):
print(" I am Constructor")
def m1(self):
print(" m1 Method ")
e1 = Employee( )
e1.m1( )
e1.m1( )

Ex3 :-

class Employee:
def __init__(self):
[Link] = 1001
[Link] = "Vishnu"
[Link] = 20000.0
def show(self):

PythonwithVenkat@[Link] [Link] P a g e 113


print("Employee id is : ",[Link])
print("Employee name : ",[Link])
print("Emp Salary is : ",[Link])

e1 = Employee( )
[Link]( )
e2 = Employee( )
[Link]( )

2)Parameterized Constructor

class Employee:
def __init__(self,idno,name,salary):
[Link] = idno
[Link] = name
[Link] = salary
def show(self):
print("Employee id is : ",[Link])
print("Employee name : ",[Link])
print("Emp Salary is : ",[Link])

e1 = Employee(1001,"Vishnu",20000.0 )
[Link]( )
idno = int(input())
name = input( )
salary = float(input( ))
e2 = Employee(idno,name,salary)
[Link]( )

Destructor
------------
--> Destructors will remove memory of object
--> Destructor is special kind of method which is called at the time of object deletion
--> Destructor name must be " __del__ "
--> Destructor will take self as a default Parameter
--> we can delete object by using del keyword
class Employee:
def __init__(self):
print(" It is Constructor ")
def show(self):
print(" I am show ")
def __del__(self):
print(" It is Destructor ")
e1 = Employee( )

PythonwithVenkat@[Link] [Link] P a g e 114


[Link]( )
del e1 # It is used to delete object

Class: A class is a collection of variables and methods.


Syntax of a class:
class <classname>:
variables
methods

Object: An Object is an instance of a Class. When a class is defined, no


memory is allocated but when an object is created then memory is allocated
for instance variables.
Syntax of object:
referencename = classname( )
What is the purpose of reference variable?
The purpose of reference variable is used to access the instance
methods.
variable: variable is a named memory location which is used to store the
data.
Types of variables:
1. Static variables
2. Instance variables
3. Local variables
4. Global variables
5. Parameters

1) Static Variable: when the data is common to all objects then we have to
use "Static variables".
Rules for static variables:
static variable should initialize with some value
static variable must declare inside the class and outside the method.
static variable must be accessible by using class name.

PythonwithVenkat@[Link] [Link] P a g e 115


Example:

Instance Variable:
When data is changing from one object to another object then we have
to use Instance variables.

Rules for Instance Variables:


 Instance variable should initialize with some value
 Instance variable should be prefixed with "self"
 Instance variable should be initialized within the instance
method/constructor.

What is "self"?
"self" is the default reference variable given for the object.
What is the purpose of "self"?
The purpose of "self" is to identify the instance variables. i.e. if we want
to initialize the value to an instance variable or if we want to access the
instance variable then we have to use "self".
Parameters: Parameters are used to pass the input to the method.

PythonwithVenkat@[Link] [Link] P a g e 116


Local variable: If a variable is declared inside a method then that variable
is called as local variable.

Rules for "Local Variables":


Local variable should be initialized within the method.

Constructor:
Constructor is used to initialize the instance variables.
Constructors are two types:
1) Parameterized constructors
2) Non-parameterized constructors
Parameterized Constructors:
It is used to initialize the instance variables by accepting parameters.

Program:
class Employee: Output:
def __init__(self,eno,ename,edept): Employee Number: 101

PythonwithVenkat@[Link] [Link] P a g e 117


[Link]=eno Employee Name: Raju
[Link]=ename Employee Department: IT
[Link]=edept Employee Number: 102
def display(self): Employee Name: Ravi
print("Employee Number:",[Link]) Employee Department:
print("Employee Name:",[Link]) Testing
print("Employee Department:",[Link])
e1=Employee(101,'Raju','IT')
[Link]( )
e2=Employee(102,'Ravi','Testing')
[Link]( )

Non-Parameterized Constructors:
It is used to initialize the instance variables with default values.

Program:
class SIM: Output:
def __init__(self): Talktime offer: 50.0
self.Talktime_offer=50.0 Data_offer: 1GB
self.Data_offer='1GB'
def display(self):
print("Talktime
offer:",self.Talktime_offer)
print("Data_offer:",self.Data_offer)
s1=SIM()
[Link]()

Types of Methods:
A method is used to perform the operations on data.
The following are the types of methods:
1) Instance method

PythonwithVenkat@[Link] [Link] P a g e 118


2) static method

Instance Method:
 Instance method is used to perform the operations on instance
variables.
 When data is changing from one object to object then that data is used
to store in "instance variables".
 An instance variable is prefixed with "self". ("self" refers the current
object)
 An instance method takes first parameter as "self"

An Instance method is called through an object reference.

Program:
class Customer: Output:
def AcceptCustomerDetails(self,cname,caddress,cmobileno): Customer Name: Raju
[Link]=cname Customer Address:
[Link]=caddress Ameerpet,Hyd
[Link]=cmobileno Customer Mobile
def display(self): Numnber: 9949404281
print("Customer Name:",[Link]) Customer Name: Ravi
print("Customer Address:",[Link]) Customer Address: SR
print("Customer Mobile Numnber:",[Link]) Nagar

PythonwithVenkat@[Link] [Link] P a g e 119


c1=Customer() Customer Mobile
[Link]('Raju','Ameerpet,Hyd',9949404281) Numnber: 9949404282
[Link]()
c2=Customer()
[Link]('Ravi','SR Nagar',9949404282)
[Link]()

2) Static Method:
 Static method is used to perform the operations on "Static Variables"
 When data is common to all objects then "static variables" are
preferred.
 Static method is called through class name
 Static method does not take "self" as a parameter

Program:
class Employee: Output:
CompanyName='TCS' Company Name: TCS
CompanyWebsite='[Link]' Company Website:
def DisplayCompanyInformation(): [Link]
print("Company
Name:",[Link])
print("Company
Website:",[Link])
[Link]()

3) Class Method:
 Class method is used to perform the operations on class variables
 Class method takes "cls" system-defined variable as a parameter
 Class method should be called through class name

PythonwithVenkat@[Link] [Link] P a g e 120


"@classmethod" decorator is used to decorate a method into class method.
Program:
class Employee: Output:
@classmethod Company Name:
def DisplayCompanyInformation(cls): Wipro
[Link]='Wipro' Company Website:
[Link]='[Link]' [Link]
print("Company
Name:",[Link])
print("Company
Website:",[Link])
[Link]()

Polymorphism
Ability to have multiple forms
They are two types

PythonwithVenkat@[Link] [Link] P a g e 121


1. Over loading

Overloading is the ability of a method to behave in different ways


based on the parameters that are passed.
Overloading are 2 types
i. Method Overloading
ii. Constructor Overloading

i. Method Overloading
Method with same name and with different parameters is said to
be "Method Overloading".

PythonwithVenkat@[Link] [Link] P a g e 122


Program:
class Test: Output:
def sum(self,*n): Sum is : 15
sum=0 Sum is : 60
for i in n: Sum is : 8.6
sum+=i
print("Sum is : ",sum)
t = Test( )
[Link](5,10)
[Link](10,20,30)
[Link](5.2,3.4)

[Link] Overloading

Constructor with same name and with different parameters is said to be


"Constructor Overloading".

class Employee: Output:

def Employee Id is : 101


__init__(self,eid,ename,sal=0,dept=10):
Employee name :
[Link] = eid Raju

[Link] = ename Employee Salary:


5000
[Link] = sal
Employee dept : 20
[Link] =dept

PythonwithVenkat@[Link] [Link] P a g e 123


def show(self): Employee Id is : 102

print("Employee Id is : ",[Link]) Employee name : Ravi

print("Employee name : ",[Link]) Employee Salary:


7000
print("Employee Salary: ",[Link])
Employee dept : 10
print("Employee dept : ",[Link])
Employee Id is : 103
e1 = Employee(101,"Raju",5000,20)
Employee name :
e2 = Employee(102,"Ravi",7000) Rani
e3 = Employee(103,"Rani") Employee Salary: 0
[Link]() Employee dept : 10
[Link]()

[Link]()

2. Overriding
Override means having two methods with the same name
but doing different tasks. It means that one of the methods
overrides the other.

Overriding are two types

i. Method Overriding

ii. Constructor Overriding

PythonwithVenkat@[Link] [Link] P a g e 124


i. Method Overriding
Method with same name and with same parameters is said
to be "Method Overriding"

PythonwithVenkat@[Link] [Link] P a g e 125


Program:
class Shape: Output:
def draw(self): Draw Square
print(" Draw Shape ") Draw Circle
class Square(Shape): Draw Hexagon
def draw(self):
print(" Draw Square ")

class Circle(Shape):
def draw(self):
print(" Draw Circle ")

class Hexagon(Shape):
def draw(self):
print(" Draw Hexagon ")

s = Square( )
[Link]()
c = Circle( )
[Link]()
h = Hexagon( )
[Link]()

We can call super class method by using super( )


class Test: Output:
def m1(self): Test class m1-Method
print(" Test class m1-Method ") Demo class m2-Method
class Demo(Test):
def m2(self):
super().m1( )
print(" Demo class m2-Method
")

d = Demo()
d.m2( )
ii. Constructor Overriding
Constructor with same name and with same parameters is said to be
"Constructor Overriding".
Program:
class Loan: Output:
def __init__(self,lname,amount):

PythonwithVenkat@[Link] [Link] P a g e 126


[Link] = lname Customer id is : 101
[Link] = amount Customer name : Venkat
class Customer(Loan): Loan Name is : Home
def __init__(self,cid,cname): Amount is : 500000
super().__init__("Home",500000)
[Link] = cid
[Link] = cname
def show(self):
print(" Customer id is : ",[Link])
print(" Customer name :
",[Link])
print(" Loan Name is :
",[Link])
print(" Amount is :
",[Link])
c1=Customer(101,"Venkat")
[Link]( )

Assignments:

PythonwithVenkat@[Link] [Link] P a g e 127


1. What is OOPS?
2. What are the advantages of OOPS?
3. What are the principles of OOPS?
4. What is Abstraction?
5. What is Encapsulation?
6. How to achieve Encapsulation?
7. What is class?
8. Which keyword is used to define a class?
9. What is the syntax of class?
10. Why should we define variables in a class?
11. Why should we define methods in a class?
12. What is inheritance?
13. What is Polymorphism?
14. Is class and object are principles of OOPS?

PythonwithVenkat@[Link] [Link] P a g e 128


Case study:-
Consider that we are developing an application for a Engineering
college to maintain Student, Employee, Dept, Course Details?
Apply Abstraction, Encapsulation?
Identify the states, behaviours belong to particular classes?
Sno Hra Percentage SetCourse
sname tsal grade SetCredits
m1 experience bloodgroup SetCourseDuratio
m2 dateofjoin courseduration n
m3 offerdate SetStudent DisplayCourse
phoneno pfno GetStudent SetDept
emailid deptno SetEmpData DisplayDept
address dname CalculateTotal DisplayCredits
gender hodname GetEmpData GetHodinfo
qualificatio deptphno CalculatePercentag UpdateDept
n coursed e DeleteEmp
ename coursenam CalGrade AddStudent
eno e DisplayTotalMarks DeleteCourse
designation credits CalculateDa UpdateCourse
basicsal total CalculateHra CreateEmployee
da CalculateTsal SearchEmployee

PythonwithVenkat@[Link] [Link] P a g e 129


Q) Consider that we are developing an application for a Online Food
Order Management System like Swiggy?
Apply Abstraction, Encapsulation?
Identify the states, behaviours belong to particular classes?
Stated Eno SetLocation GetGstAmt
statename ename GetLocation SetDeliveryBoy
cityid doj AddLocation GetDeliveryBoy
cityname salary UpdateEmployee Update DeliveryBoy
locationid da ViewEmployee SetRestaurantTy0pe
locationname hra SetItems GetRestaurantType
streetid tsal UpdateStock CheckDeliveryStatus
streetname deliveryboyid GetPrice custid
ino deliveryboyname CheckStock custname
iname address SetCusine OrderFood
price resttypeid SetRestaurant CancelFood
qty resttypename GetRestaurant ChageDeliverAddress
cusineid SetState GetCusine ViewSales
cusinename GetState UpdateCusine AddStreet
restaurantid UpdateState ViewCusine DeleteStreet
restaurantname SetCity CreateEmployee UpdateStreet
restaurantaddress GetCity DeleteEmployee ViewStreet
phno CreateState CalDa
emailid CreateCity CalHra
noofoutlets UpdateLocation CalTsal

PythonwithVenkat@[Link] [Link] P a g e 130


Variables
1. What is a variable?
2. What is variable initialization?
3. How many types of variables are there in Python?
4. What is an instance variable?
5. Where should we declare Instance variables?
6. What is a static variable?
7. Where should we declare static variables?
8. What is a local variable?
9. Where should we declare local variables?
10. When the memory is allocated for instance variables?
11. When the memory is allocated for static variables?
12. How many times memory is allocated for static variable?
13. How many times memory is allocated for instance variable?
14. What is the scope of Instance variable?
15. What is the scope of static variable?
16. What is the scope of local variable?
17. How can we access static variables?
18. How can we access Instance variables?

PythonwithVenkat@[Link] [Link] P a g e 131


Ex1:
class Student:
collegename=' '
collegeaddress=' '
def SetStudent(self,no,name):
[Link]=no
[Link]=name
def CalTotal(self,m1,m2,m3):
[Link]=m1+m2+m3
def CalPercentage():
percentage = [Link] / 3;
def GetGrade():
grade = 'A'

Class Method Static Instance Local Method


name Names variables variables variables Parameters

PythonwithVenkat@[Link] [Link] P a g e 132


Ex2:
class Employee:
companyname=' '
companyaddress=' '
def SetEmp(self, no,name, sal):
[Link]=no
[Link]=name
[Link]=sal
def CalDa():
da = [Link] *0.2
def CalHra():
hra = [Link] *0.4

Classname MethodNames Staticvariables Instance Local Method


variables variables Parameters

1. Identify the static,instance,local 2. Identify the Line numbers


variables in the below where Error will occur
codesnippet
class A:
x=None class A:
y=None x
def m1(self): y=None
self.z=None def m1(self):
b=None self.z=None

PythonwithVenkat@[Link] [Link] P a g e 133


3. 4.
Write an instance method in a class to Write an static method in a class to
Assign 5 to x 3 to y, store sum of x and Assign 7 to x,4 to y, store sum of x
y in z and display z. and y in z and display z.

5. 6.
class A: Class A:
i def m1(self):pass
j=10 def m2(self):
print(i, j) a=100
b=200
Identify the O/p or Error in the print("Sum=",a+b)
Above code snippet obj=A()
obj.m2()

Identify the O/p or Error in the


Above code snippet

7. 8. Identify the O/p or Error


How many Outputs for the below
program class B:
class A: i=10
var1=100 print("i=",i)
print("var1=",var1) def display(self):
def display(self): self.j=20
self.var2=200 print("j=",j)
print("var2=",var2) def show():
def show(): k=300
var3=300 print("k=",k)

PythonwithVenkat@[Link] [Link] P a g e 134


print("var3=",var3) obj=A()
obj=A() display()
[Link]() show()
[Link]()

9. Identify error or output 10. What is the output of


class customer: the following code
def __init__(self): snippet:
[Link]=15 class Student:
def store(self): def __init__(self):
[Link]='raju' [Link]=10
c=customer() [Link]='raju'
print(c.__dict__) [Link]=65.7
[Link]() def display(self):
print(c.__dict__) print([Link])
[Link]=3455.7 print([Link])
print(c.__dict__) print([Link])
s=Student()
[Link]()

11. What is the output of the 12. Identify the error or


following Code snippet: output:

def f1(): class Employee:

global a def __init__(self):

a=10 [Link]=100

print(a) [Link]='Raju'

def f2(): [Link]=10000

print(a) print(self.__dict__)

e=Employee()

PythonwithVenkat@[Link] [Link] P a g e 135


13. Identify what variables are 14. What is the expected
used in following code snippet: output for the following
code snippet:
class Test:
class Test:
def __init__(self):
def __init__(self):
self.a=10
self.a=10
self.b=20
self.b=20
def m1(self):
self.c=30
self.c=30
self.d=40
t=Test()
def m1(self):
t.m1()
del self.d
print(t.__dict__)
t=Test()

print(t.__dict__)

t.m1()

print(t.__dict__)

del t.c

print(t.__dict__)

15. Identify the error or output

class Test:

def __init__(self):

self.a=11

PythonwithVenkat@[Link] [Link] P a g e 136


self.b=21

t1=Test()

t1.a=777

t1.b=999

t2=Test()

print('t1:',t1.a,t1.b)

print('t2:',t2.a,t2.b)

self

1) What is "self" in python?

2) Where "self" should be used?

3) What variables are prefixed with "self"?

4) What is the first parameter to an instance method and to constructor?


1. Identify the instance variables 2. Identify error or output
class Student: class Test:
def a=10
__init__(self,name,rollno,marks): def m1(self):
[Link]=name self.a=1000
[Link]=rollno t1=Test()
[Link]=marks t1.m1()
def display(self): print(Test.a)
print("Hello My Name print(t1.a)
is:",[Link])
print("My Rollno is:",[Link])
print("My Marks are:",[Link])
s1=Student('Raju',1122,80)

PythonwithVenkat@[Link] [Link] P a g e 137


[Link]()

3. Identify the output of the 4. Identify error or ouput


following code snippet: class Person:
class Student: def __init__(self):
def __init__(self,name,marks): [Link]='Raju'
[Link]=name [Link]=[Link]()
[Link]=marks def display(self):
def display(self): print('Name:',[Link])
print('Dear Student',[Link]) class Dob:
print('Your Marks def __init__(self):
are:',[Link]) [Link]=12
def grade(self): [Link]=6
if [Link]>=60: [Link]=1990
print('You got First Grade') def display(self):
elif [Link]>=50:
print('Yout got Second Grade') print('Dob={}/{}/{}'.format([Link],self.
elif [Link]>=35: mm,[Link]))
print('You got Third Grade') p=Person()
else: [Link]()
print('You are Failed') x=[Link]()
[Link]()
n=int(input('Enter number of
students:'))
for i in range(n):
name=input('Enter Name:')
marks=int(input('Enter Marks:'))
s= Student(name,marks)
[Link]()
[Link]()
print()

[Link] is expected output for the 6. Error or Output?


following code snippet? class Product:
class Product: def __init__(self,price):
def __init__(self,price): [Link]=price
[Link]=price def __lt__(self,second):
def __add__(self,second): if
[Link]<[Link]
e:

PythonwithVenkat@[Link] [Link] P a g e 138


return return "Product 1 price is less
[Link]+[Link] than Produnct 2 price"
ce else:
p1=Product(50) return "Product 2 price is less
p2=Product(100) than Product 1 price"
print("Total Bill=",p1+p2) p1=Product(20)
p2=Product(50)
print(p1<p2)

7. Identify error or output? 8. How many instance variables are


class Student: existed in the following code
def __init__(self,a,b,c,d,e): snippet?
[Link]=a class Customer:
self.s1=b def __init__(self):
self.s2=c [Link]=111
self.s3=d def CustomerDetails(self):
self.s4=e [Link]='Raju'
def calculation(self): c=Customer()
[Link]()
total=self.s1+self.s2+self.s3+self.s4 print(c.__dict__)
average=total/4 [Link]=50000.50
print("Total=",total) print(c.__dict__)
print("Average=",average)
s=Student('S1122',70,80,90,100)
[Link]()

[Link] is the expected output of 10. which constructor is executed in


the following code snippet the following code snippet:
class Sample: class Sample:
def __init__(self): def __init__(self):
self.i=int(input("Enter first self.i=int(input("Enter first
integer:")) integer:"))
self.j=int(input("Enter second self.j=int(input("Enter second
integer:")) integer:"))
class Simple: print(self.__dict__)
def __init__(self,a,b): def __init__(self):
Sample.__init__(self)

PythonwithVenkat@[Link] [Link] P a g e 139


self.k=a self.m=int(input("Enter first
self.m=b integer:"))
print(self.__dict__) self.n=int(input("Enter second
s=Simple(10,20) integer:"))
print(self.__dict__)
s=Sample()

Object
1. What is an object?
2. What is the syntax to create an object?
3. What is the purpose of object reference?
4. Identify Object & Object Reference in the following code?

obj=Employee()
5. Can we create object without reference variable?
6. How many objects can be created for one class?

Code snippets:
2. What object is created in the
1. In the following coding following code snippet and which
snippet object is method is called through object:
created or not
class Test: class Sample:
def m1(): def m1(self):
Test.a=100 self.i=10
def m2(): def m2(self):

PythonwithVenkat@[Link] [Link] P a g e 140


print("a=",Test.a) self.j=20
Test.m2() def m3(self):
self.m1()
self.m2()
print(self.__dict__)
Sample().m3()

4. Any object reference found in the


3. Identify the object following coding snippet:

class Test:
class Demo: def m1(self):
def __init__(self,a,b): a=1000
self.a=a print(a)
self.b=b def m2(self):
def m1(self): b=2000
print(self.__dict__) print(b)
Demo(1,2).m1() t=Test()
t.m1()
t.m2()

6. How many objects are created and


5. Identify the number of how many objects are destroyed:
objects and object
references: class Employee:
def __init__(self,i):
[Link]=i
class Student: def display(self):
def __init__(self,x): print([Link])
[Link]=x def __del__(self):
def display(self): print(id(self)," object is destroyed")
print([Link]) e1=Employee('E1122')
s1=Student(10) [Link]()
[Link]() e2=Employee('E2233')

PythonwithVenkat@[Link] [Link] P a g e 141


s2=Student(12) [Link]()
[Link]() del e1

Methods
1. What is a method?
2. What is logic?
3. In Python where should we write the logic?
4. What is the syntax for creating a method?
5. Which part of the method is called method signature?
6. Which part of the method is called body?
7. What is a method parameter?
8. How to define a static method in python?
9. How to define an instance method in python?
10. What is a parameterized method?
11. What is non-parameterized method?
12. How to call a static method?
13. How to call an instance method?
14. How to call one instance method in another instance method of same
class?
15. How to call one static method in another static method of same class?
16. How to call an instance method of one class in instance method of
another class?
17. How to call a static method of one class in static method of another
class?
18. What is the use of 'return' statement?
19. What is the difference between formal parameter and actual
parameter?

PythonwithVenkat@[Link] [Link] P a g e 142


20. Parameters (arguments) are categorized into how many types?
21. What is the first parameter of instance method?
22. How to access instance variables inside of instance method?
Code Snippets-
1.
class A:
def add(x,y):
print(x+y)
print([Link](10,20))

Method Keyword Return Method i/p parameters


Type type Name

Expected O/P:-

[Link] A:
def Sub(self,x,y):
return x-y
obj=A()
print([Link](20,10))

Method Return Method i/p parameters


Type type Name

Expected O/P:-

[Link] A:
def CalTotalMarks(m1,m2,m3):
total = m1 + m2 + m3
return total
print([Link](90,80,70))

PythonwithVenkat@[Link] [Link] P a g e 143


Method Keyword Return Method i/p Returnvalue
Type type Name parameters

Expected o/p:-

4. class A:
cbal = 5000
def Deposit(amt):
[Link] = [Link] + amt
return [Link]
print([Link](10000))

Method Return Method i/p returnvalue


Type type Name parameters

Expected o/p:-

5. class B:
def m1():
return B()
print(B.m1())

Method Return Method i/p returnvalue


Type type name parameters

Expected o/p:-

PythonwithVenkat@[Link] [Link] P a g e 144


Examples on Methods
1. Write a static method to print " Venkat Technologies "
2. Write a static method to return integer result of 2*3+4-5-7/6+5%2
3. Write a static method to return integer result of 2+3*5-8/2+9%2
4. Write an instance method to return "Object Oriented Programming" string.
5. Write an instance method namely M4 to take two parameters x,y and
return the integer result of sum of those two parameters.
6. Write an instance method namely M5 and return the integer result of M4
method
7. Write an instance method to return float result after adding one integer
number and one float number
8. Write a static method namely M8 to take one integer parameter and return
boolean value 'True' if integer parameter value is greater than 5
9. Write a static method namely M9 with return type boolean by calling M8
method inside of M9 method.
10. Write M1 instance method and M2 instance method and write M3
instance method to return the sum of M1 and M2 methods
11. Write an instance method to return an object of class.

PythonwithVenkat@[Link] [Link] P a g e 145


Exam:

Invoke the methods


class A:
def M1():
return "welcome to Python"
def M2():
return 2 * 3 + 4 - 5 - 7 / 6 + 5 % 2
def M3(x,y):
return x + y
def M4():
return M3(7, 4)
def M6(x):
return x + 2.3
def M7():
if 10 > 5:
return true
def M8():
return M7()
def M9():
b = False
if (M8()):
b = True
return b
def M10():
return 2 + 3 * 5 - 8 / 2 + 9 % 2
def M11():
return M2() + M10()

Code snippets:

1. Identify error or output 2. Identify the output


class Test: class Test:
def m1(): def m1(self):
Test.a=100 a=1000
def m2(): print(a)
print("a=",Test.a) def m2(self):
Test.m2() b=2000
print(b)
t=Test()
t.m1()
t.m2()

PythonwithVenkat@[Link] [Link] P a g e 146


4. What methods are used in the
3. Identify output or error following coding snippet and
class Test: identify the output
def m1(self): class Sample:
a=1000 def m1(self):
print(1) self.i=10
def m2(self): def m2(self):
b=2000 self.j=20
print(a) def m3(self):
print(b) self.m1()
t=Test() self.m2()
t.m1() print(self.__dict__)
t.m2() Sample().m3()

5. What output comes when m1() 6. Identify error or output. If error


method is executed: comes then what is the reason?
class Demo: class Demo:
def __init__(self,a,b): def method1(a):
self.a=a print(a**a)
self.b=b def method2(self):
def m1(self): method1(10)
print(self.__dict__) Demo().method2()
Demo(1,2).m1()

7. Identify error or output 8. What is the expected output of the


class Demo: following code snippet:
def __init__(self,a,b): class Test:
self.m=a def __init__(self,a,b):
self.n=b self.m=a
def m1(self): self.n=b
print(self.__dict__) def m1(self):
def m2(): print(self.__dict__)
self.m1() def m2():
Demo.m2() Test(1,2).m1()
Test.m2()

PythonwithVenkat@[Link] [Link] P a g e 147


9. What is the expected output 10. Identify the error or output
of the following code class Rectangle():
snippet: def __init__(self,length,breadth):
class Student: [Link]=length
def __init__(self,x): [Link]=breadth
[Link]=x def area(self):
def display(self): return [Link]*[Link]
print([Link]) a=int(input("Enter the length of
s1=Student(10) rectangle:"))
[Link]() b=int(input("Enter the breadth of
s2=Student(12) rectangle:"))
[Link]() obj=Rectangle(a,b)
print("Area of rectangle:",[Link]())

12. Identify error or output:


11. Identify the output of class Student:
the following code def calculate(self,data):
snippet: n=len(data)
import math sum=0
class Circle: for x in data:
def __init__(self,radius): sum=sum+x
[Link]=radius avg=sum/n
def area(self): return sum,avg
return marks=[int(x) for x in input("Enter the
[Link]*([Link]**2) marks:").split()]
def perimeter(self): print("marks=",marks)
return 2*[Link]*[Link] r1,r2=Student().calculate(marks)
radius=int(input("Enter the radius print("Total:",r1)
of a circle:"))
obj=Circle(radius) print("Average:",r2)
print("Area of
circle:",round([Link](),2))
print("Perimeter of
circle:",round([Link](),2))

PythonwithVenkat@[Link] [Link] P a g e 148


13. What is the output of code 14. Identify error or output
snippet: class Employee:
class calculate: def
def lcm(self,a,b): __init__(self,eno,ename,esal):
if a>b: [Link]=eno
big=a [Link]=ename
else: [Link]=esal
big=b def display(self):
while(True): print('Employee
Number:',[Link])
if((big%a==0)and(big%b==0)): print('Employee
lcm=big Name:',[Link])
break print('Employee
big+=1 Salary:',[Link])
return lcm class Test:
n1=int(input("Enter first number:")) def modify(emp):
n2=int(input("Enter second [Link]=[Link]+10000
number:")) [Link]()
print("The LCM of ",n1,"and",n2," e=Employee(100,'Raju',10000)
is:",calculate().lcm(n1,n2)) [Link](e)

[Link] the output of the


following code Snippet:
class Outer:
def __init__(self):
print("outer class object
creation")
class Inner:
def __init__(self):

PythonwithVenkat@[Link] [Link] P a g e 149


print("inner class object
creation")
def m1(self):
print("innerclassmethod")
o=Outer()
i=[Link]()
i.m1()

Constructors
1. What is a constructor?
2. How to define a constructor?
3. How many types of constructors will Python supports?
4. What is the difference between non-parameterized and
parameterized constructor?
5. What are the differences between Instance methods and
constructors?

Code Snippets:
1. Which of the following ways are correct to create an object of
the Sample class.
class Sample:
def __init__ (self, ii, jj, kk):
self.i = ii
self.j = jj
self.k = kk

A. s1 = Sample()
B. S2 = Sample(10)
C. s3 = Sample(10, 20)
D. S4 = Sample(10, 20, 30)

PythonwithVenkat@[Link] [Link] P a g e 150


E. S5 = Sample(, , 30)
F. S6= Sample(None,20,None)

2. What will be the output of the code snippet given below?


class Sample:
def __init__(self):
print(" Sample class ")
def m1(self):
print("m1 method ")
Sample().m1()

3. What will be the output of the code snippet given below?


class Bank:
def __init__(self,a,b,c,d):
[Link]=a
[Link]=b
[Link]=c
[Link]=d
print(self.__dict__)
Bank(112233445566,'Savings',None,None)
Bank(778899001122,None,'HDFC9988',100000)
Bank(None,None,None,200000)

PythonwithVenkat@[Link] [Link] P a g e 151


Inheritance in Python
 Getting Properties from one class to another class is called as
inheritance
 The class which provides properties is called as parent class
 The class which uses properties is called as child class

 In Inheritance main advantage is code-reusability


 Based on number of parent and child classes inheritance are classified
into different types, They are
1. Single Inheritance
2. Multi-level inheritance
3. Hierarchical inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

Note:- In Inheritance, if we create object for parent class we can access only
parent class members,

If you create object for child class then we can access all the properties of
parent and child classes

Syntax:

PythonwithVenkat@[Link] [Link] P a g e 152


Class Parentclass :
Method
Variables
Class childclass(Parentclass) :
Methods
Variables

1. Single Inheritance

 In Single Inheritance we have only one parent class and one child class

Ex:-
class Test:
def show(self):
print(" Test class show Method ")
class Demo(Test):
def display(self):
print(" Demo class Display method ")

d = Demo( )

PythonwithVenkat@[Link] [Link] P a g e 153


[Link]()
[Link]()

Output :- Test class show Method


Demo class Display method

Ex2:-

class Test:
def assign(self):
self. a = 5
self. b = 7
class Demo(Test):
def display(self):
self. c = self.a + self. b
print(" Sum is : ",self.c)
d = Demo( )
[Link]()
[Link]()

Note:- When we create object, it just stores method names, when you call method
then only memory is allocated for instance variable

PythonwithVenkat@[Link] [Link] P a g e 154


 If we have constructor, if you create object for child class it will execute
only child class constructor

Ex:-

class Test:
def __init__(self):
print(" Test class default constructor ")
class Demo(Test):
def __init__(self):
print(" Demo class default Constructor ")
d = Demo( )

Output:

Demo class default Constructor

 If you don’t have constructor in child class then only it checks parent class
constructor, in case parent class contains constructor then it will execute
parent class constructor
 class Test:
def __init__(self):
print(" Test class default constructor ")
class Demo(Test):
def show(self):
print(" Demo class show ")
d = Demo( )

PythonwithVenkat@[Link] [Link] P a g e 155


Output :- Test class default constructor

 If we want to access super class constructor then we have to use super( )


function
 Super( ) function is used to access parent class instance method,
constructor, and static method
 By using super( ) we cannot access parent class instance variable
 Instance variable must be accessed only by using self

Ex:-

class Test:
def __init__(self):
print(" Test class default constructor ")
class Demo(Test):
def __init__(self):
super().__init__()
print(" Demo class default Constructor ")
d = Demo( )

Output:-

Test class default constructor

Demo class default Constructor

Ex2:

class Test:
def __init__(self):
print(" Test class default constructor ")
class Demo(Test):
def __init__(self):

PythonwithVenkat@[Link] [Link] P a g e 156


print(" Demo class default Constructor ")
super().__init__( )
d = Demo( )

Output:

Demo class default Constructor


Test class default constructor

 If you have instance variable in constructor then when ever you create
object then automatically it will load into memory

Ex:-

class Test:
def __init__(self):
self.a = 5
self.b = 10
class Demo(Test):
def __init__(self):
super().__init__()
self.c = 30
def display(self):
print(" a value is : ",self.a)
print(" b value is : ",self.b)
print(" c value is : ",self.c)

d = Demo( )
[Link]()

Output: -

a value is : 5
b value is : 10
c value is : 30

PythonwithVenkat@[Link] [Link] P a g e 157


 If you have parameterized constructor then at the time of calling super
class constructor pass arguments also
Ex:-
class Test:
def __init__(self,p,q):
self.a = p
self.b = q
class Demo(Test):
def __init__(self):
super().__init__(5,9)
self.c = 30
def display(self):
print(" a value is : ",self.a)
print(" b value is : ",self.b)
print(" c value is : ",self.c)

d = Demo( )
[Link]()

Output:
a value is : 5
b value is : 9
c value is : 30
Ex2:
class Test:
def __init__(self,p,q):
self.a = p
self.b = q
class Demo(Test):
def __init__(self, x):
super().__init__(5,9)
self.c = x
def display(self):
print(" a value is : ",self.a)
print(" b value is : ",self.b)
print(" c value is : ",self.c)

d = Demo(10)
[Link]()

PythonwithVenkat@[Link] [Link] P a g e 158


Overloading
------------------
 If we have more than one method with same name but different
parameters then it is called as Method Overloading

class Test:
def add(self):
print(" Test class Default add method ")
def add(self,a,b):
print(" Test class 2-param add Method ")

t = Test( )
[Link]()
[Link](5, 7)

Output : Error
 In all other programming languages , based on method name and
parameters we can call, so that method only executed
 But in python, If we write more than one method with same name
Then it will override
Ex;
class Test:
def add(self):
print(" Test class Default add method ")
def add(self,a,b):
print(" Test class 2-param add Method ")

t = Test( )
[Link](10,20)
[Link](5, 7)

 In above program only one method is available , that is the latest method
means add(self,a,b) method
 In Python Method overloading is not possible directly

PythonwithVenkat@[Link] [Link] P a g e 159


 If we want to perform method over loading python provides called
default arguments / variable length arguments
Ex:-
class Test:
def add(self,a = None, b=None):
if(a == None and b == None):
print(" Test class default add Method ")
else:
print(" Test class 2-param add Method ")

t = Test( )
[Link]()
[Link](5, 7)

Output:-
Test class default add Method
Test class 2-param add Method

Ex2:
class Test:
def add(self,*a):
s=0
for i in a :
s=s+i
print(" Sum is : ",s)

t = Test( )
[Link](5, 7)
[Link](7,3,8,2)
[Link](2.5,6,7.4,9)

PythonwithVenkat@[Link] [Link] P a g e 160


Method Overloading

class Payment:
def payAmount(self,phno=None,upi=None, accno=None,amt=None):
if(phno!=None):
print(" Customer is paying Amount using ",phno)
elif(upi!=None):
print(" Customer is paying Amount using ",upi)
else:
print("Customer is paying Amount using Netbanking ")
print(accno,"\t",amt)
c1=Payment()
c2=Payment()
c3=Payment()
[Link](phno=8074864650)
[Link](upi="python@[Link]")
[Link](accno=11221,amt=5000)

PythonwithVenkat@[Link] [Link] P a g e 161


Method Overriding

class RBI:
def calInterest(self,amount,t):
r = 4.8
self.i = amount * t * r / 100
print(" Interest Amount is : ", self.i)
class SBI(RBI):
def calInterest(self,amount,t): # Overriding
[Link] = amount
r = 6.4
self.i = [Link] * t * r /100

PythonwithVenkat@[Link] [Link] P a g e 162


print(" Interest Amount is : ",self.i)
def calFinalAmt(self):
[Link] = [Link] + self.i
print("Final Amount is : ",[Link])

class ICICI(RBI):
def calFinalAmt(self,amt):
[Link] = amt + self.i
print(" Final Amount is : ",[Link])

print(" From SBI Customer ")


s = SBI()
[Link](50000, 3)
[Link]()
print(" From ICICI Customer ")
c = ICICI()
[Link](50000,3)
[Link](50000)

Poly Morphism
---------------------
 Poly morphism means many forms

def add(a,b):

c=a+b

print( c )

add(5, 9) # 14

add(2.5, 3.7) # 6.2

add(“Adv”, “ Python”) # Adv Python

PythonwithVenkat@[Link] [Link] P a g e 163


PolyMorphsim
Static Ploymorphsim  OverLoading
Dynamic Polymorphsim  Overriding

Multi-level inheritance

--------------------------------

 One class will act as parent and child then that inheritance is called as
multi level inheritance

 class RBI:
def register(self):
self. a = 10
print(" Every Bank has to Register in RBI ")
class ICICI(RBI):
def createAccount(self):
self. b = 20
print(" Every Customer has to take Account ")
class Customer(ICICI):
def login(self):
self.c = 30
print(" Every one Login then access your data ")
def show(self):

PythonwithVenkat@[Link] [Link] P a g e 164


print(" a value is : ",self.a)
print(" b value is : ",self.b)
print(" c value is : ",self.c)
c = Customer()
[Link]()
[Link]()
[Link]()
[Link]()

Output:-

Every Bank has to Register in RBI

Every Customer has to take Account

Every one Login then access your data

a value is : 10

b value is : 20

c value is : 30

Multiple Inheritance

 More than one parent and one child class is called as Multiple
Inheritance

class ICICI:
def login(self):
self.a = 10
print("ICICI Bank Login")

PythonwithVenkat@[Link] [Link] P a g e 165


class CreditCard:
def applyCard(self):
self.b = 20
print(" Credit card apply ")

class Customer(ICICI,CreditCard):
def show(self):
print(self.a)
print(self.b)
c = Customer()
[Link]()
[Link]()
[Link]()

Ex2:
class A:
def show(self):
print("A class show method")
class B:
def show(self):
print("B class show method")
class C(A,B):
def display(self):
print("C class Display")
obj = C()
[Link]()
[Link]()
[Link]()

PythonwithVenkat@[Link] [Link] P a g e 166


Hybrid Inheritance

Inheritance
1. What is inheritance?
2. What are the types of inheritance?
3. How can we implement inheritance in Python?
4. How many child classes can inherit from a parent class?

PythonwithVenkat@[Link] [Link] P a g e 167


1. Does Inheritance Exist in the
below program 2. Identify the no of variables
available in A class and B class
class A:
a=None class A:
class B: x=None
b=None y=None
class B:
z=Non

3. Identify the no of variables


available in B class 4. Identify the no of variables
class A: available in B class
def __init__(self):
self.a=self.b=None class A:
class B(A): def __init__(self):
def __init__(self): self.a=self.b=None
super().__init__() class B(A):
self.c=self.d=None def __init__(self):
print(B().__dict__) self.c=self.d=None
print(B().__dict__)

6. Identify the type of inheritance


5. Identify the Type of
inheritance class A:
class A: i=None
a=b=None class B:
class B(A): k=None
c=d=None class C(A,B):
m=None

7. Identify the type of inheritance? 8. Identify the type of inheritance?


class A: class A:
a1=a2=None i1=i2=None
class B(A): class B(A):
b1=b2=None j1=b2=None

PythonwithVenkat@[Link] [Link] P a g e 168


class C(B): class C(A):
c1=c2=None k1=k2=None
class D(B,C):
m1=m2=None

9. Identify the type of inheritance? 10. Identify the type of inheritance?


class A: class A:
ab1=ab2=None a1=a2=None
class B(A): class B(A):
ba1=ba2=None b1=b2=None
class C(A): class C(B):
ca1=ca2=None c1=c2=None
class D(B):
d1=d2=None

11. Identify object of B class 12. Identify object of C class


contains which Instance variables contains which Instance variables
and write the output? and write the output?

class A: class B:
def __init__(self): def __init__(self):
self.i=self.j=None self.a=self.b=None
class B(A): class C(B):
def __init__(self): def __init__(self):
self.m=self.n=None super().__init__()
obj=B() self.c=self.d=None
print(obj.__dict__) b1=C()
print(b1.__dict__)

13. Identify the output 14. Identify error or output


class A1: class A:
def __init__(self): def m1():
self.a=self.b=None print("Static method1")
class A2(A1): def m2():
def __init__(self): A.m1()
A1.__init__(self) print("Static method2")
self.c=self.d=None class B(A):

PythonwithVenkat@[Link] [Link] P a g e 169


obj=A2() def m3():
print(obj.__dict__) A.m2()
print("Static method3")
B.m3()

15. Identify error or output


class A:
def m1(self):
print("Instance method1")
def m2(self):
A.m1(self)
print("Instance method2")
class B(A):
def m3(self):
A.m2(self)
print("Instance method3")
B().m3()

Polymorphism
1. What is a Polymorphism?
2. What is Operator Overloading?
3. What is Method overriding?
4. Can we override static method?
5. Can we override instance method?
6. Can we override constructor?
7. Can u give examples for Method overriding, Constructor Overriding?
8. Is it possible to override a method in the same class?

1. Identify what operator is overloaded 2. Identify the type of overriding and


and what is the output? what is the output?

PythonwithVenkat@[Link] [Link] P a g e 170


class A: class A:
def __init__(self): def m1(self):
self.a=100 print("Class A")
def __add__(self,other): class B(A):
return self.a+other.a def m1(self):
i=A() print("Class B")
j=A() obj=B()
print(i+j) obj.m1()

3. Identify the type of method overriding 4. Identify the type of Overriding and
and what is the output? what is the output?
class A: class A:
def m1(): def __init__(self):
print("A") print("Class-A")
class B(A): class B(A):
def m1(): def __init__(self):
print("B") print("Class-B")
B.m1() obj=B()

5. Identify the types of overriding and 6. Identify whether compile-time error


write the output? or run-time error or no output:
class A: class A:
def __init__(self): def __init__(self):
print("Class-A constructor is self.i=100
executed") self.j=200
def m1(self): def m1(self):
print("Class-A instance method is print(self.i,self.j)
executed") class B(A):
def m2(): def m1(self):pass
print("Class-A Static method is B().m1()
executed")
class B(A):
def __init__(self):
print("Class-B constructor is
executed")
def m1(self):
print("Class-B instance method is
executed")
def m2():
print("Class-B static method is
executed")
B.m2()
obj=B()

PythonwithVenkat@[Link] [Link] P a g e 171


obj.m1()

7. Identify error or output [Link] error or output or no output.


class A: If no output then what is the reason?
def m1(): class A:
A.i=100 def f1():
A.j=200 A.a=111
print(A.i,A.j) A.b=222
class B(A): print(A.a,A.b)
def m1(): class B(A):
A.m1() def f1():
B.m1() A.f1()
class C(B):
def f1():pass
C.f1()

9. Identify error or output 10. Identify error or output


class A: class A:
def __init__(self,a,b): def __init__(self,i,j):
self.i=a self.a1=i
self.j=b self.a2=j
class B(A): class B(A):
def __init__(self,a,b): def __init__(self,m,n):
super().__init__(3344,4455) A.__init__(self,None,None)
self.k=a self.b1=m
self.m=b self.b2=n
def m1(self): def m1(self):
print(self.__dict__) print(self.__dict__)
B(5566,6677).m1() B(200.678,500.78).m1()

PythonwithVenkat@[Link] [Link] P a g e 172


Chapter-2
Exception Handling

PythonwithVenkat@[Link] [Link] P a g e 173


Error:
----------
--> The mistakes in our program are called as Errors
--> Errors are 3 types
1) Syntax Errors :- If you are not following the syntaxes, then we are
getting syntax Errors
Ex:-
print(" hai ') --> Syntax Error
if(n>0) --> Syntax Error

2)Logical Errors :- While Writting logics if you any mistakes


then they are called as logical errors
Ex:- amount = amount + wamt --> Logical Error

3) Exceptions:- The Errors occurred at runtime , they are called as


Exceptions

--> Exception means Runtime Errors

Ex:-
x = int(input("Enter any Number : "))
y = int(input("Enter any Number : "))
z = x // y
print(" Division is : ",z)
a=x+y
print(" Sum is : ",a)
print(" Thank You ... ")
Output:
Enter any Number : 10
Enter any Number : 2
Division is : 5

PythonwithVenkat@[Link] [Link] P a g e 174


Sum is : 12
Thank You ...

Output2:
Enter any Number : 10
Enter any Number : 0
ZeroDivisionError: integer division or modulo by zero

Note:- Whenever Runtime error , then entire program execution is stop.

Statement -1 --> Exception means runtime Error,


--> Exceptions occurs because of invalid input or wrong data
--> When ever Exception occur Program Execution will be terminated without
executing reaming line of code
--> To Handle Exceptions, we have a concept called Exception Handling

Exception Handling
-------------------------------
--> Handling of Exception is called as Excption handling
--> In Python, We can handle Exception by using
* try --> The problematic code --> The code which gives exception
* except --> When ever exception occurs then only except will executed
* else --> If there is no Exception, then only else block is executed
* finally --> Whether Exception occur or not finally block is always executed

Note:- Handling of Exception means it will not remove the Exception , but it will
display the cause of Exception then continue the program

Ex:-

x = int(input("Enter any Number : "))


y = int(input("Enter any Number : "))
try:
z = x // y
print(" Division is : ",z)
except:

PythonwithVenkat@[Link] [Link] P a g e 175


print(" Exception Occurred because of y value ")
a=x+y
print(" Sum is : ",a)
print(" Thank You ... ")

Syntax:

try
-----
try:
Statement-1
Statement-2
except
----------

1) except :
Statement

2) except ExceptionName:
Statement-1
Statement-2

3) except Exception1, Exception2, Exception3, ....:


Statement-1
Statement-2

4) except ExceptionName as variable :


Statement-1
Statement-2
5) except (Exception1,Exception2,Exception3, ....) as Variable :

Statement -2

Ex:
x = int(input("Enter any Number : "))
y = int(input("Enter any Number : "))
try:
z = x // y

PythonwithVenkat@[Link] [Link] P a g e 176


print(" Division is : ",z)
except ZeroDivisionError as zde:
print(zde)
print(" Thank you ")

Output:
Enter any Number : 10
Enter any Number : 0
integer division or modulo by zero
Thank you

--> For a Single try block we can write more than one except block

x = int(input("Enter any Number : "))


y = int(input("Enter any Number : "))
try:
z = x // y
print(" Division is : ",z)
except NameError as n:
print(n)
except ZeroDivisionError as zde:
print(zde)
print(" Thank you ")

Output:
Enter any Number : 10
Enter any Number : 0
integer division or modulo by zero
Thank you

PythonwithVenkat@[Link] [Link] P a g e 177


Exception class Hierarchy
-----------------------------------------

Note:- Every Exception in python is a class, Every Exception in python will be a subclass of
Exception class which is subclass of Base Exception
 Super class for All Exception is “Exception” class
 Super most class for All Exceptions is “BaseException”
 Exception is a class which will handle all types of Exception, because it is parent class for
all Exceptions

try-except-else
---------------------

x = int(input("Enter any Number : "))


y = int(input("Enter any Number : "))
try:
z = x // y
except ZeroDivisionError:
print(" Y Value should not be Zero for Division ")
else:
print(" Division is : ",z)

PythonwithVenkat@[Link] [Link] P a g e 178


print(" Thank you ")

finally
---------
--> finally block contain a group of statements which can perform code cleanup activites
like releasing the files, memory, connection etc..

x = eval(input("Enter x value : "))


y = eval(input('Enter y value : '))
try:
z = x // y
except ZeroDivisionError:
print("Y value should not be Zero")
else:
print(" Division is : ",z)
finally:
print("Conneciotn close logic ")

print("Thank you ")

Note: When we communicate with files, or database then we have to use finally block to close
those connections once our task is over.

Ex2:
x = int(input("Enter x value : "))
y = int(input('Enter y value : '))
try:
z = x // y
except NameError:
print("Y value should not be Zero")
else:
print(" Division is : ",z)
finally:
print("Resorce close logic ")

print("Thank you ")

--> For one try block we can write more than one except blocks

try:

PythonwithVenkat@[Link] [Link] P a g e 179


a = int(input("Enter any Number : "))
b = int(input("Enter any number : "))
c = a // b
print(" Division is : ",c)
except ZeroDivisionError:
print(" B value should not be zero ")
except ValueError:
print(" a and b should be integers only ")
print("Thank You")

Ex2:
try:
a = int(input("Enter any Number : "))
b = int(input("Enter any number : "))
c = a // b
print(" Division is : ",c)
except ZeroDivisionError:
print(" B value should not be zero ")
except ValueError:
print(" a and b should be integers only ")
except:
print(" Exception Occured ")
print("Thank You")

Rules of try, except, finally and else


------------------------------------------------
--> A try must be followed by either except or finally
Ex:-
try:
.............
except :
................
Ex2:
try:
.............

finally :
................
-->An else block can be followed by except
Ex:
try:
............
except:

PythonwithVenkat@[Link] [Link] P a g e 180


...........
else:
...........
--> A try can contain any number of except blocks
Ex:
try:
.............
except exceptionclass:
.............
except exceptionclass:
..............
--> if you are specifying multiple except blocks then the default except must be specified as the
last except

Nested try:
----------------
--> A try inside of another try is called as nested try

Ex:
try:
a = int(input("Enter any Number : "))
b = int(input("Enter any Number : "))
try:
c = a // b
print(" C value is : ",c)
except ZeroDivisionError:
print("b value should not be zero ")
except ValueError:
print(" a and b should be integer only ")

print("Thank you")

--> If Exception occur at outer try block, then outer except block is executed
--> If Exception occur at inner try block, then inner except block is executed
--> If Exception occur at outer level, then it will check only in outer except block, if match occurs
then
it will handle the exception otherwise program is terminated
-->If Exception occur at inner try then first it check inner except block, if match occur then it will
executed
otherwise it will check outer except , if it match then it will execute otherwise program is
terminated

Example2:

PythonwithVenkat@[Link] [Link] P a g e 181


try:
a = int(input("Enter any Number : "))
b = int(input("Enter any Number : "))
try:
c = a // b
print(" C value is : ",c)
except ValueError:
print("a and b should be integer only ")
except ZeroDivisionError:
print(" b value should not be zero ")
print("Thank you")

Output:
Enter any Number : 2.5
Traceback (most recent call last):
File "E:/Python/OnlineClasses/PythonPrgms/AllPrg/Exceptions/[Link]", line 2, in
<module>
a = int(input("Enter any Number : "))
ValueError: invalid literal for int() with base 10: '2.5'

Example3:

try:
a = int(input("Enter any Number : "))
b = int(input("Enter any Number : "))
try:
c = a // b
print(" C value is : ",c)
except ValueError:
print("a and b should be integer only ")
except ZeroDivisionError:
print(" b value should not be zero ")
print("Thank you")

Output:

Enter any Number : 5


Enter any Number : 0
b value should not be zero
Thank you

PythonwithVenkat@[Link] [Link] P a g e 182


raise
--------
--> raise keyword can be used for explicitly raising or generating the exception

Syntax: raise Exceptionname

Userdefined Exceptions
---------------------------------
--> The exceptions that are created by Programmer is called as user-defined exceptions

Procedure to create userdefiend exceptions


-----------------------------------------------------
--> Every Pre defined exception in python is a class, so user defined exception should be
class only
--> Every predefined exception in python is a subclass of Exception class , so user defined
Exception class also child class of Exception
--> we have to use raise keyword to create user defined exception class object
--> In Every user defined exception we have to specify a constructor to display the
description of the exception

Ex:-
class SmallAgeException(Exception):
def __init__(self,msg):
[Link] = msg

age = int(input("Enter your Age : "))


if(age<22):
raise SmallAgeException(" You are not Eligible for apply job ")
else:
print(" Apply job ")
print(" Thank you ")

Ex2:-
class SmallAgeException(Exception):
def __init__(self,msg):
[Link] = msg

PythonwithVenkat@[Link] [Link] P a g e 183


age = int(input("Enter your Age : "))
try:
if(age<22):
raise SmallAgeException(" You age is small to Apply job ")

except SmallAgeException as e:
print(e)
else:
print(" Apply job ")

print(" Thank you ")

Assignments:
1. What is an Error?
2. How many types of errors are there?
3. What is a compile time error?
4. What is an exception?
5. Why exceptions occur?
6. How many types of exceptions are there?
7. What is exception handling?
8. What are the keywords used in exception handling?
9. What is predefined exception?
10. What is user defined exception?
11. What is the most super class for all exception classes?

PythonwithVenkat@[Link] [Link] P a g e 184


Code Snippets:

1. Identify whether exception 2. Identify compile-time error or


handling is done or not in the run-time error or output
following code:
class A: try:
def __init__(self): i=10
self.a=100 j=0
def __add__(self,other): print(i/j)
return self.a+other.a
i=A()
j=A()
print(i+j)

3. Identify Compile-time error or run- 4. Identify the output


time error or output: try:
try: i=10
i=10 j=0
j=0 print(i/j)
print(i/j) except ValueError:
except ValueError: print("Invalid Value")
print("Invalid Value") except ZeroDivisionError:
print("Division by Zero")

5. Identify error or output: [Link] error or output


try: try:
i=10 i=10
j=0 j=0
print(i/j) print(i/j)
except:pass try:
a=int(input("Enter an integer:"))
except ValueError:

PythonwithVenkat@[Link] [Link] P a g e 185


print("Value Error is occurred")

7. What output comes in the following 8. What is the expected output of


code snippet: the following code snippet?
try: try:
a=111 str1=input("Enter first String:")
b=0 str2=input("Enter second string:")
print(a/b) print(str1+str2)
try: except:
m=float(input("Enter a float number:")) print("Please enter strings")
try: finally:
n=int(input("Enter an integer:")) del str1,str2
print(m*n)
except:
print("Please Enter an integer
value")
except:
print("Please Enter float value")
except:
print("Division by zero")

[Link] 'except' block is executed if 10.


Invalid input is given? i) What is expected output if integer
try: value is entered?
i=float(input("Enter Float Value:")) ii) What is expected output if non-
print("Entered Float value=",i) integer value is entered?
except ZeroDivisionError: try:
print("Division by zero") i=int(input("Enter first integer:"))
except ValueError: print("Entered integer value=",i)
print("Float value is expected") except ValueError:
except NameError: print("Integer value is expected")
print("Name Error is occurred") try:
finally: j=float(input("Enter float value:"))
i=None print("Entered float value=",j)
except:
print("Float value is expected")

PythonwithVenkat@[Link] [Link] P a g e 186


Chapter-3
File Handling

PythonwithVenkat@[Link] [Link] P a g e 187


File Handling
A file stores data permanently.
File Handling means to perform the number of operations on files.
The following are the types of operations to be performed on files:
 Opening a file
 Writing data to a file
 Reading data from a file
 Closing a file

Types of Files:
There are two types of files:
1. Text Files store:
i) Alphabets(A-Z,a-z)
ii) Digits(0-9)
iii) Symbols: ~ ` ! @ # $ % ^ & * ( ) ; . " , ' ? / \ < > | - _

2. images files, audio files, video files, executable files are Binary files.
File Modes:
"File Mode" specifies the type of operation to be performed on the file. The
following are the file modes in python:
r Read operation
w Write operation
a append operation
r+ read and write operations
w+ write and read operations

PythonwithVenkat@[Link] [Link] P a g e 188


a+ append and read operations
rb read data from binary file
wb write data to binary file
ab append data to binary file
r+b read and write on binary file
w+b write and read on binary file
a+b appen and read on binary file

Writing Data to a file:


[Link]
f=open("[Link]",'w')
[Link]("Python Programming language is used to develop multiple types of
applications\n")
[Link]("Application Development is fast with Python programming language
\n")
print("Data written to the file successfully")
[Link]()

Reading the data from a file:


[Link]
f=open("[Link]",'r')
data=[Link]()
print(data)
[Link]()

Working with the methods of file object


The following methods are used with file object.
open()

PythonwithVenkat@[Link] [Link] P a g e 189


write()
read()
close()

CSV Module
-----------------
 Camma separated value
--> To work with csv files , then we have to import csv module
--> CSV means comma separated value file
Eno Ename Salary
1 Venkat 50000
2 Vishnu 30000
In CSV Format is
Eno,Ename,salary
1,Venkat,50000
2,Vishnu,30000

File extension is .csv


 Write data into file
import csv
f= open('[Link]','w',newline='')
w = [Link](f)
[Link](['Eno','Ename', 'ESal'])
[Link]([101, 'Ravi' , 5000.0])
[Link]()

 Read data from file


 import csv
f = open('[Link]','r')
d = [Link](f)
#print(d)
for x in d:
for y in x:
print(y,end='\t')
print()
[Link]()

PythonwithVenkat@[Link] [Link] P a g e 190


Task:-
Write 5 rows in to your csv file dynamically

import csv
f= open('[Link]','w',newline='')
w = [Link](f)
[Link](['Eno','Ename', 'ESal'])
ch = 'y'
while(ch=='y'):
eid = int(input("Enter Emp id : "))
ename = input("Enter Emp Name : ")
sal = float(input("Enter salary :"))
[Link]([eid,ename,sal])
ch = input("Do you want to store other
records(y/n) : ")
[Link]()
print(" All Records are stored in empdata1 file ")

pickling and unpickling

pickling :
It is a process of converting an object into a stream of bytes
Unpickling:
It is a process of converting a stream of bytes into object
1) dump( ) :- This function is used to serialize an object
2) load() :- This function is used to de-serialize an object
The dump( ) and load( ) are available in pickle module
Ex1
import pickle
class Employee:
def __init__(self,eid,ename,sal):
[Link] = eid
[Link] = ename
[Link] = sal

PythonwithVenkat@[Link] [Link] P a g e 191


def display(self):
print(" Emp id is : ",[Link])
print(" Emp name : ",[Link])
print(" Emp Salary : ",[Link])

f = open("[Link]","wb")
e = Employee(101,"Vishnu",50000)
[Link](e,f)
[Link]()
print(" Your object is stroed in file ")

f = open("[Link]","rb")
a = [Link](f)
[Link]( )

Ex2:-
# Read object data from file
import pickle
from Files import pickelEx1
f = open("[Link]","rb")
e = [Link](f)
[Link]( )

OS Module
---------------
1) getcwd( ):- It will return the current working directory
import os
d = [Link]()
print(" Your Current working dir is : ",d)

2) mkdir( ) :- it is used to create directory

import os
[Link]("Test")
print(" Test Directory is created in your current location ")

Ex2:
import os
[Link]("E:\Python\OnlineClasses\PythonPrgms\ModuleEx\Test")
print(" Test Directory is created ")
Note:- If we specify path, then folder is created in that location

PythonwithVenkat@[Link] [Link] P a g e 192


3) rmdir( ) :- It is used to remove the directory
import os
[Link]("Test")
print(" Test dir is removed ")

4)listdir( ): it will display all the contents of the directory

import os
t = [Link]("E:\Python\OnlineClasses\PythonPrgms\ModuleEx")
print(t)

pypi
Python Package Index
Pip
pip is a package manager for Python. it’s a tool that allows you to install and manage
additional libraries

--> If you want to install any library, we have to open "[Link]" website

Microsoft Windows [Version 10.0.17763.1217]


(c) 2018 Microsoft Corporation. All rights reserved.

C:\Users\Venkat>pip list
Package Version
---------- -------
pip 19.2.3
setuptools 41.2.0
xlwt 1.3.0
WARNING: You are using pip version 19.2.3, however version 20.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\Users\Venkat>python -m pip install --upgrade pip


Collecting pip
Downloading
[Link]
a38388954d01d3f2e821d/[Link] (1.5MB)
|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 1.5MB 595kB/s
Installing collected packages: pip
Found existing installation: pip 19.2.3
Uninstalling pip-19.2.3:
Successfully uninstalled pip-19.2.3

PythonwithVenkat@[Link] [Link] P a g e 193


Successfully installed pip-20.1.1

Matplotlib Module
--------------------------
In Command prompt c:\> pip install matplotlib
# To Display bar graph
from matplotlib import pyplot as p
x = [1,2,3,4]
y = [75, 42, 98, 69]
[Link](x,y,color='b')
[Link]("year")
[Link]("Sales in thousands")
[Link]("Sales Report")
[Link]()

# To Display pie graph


from matplotlib import pyplot as p
seats =[125,76,40,12,90]
areas =['Hyd','Bang','Vizag','Delhi','che']
col = ['blue','green','pink','purple','orange']
[Link](seats,labels=areas,colors=col)
[Link](" Number of Seats Reserved by city ")
[Link]()

calendar module
--------------------
1) calendar(year) : - This function displays calendar of the specified year
Ex:-
import calendar as c
print([Link](2020))

2) month(year, month) :- This function is used to display specified month information

import calendar as c
print([Link](2020,5))

3)isleap(year) :- This funciton is used to check given year is leap year or not

import calendar as c
year = int(input(" Enter any Year : "))
if([Link](year)):
print(year ," Year is Leap Year ")
else:

PythonwithVenkat@[Link] [Link] P a g e 194


print(year," Year is not a Leap Year ")

datetime module
---------------------
date :
--> In datatime module we have date class which is used to perform operations on dates
import datetime as d
x = [Link](2020, 5,21) # year , month, date
print(x)
print('Year is : ',[Link])
print('Month is : ',[Link])
print('Date is : ',[Link])

time :
--> time class in datetime module deals with time
import datetime as d
t = [Link](6,30,43)
print("Time is : ",t)
print(" Hours is : ",[Link])
print(" Minute is : ",[Link])
print(" Sec is : ",[Link])

datetime :
--> datetime class will deal with both date and time
import datetime as d
x = [Link]()
print(x)
print("Current year is : ",[Link])
print("Current month is : ",[Link])
print("current day is : ",[Link])
print(" Hour is : ",[Link])
print(" minute is : ",[Link])

# W. a.p to find difference between two dates


import datetime as d
x = [Link](2018,8,17)
y = [Link]()
print(" Employee joined in : ",x)
print(" Today date is : ",y)
diff = y - x
print(" Difference is : ",[Link]," days")

Task:- W.a.p to find difference between two timeings

PythonwithVenkat@[Link] [Link] P a g e 195


Assignments:
1) What is a File?
2) How many types of files are existed?
3) How many File modes are existed?
4) What is open() function?
5) What is read() method?
6) What is the purpose of write() method?
7) When to use mkdir() function?
8) How to handle File Exceptions?

Code Snippets:

1. Identify error or output? 2. What is the expected output of the


f=open("file1','w') following coding snippet?
[Link]("File Handling") f=open("file1",'a')
[Link]() ans='yes'
while ans='yes'
data=input("Enter the data:")
[Link](data)
ans=input("Do You want to add some
more data(yes/no):")

3. Identify output or error 4. What is the expected output of the


f=open("[Link]",'r') following code snippet:

PythonwithVenkat@[Link] [Link] P a g e 196


data=[Link]() import os
print(data) [Link]('D:\Python\[Link]','
w')

5. What operation is done with the 6. What is the output of the following
following code snippet: coding snippet:
f1=open("D:\cars\[Link]",'rb') import os
data=[Link]() drive=input("Enter the DRIVE under
f2=open("[Link]",'wb') which you want to create a directory:")
[Link](data) directory=input("Which DIRECTORY you
[Link]() want to create under specified drive:")
[Link]() [Link](drive+directory)

7. Identify what information is 8. Identify Error or output in the


displayed with the following following code snippet:
coding snippet:
f=open("[Link]",'w')
f=open("[Link]",'w') list1=["Ramesh\n","Ravi\n","Roja\n","Ran
print("File Name: ",[Link]) i"]
print("File Mode: ",[Link]) [Link](list1)
print("Is File Readable: ",[Link]()) [Link]()
print("Is File Writable: ",[Link]())
print("Is File Closed : ",[Link])
[Link]()
print("Is File Closed : ",[Link])

9. Identify the correct output 10. What is expected output for the
[Link]: following coding snippet:
File Handling in Python Programming
with open("[Link]","w") as f:
[Link] [Link]("Raju\n")
f=open("[Link]",'r') [Link]("Ravi\n")
data=[Link](10) [Link]("Ramya\n")

PythonwithVenkat@[Link] [Link] P a g e 197


print(data) print("Is File Closed: ",[Link])
[Link]()
print("Is File Closed: ",[Link])

Chapter-4
Regular Expressions

PythonwithVenkat@[Link] [Link] P a g e 198


Regular Expressions
----------------------------------
--> Regular Expressions are used to identify whether a pattern exists in a given sequence
of character or not
--> To work with regular expression we have to use moduel, i.e re module
--> To perform search operations we have to use two methods, they are

1. Compile( )
It is used to convert your string value in to match object pattern
Syntax:
[Link](“text”)
Ex:
import re
p = [Link]("TCS")  a Simple Character matches

2. finditer( ):
finditer( ) gives us iterator object, which contains matching information
For every match it will store starting index, end index and match string
Syntax:
[Link](“Text”)
Ex:-
match =[Link]("TCS stands for Tata Consultancy Services.” )

On Match object we can call the following methods.


1. start( ) à Returns start index of the match
2. end( ) à Returns end+1 index of the match
3. group( ) à Returns the matched string

PythonwithVenkat@[Link] [Link] P a g e 199


Ex1:-

import re
t ="python"
data = "core python and advnced python both are important for python jobs"
p=[Link](t)
m=[Link](data)
print(m) # It will give object Address
for i in m:
print([Link](),"\t",[Link](),"\t",[Link]())

Ex2:-

# W.a.p to check given pattern is avaialbe or not if availble how many times
import re
t ="python"
data = "core python and advnced python both are important for python jobs"
p=[Link](t)
m=[Link](data)
print(m) # It will give object Address
count = 0
for i in m:
print([Link](),"\t",[Link](),"\t",[Link]())
count = count + 1
print(t ," is Available ", count, " Times")

Character classes:
-----------------------
We can use character classes to search a group of characters

PythonwithVenkat@[Link] [Link] P a g e 200


1. [abc] ===> matches for a,b and c
2. [^abc] ===> Except a , b and c
3. [a-z] ===> Any Lower case alphabet symbol
4. [A-Z] ===> Any upper case alphabet symbol
5. [a-zA-Z] ===> Any alphabet symbol
[^a-zA-Z] = Except alphabet
6. [0-9] ===> Any digit from 0 to 9
[^0-9] = Except 0 to 9
7. [a-zA-Z0-9] ===> Any alphanumeric character
8. [^a-zA-Z0-9] ===> Except alphanumeric characters(Special Characters)
9. [a|b|c] ===> Matches for either a or b or c

Ex1: # w.a.p to check whether given name is valid or not


import re
name = input("Enter your name : ")
p=[Link]("[^a-z]")
count = 0
m=[Link](name)
for i in m:
print([Link](),"-->",[Link]())
count = count + 1
if(count>0):
print(" Invalid Name ")
else:
print(" Valid Name ")
Ex2:
# w.a.p to check whether given name is valid or not
import re
name = input("Enter your name : ")
p=[Link]("[^a-zA-Z]")
count = 0
m=[Link](name)
for i in m:
print([Link](),"-->",[Link]())
count = count + 1
if(count>0):
print(" Invalid Name ")
else:
print(" Valid Name ")

Ex3:-

PythonwithVenkat@[Link] [Link] P a g e 201


# W.a .p to check whether phone number is valid or not
import re
phno = input("Enter your phnumber : ")
p=[Link]("[^0-9]")
count = 0
m=[Link](phno)
for i in m:
print([Link](),"-->",[Link]())
count = count + 1
if(count>0):
print(" Invalid Phnumber ")
else:
print(" Valid phnumber ")
Pre defined Character classes:
-------------------------------------
\s - Space character
\S - Any character except space character
\d - Any digit from 0 to 9
\D - Any character except digit
\w - Any alpha numeric character [a-zA-Z0-9]
\W - Any character except alpha numeric character (Special Characters)
. - All character including special characters

Ex:-
# w.a.p to check whether given phnumber is valid or not
import re
phno = input("Enter your phnumber : ")
p=[Link]("\D")
count = 0
m=[Link](phno)
for i in m:
print([Link](),"-->",[Link]())
count = count + 1
if(count>0):
print(" Invalid Phnumber ")
else:
print(" Valid phnumber ")

3. match( )
--> It checks whether the given data is starts with specific string or not
--> It checks starting match only.

Syntax: match(searchstring,Text)

PythonwithVenkat@[Link] [Link] P a g e 202


Ex: m = [Link](string,"Python and java are Good Programming Lang")

Ex: import re
t = input("Enter your text : ")
data = "Python and java are Good Programming Lang"
m = [Link](t,data)
if(m!=None):
print("Data started with ",t)
else:
print("Data does not starts with ",t)

4) fullmatch( )
--> It checks complete match is available or not
m=[Link](string,"core python")
Ex:-
import re
t = input("Enter your Password ")
m = [Link](t,"5a2b1")
if(m!=None):
print(" Password is matched ")
else:
print(" Password is not matched ")
5. search( )
--> It is used to check whether given string is available or not,
--> It will check entire Text, but it will display first occurrence only
m=[Link](string,"python java are Good for python")
Ex:
import re
t = input("Enter Search String ")
m = [Link](t, "python java are Good for python")
if(m!=None):
print(t," is Available")
else:
print(t,"is not Available ")

6. findall( )
-->It is used to get all matching Elements in a Text in the form of List
m=[Link](string,"python java are Good for python")
Ex:
import re
t = input("Enter search text : ")
m = [Link](t,"python java are Good for python")
print(m)

PythonwithVenkat@[Link] [Link] P a g e 203


7. split( )
--> it is used to split the string by specified pattern

import re
emailid = input("Enter your Email id : ")
d = [Link]('@',emailid)
print(d)

# Note: split will divided your string into multiple parts and it returns in list format

Iterator:
-->Iterator is an object which allows a programmer to traverse through All the elements
of a collection.
-->It works as like as for loop
-->To Work with Iterator we have to use “iter( )” function

s = input("Enter a string : ")


print("Displaying character by character through for loop:")
for i in s:
print(i,end=" ")
print("\nDisplaying character by character through 'iter()' function:")
x=iter(s)
print(type(x))
print(list(x))

Generator
--> Generator is a function which is responsible to generate a sequence of values
--> We can write generator functions just like ordinary functions,
but in generator we have to use “yield” keyword to return values.

Ex1:-
#generate seq of number
def increment(n):
l2 =[ ]
for i in range(1,n+1):
[Link](i)
return l2
v = increment(10)
for i in v:
print(i,end=" ")

Ex2:-

PythonwithVenkat@[Link] [Link] P a g e 204


def counter():
i =1
while(i<=10):
yield i
i=i+1

for i in counter():
print(i, end=" ")

Assignments:
1. What is a Regular Expression?
2. Which module in Python supports regular expressions?
3. Which method creates a pattern object?
4. What does the function [Link] do?
5. What does the function [Link] do?
6. What is the difference between sub() and subn() methods?
7. what is split() method?

Code snippets:

1. Identify the output 2. Identify the output


import re import re
i=[Link]('[a-z]','[Link]') count=0
print(i) pattern=[Link]("Python")
matcher=[Link]("Python is a
general purpose programming language.
Python is functional oriented programming
language. Python is object oriented
programming language")
for match in matcher:

PythonwithVenkat@[Link] [Link] P a g e 205


print([Link](),"...",[Link](),"...",m
[Link]())

3. Identify the output 4. Identify the output:


import re import re
count=0 pattern=[Link]("[^app]")
pattern=[Link]("Python") match=[Link]("apple1234")
match=[Link]("Python is a for i in match:
functional oriented programming and print([Link](),"...",[Link]())
Python is an object oriented
programming")
for i in match:
print(i)

5. Identify the output: 6. What is the output of the following


import re snippet:
pattern=[Link]("\d") import re
match=[Link]("Python1234") list1=[Link](" ","apple banana cherry")
for i in match: print(list1)
print([Link](),"...",[Link]())

7. Identify error or output: 8. What is the output of the following


import re code snippet:
pattern=[Link]("\d") import re
match=[Link]("b7c@k9z") string=[Link]("apple","grapes","apple
for i in match: banana cherry apple")
print([Link](),"...",[Link]()) print(string)

9. What is the output of the 10. what is the expected output of


following code snippet: the following code snippet:
[Link] import re
<html> pattern=[Link]("[abc]")
<head><title>web match=[Link]("a10c@k9z")
page1</title></head> for i in match:
<body> print([Link](),"...",[Link]())
<ul>
<li>Item 1</li>

PythonwithVenkat@[Link] [Link] P a g e 206


<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
[Link]
import re
pattern=[Link]("<li>.*</li>")
f1=open("D:\\[Link]")
data=[Link]()
matches=[Link](pattern,data)
print(matches)

Chapter-5
Database Connectivity
Programming

PythonwithVenkat@[Link] [Link] P a g e 207


My SQL

 Download Software :

Link : [Link]
Version :- 5.7.29 or any version
Select version, operating system, then download software

 By default My SQl Comes with command prompt


 If you want to work with GUI Model then install SQL Yog

Download SQL Yog Any Version


----------------------------------------

 Download sql yog any version and install it

Install Mysql
Step 1:
Download the latest Mysql Community server from MySQL official website. For me, it is 8.0.12, if the version
differs you no problem the installation steps will be the same.

PythonwithVenkat@[Link] [Link] P a g e 208


Step 2:
It will show you Generally Available (GA) Releases. Where we can see two different installers, one is a web community
installer which comes as a little file and another one is MySQL installer community. Click the Download button on the
second one (mysql-installer-community).

Step 3:
It will ask your MySQL credentials to download the .msi file. If you have your credentials, you can log in or else if you wish to sign
up now you can click on the green coloured signup button.

If you are not interested in login or sign up for now, you can directly go and click on No thanks, just start my download option. It
will download selected MySQL for you on your local machine.

PythonwithVenkat@[Link] [Link] P a g e 209


Step 4:
Go to your downloads folder where you can see the mysql-installer-community file, right click on that file and click Install option.

Step 5:
This window configures the installer, in the middle, it may ask you for permissions to change your computer settings or firewall
confirmation, you can accept and then it will take a few seconds to configure the installer.

PythonwithVenkat@[Link] [Link] P a g e 210


Step 6:
Read the license agreement and accept the license terms.

Step 7:
This window provides you to set up different types of MySQL installations. You can set up Mysql in 5 different types as provided
below. Now I am selecting the Developer Default as I am a developer so that I need all the products which help my development
purposes. Click on Next.

Step 8:
Based on your Windows configuration, it may prompt you like “One or more product requirements have not been satisfied”. You
can just click on YES.

PythonwithVenkat@[Link] [Link] P a g e 211


Step 9:
Click on Execute.

Step 10:
Upon execution of the previous step, the installer grasps all recommended products in place and asking for our approval to
execute the product installation process. Click on Execute.

PythonwithVenkat@[Link] [Link] P a g e 212


Step 11:
Upon successful execution of all required products, now the MySQL allows us to configure the server settings. Click on Next to
configure the server.

Step 12:
This step allows you to configure the server. We can set the server in two different modes. One is a standalone mode, and
another one is cluster mode. I don’t want to make it as a cluster because I am installing MySQL for development purpose so that I
am selecting Standalone MySQL server and click on Next.

PythonwithVenkat@[Link] [Link] P a g e 213


Step 14:
Choose the Development Computer option from Config Type drop-down. You can find the following controls like TCP/IP, Port
and X Protocol Port. If you wish to configure your port, you can change here itself and click on Next. For now, I am leaving as its
default configuration.

Step 15:
It is prompting you to select the authentication method, leave it as the default recommended method and click on Next.

PythonwithVenkat@[Link] [Link] P a g e 214


Step 16:
Here you can set your MySQL root user password. If you wish to create a new user, you can click on Add User button under
MySQL user accounts section.

Step 17:
Upon clicking on Add User button, you will get the user details popup which allows you to create a new user account. After
creating the user click on Next.

PythonwithVenkat@[Link] [Link] P a g e 215


Step 18:
Leave the service details as default and click on Next.

Step 19:
Press Execute to apply the configurations on the previous step.

PythonwithVenkat@[Link] [Link] P a g e 216


Step 20:
Upon execution, you can see the below green coloured ticks on every configuration option and finally you will get Finish button.

Click on Finish you got your MySQL on your Windows 10 operating system.

Testing:
Search for MySQL in your taskbar search item. There you can see all MySQL products which we installed and click on MySQL
client; it will ask your MySQL password to login, after successful login you could see the MySQL prompt like below.

PythonwithVenkat@[Link] [Link] P a g e 217


MySQL comes along with some default databases. We can see the databases by using show databases command.

Open SQL YoG


----------------------
 In sql yog “connect to mysql host” window click “new” button
 Provide name as “localhost” ([Link])
 User name : root
 Port : 3306
 Give password : root (you can choose any name)
 Test connection by clicking “Test connection” and it will display a
window as connected successfully
 Click on Connect

PythonwithVenkat@[Link] [Link] P a g e 218


PythonwithVenkat@[Link] [Link] P a g e 219
Note:- To work with mysql from python we need to install “MySql
connector” from Pypi
 Open command prompt type the command as
“ Pip install mysql-connector”

Steps to create database:-


-----------------------------
 Open sqlyog and connect to localhost database
 In left panel, right click on “root@localhost” and seclect “create
database” and provide database name and click on create

Example program to connect to MySQL:


------------------------------------------------
import [Link] as mysql
try:
con =
[Link](user="root",password="root",host="[Link]",port="3306
",database="RedBus")
print(con)

except:
print(" Unable to Establish Connection ")

Example Program to create table


import [Link] as mysql
try:
con =
[Link](user="root",password="root",host="localhost",port="3306
",database="RedBus")
print(con)
cur = [Link]()
[Link]("create table Student(sid integer, sname text, fee real)")
print(" Table is created ")

PythonwithVenkat@[Link] [Link] P a g e 220


[Link]()
except:
print(" Unable to Establish Connection ")
finally:
[Link]()

# Program to insert record in table


import [Link] as mysql
con =
[Link](user="root",password="root",host="[Link]",port="3306
",database="Amazon")
print(" Connection is Established ")
cur = [Link]()
[Link]("insert into Employee values(101,'Vishnu',50000)")
[Link]()
print(" Record is inserted ")
[Link]()
print(" Connection is Closed ")

Insert Record Dynamically

eid = int(input("Enter Emp id : "))


ename = input(" Enter Emp name : ")
salary = float(input("Enter salary : "))

import [Link] as mysql

PythonwithVenkat@[Link] [Link] P a g e 221


con =
[Link](user="root",password="root",host="[Link]",port="3306
",database="Amazon")
print(" Connection is Established ")
cur = [Link]()
[Link]("insert into Employee values(%s,%s,%s)",(eid,ename,salary))
[Link]()
print("Record is Inserted ")
[Link]()
print(" Connection is closed ")

Select data from Mysql


import [Link] as mysql
con = [Link](user="root",password="root",host="[Link]",port
="3306",database="Amazon")
cur = [Link]()
[Link]("Select * from Employee")
res = [Link]()
for x in res:
for y in x:
print(y,end="\t")
print()

[Link]()

Update the data


eid = int(input("Enter Emp id : "))
ename = input("Enter new Name : ")
import [Link] as mysql
con = [Link](user="root",password="root",host="[Link]",port ="3306",database="Amazon")
cur = [Link]()

PythonwithVenkat@[Link] [Link] P a g e 222


[Link]("update Employee set ename = %s where eid = %s",(ename,eid))
[Link]()
print(" Record is updated ")
[Link]()

Delete the data


eid = int(input("Enter Emp id : "))

import [Link] as mysql


con = [Link](user="root",password="root",host="[Link]",port
="3306",database="Amazon")
cur = [Link]()
[Link]("delete from Employee where eid = %s",(eid,))
[Link]()
print(" Record is Deleted ")
[Link]()

PythonwithVenkat@[Link] [Link] P a g e 223


Mongo DB
 Mongo DB is NOSQL Database
 To work with Mongo Db We have to install MongoDb software

Download
 Download Mongo DB from

[Link]/download-center
Select Server  select the version 3.6.14  Select OS(windows)
select package(MSI)  click on download
To work with MongoDb we need MonoDB Compass, it will come
along with your Mongo Db Software
 MongoDb compass

Steps to create DataBase


 In NOSQL(Not only SQL), we call table as a collection
 HostName: LocalHost

PythonwithVenkat@[Link] [Link] P a g e 224


 Port : 27017

 To Open Mongo DB double click on Mongo DB Compass (or) Search for


mongo DB compass in start menu
 Without doing any changes click on “connect “ button
 Once you open cluster window, click on create DB button
 Provide data base name and a collectionname( Table name) and click on
create data base
 To create more collections click on “Create collection” button

Note:- To work with Mongo DB First Start Server

Note:
In No Sql Table is Collection
In No Sql Each row is represented as one document
In No Sql we don’t have fixed columns
In mongo DB data(document) is stored in dictionary format

Ex:- “idno” : 101


“Name” : “ Venkat Reddy”
“Salary” : 5000
Note:
C:\Users\Venkat\AppData\Local\Programs\Python\Python37\Scripts

Set Path First then work with pip…


To connect to mongo DB from Python we need connector(Driver).
Ie. Py mongo
Check PyMongo is available or not in your Pip

PythonwithVenkat@[Link] [Link] P a g e 225


Open Command Prompt

Type “pip list”

It will give you all the packages available in Pip,

If PyMongo is not available then install Pymongo from [Link]


To install pymongo use Pip
Open Command prompt then execute bellow command

Pip install pymongo(command prompt)

Example program to connect to mongo DB


from pymongo import MongoClient
mc = MongoClient("localhost:27017")
print(mc)

Example to connect amazon Db


from pymongo import MongoClient
mc = MongoClient("localhost:27017")
print(mc)
db = [Link]
print(db)

Insert data in table


from pymongo import MongoClient
mc = MongoClient("localhost:27017")
db = [Link]
d1 = {"eid":1001, "ename":"Vishnu","sal":50000.0}
[Link].insert_one(d1)
print(" Data Inserted ")

Note: Mongo DB will autogenerated unique id using “_id” key

PythonwithVenkat@[Link] [Link] P a g e 226


To override use “_id” in the dictionary

Example to insert unique id


from pymongo import MongoClient
from [Link] import DuplicateKeyError
mc = MongoClient("localhost:27017")
db = [Link]
d1 = {"_id":1002, "ename":"Vishnu","sal":50000.0}
try:
[Link].insert_one(d1)
print(" Data Inserted ")
except DuplicateKeyError as dk:
print(" Id number is already available ")

Dynamic data insert


from pymongo import MongoClient
from [Link] import DuplicateKeyError
mc = MongoClient("localhost:27017")
db = [Link]
ch = 'y'
while(ch=='y'):
eid = int(input("Enter Employee id : "))
ename = input("Enter Employee name : ")
sal = float(input("Enter Salary : "))
d1 ={"_id":eid,"ename":ename,"sal":sal}
try:
[Link].insert_one(d1)
print(" Data Inserted ")
except DuplicateKeyError as dk:
print(" Id number is already available ")
ch = input(" Do you want to store any records(Y/N) : ")

print(" Thank you")

Example to read all records from a collection


from pymongo import MongoClient
mc = MongoClient("localhost:27017")
db = [Link]
res = [Link]()
#for x in res:
# print(x)
for a in res:
for b,c in [Link]():

PythonwithVenkat@[Link] [Link] P a g e 227


print(c,end="\t")
print()

Query in SQL
Select * from Client
Query in NOSQL
[Link]()
[Link]()

Syntax to read specific document


In SQL:
Select *from Employee where _id = 1001
In No SQL:
[Link](“conditions”)
[Link]({“_eid”:1001})

Example:
idno = int(input("Enter Employee id : "))
from pymongo import MongoClient
mc = MongoClient("localhost:27017")
db = [Link]
res = [Link]({"_id":idno})
a = list(res)
if a!=[]:
for x in a:
print(x)

PythonwithVenkat@[Link] [Link] P a g e 228


else:
print("Emp id ",idno," is not available ")

Update Records

Example:

idno = int(input("Enter Employee id : "))


salary = float(input("Enter Salary : "))
from pymongo import MongoClient
mc = MongoClient("localhost:27017")
db = [Link]
[Link].update_one({"_id":idno},{"$set":{"sal":salary }})
print("Data is updated ")
for x in [Link]():
print(x)

Delete Records
 To delete record in Mongo DB , we have to use delete_one() Method
idno = int(input("Enter Employee id : "))
from pymongo import MongoClient
mc = MongoClient("localhost:27017")
db = [Link]
res = [Link]({"_id":idno})
a = list(res)
if a!=[]:
[Link].delete_one({"_id": idno})
print("Record is deleted ")
else:
print("Emp id ",idno," is not available ")

print(" Your Records are ")


for x in [Link]():
print(x)

 If you want to remove more than one record at a time based on condition
then
sal = int(input("Enter Employee salary : "))
from pymongo import MongoClient
mc = MongoClient("localhost:27017")

PythonwithVenkat@[Link] [Link] P a g e 229


db = [Link]
[Link].delete_many({"sal":{"$gt":sal}})
print("Records deleted ")

print(" Your Records are ")


for x in [Link]():
print(x)

Operators

Following is the list of operators used in the queries in MongoDB.

Operation Syntax

Equality {"key" : "value"}

Less Than {"key" :{$lt:"value"}}

Less Than Equals {"key" :{$lte:"value"}}

Greater Than {"key" :{$gt:"value"}}

Greater Than Equals {"key" {$gte:"value"}}

Not Equals {"key":{$ne: "value"}}

PythonwithVenkat@[Link] [Link] P a g e 230


PythonwithVenkat@[Link] [Link] P a g e 231
PythonwithVenkat@[Link] [Link] P a g e 232

You might also like