Python Complete Book
Python Complete Book
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.
3rd Screen
Note:
Python Installation Process :
[Link]
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.
import keyword
print([Link])
Identifier
Identifier is a name given to an entity like Class, Function (or)Method
and Variable.
1. Literals
Types of Literals:
2. Constant
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
Case Study:
PI = 3.14
r = 5.2
area = circle_Area()
print(area)
def circle_Area():
a = PI * r * r
return a
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
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
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:-
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:-
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:-
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:-
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:-
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.
gstamout is 30
gst is 10%
formula:
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
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.
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:
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
== Equal to
!= Not Equal to
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
Ex2: Consider m value is 15, write the condition to check given number is
divigible by 5 or not
4) Logical Operators:
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
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”
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
Operator Name
//
**
<
>=
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
PythonwithVenkat@[Link] [Link] P a g e 35
Chapter-6
Statements and Types
PythonwithVenkat@[Link] [Link] P a g e 36
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
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 you”)
Output:
s2 = 57 card = 'ICICI'
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
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):
else: else:
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):
else: else:
Output: Output:
5) n = 0 6) s1 = 52
if(n>0): s2 = 36
else:
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("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:-
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:-
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
.......
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"
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
output:
1
2
3
4
5
6
7
8
9
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)
PythonwithVenkat@[Link] [Link] P a g e 55
print(i,end=" ") print(i,end=" ")
Output: Output:
count=count+1
print(count)
Output:
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:-
Output: Output:
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
PythonwithVenkat@[Link] [Link] P a g e 58
12) 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
33*3*3 = 27
5 5 * 5 * 5 = 125
11*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
A # * A A
AB # # * * AA BB
ABC # ## * * * A AA C CC
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
PythonwithVenkat@[Link] [Link] P a g e 70
8) qualification= “ [Link]”
qualification[0]=’M’
print(qualification)
output:-
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
PythonwithVenkat@[Link] [Link] P a g e 71
16) How to check our string is in upper case or not
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
PythonwithVenkat@[Link] [Link] P a g e 72
25) How to check whether a given string starts with a specific string or
not
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:-
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:-
Output: 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
“Lakshmi@[Link]”, “avinash@[Link]”]
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.”
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
PythonwithVenkat@[Link] [Link] P a g e 78
Add a single element to the end of the
append() list
PythonwithVenkat@[Link] [Link] P a g e 79
print(n)
PythonwithVenkat@[Link] [Link] P a g e 80
n1 = [5, 2, 8, 3, 1, 6] Output:
l = min(n1) 1
print(l)
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:-
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:
Output:- Output:-
Output:
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:-
Output:- Output:-
Output:- Output:-
Output:- Output:-
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
PythonwithVenkat@[Link] [Link] P a g e 84
n1 = (5, 2, 8, 3, 1, 6) Output:
l = min(n1) 1
print(l)
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:-
Output:- Output:-
Output:- 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
PythonwithVenkat@[Link] [Link] P a g e 87
print(n)
PythonwithVenkat@[Link] [Link] P a g e 88
[Link](6)
print(n)
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)
PythonwithVenkat@[Link] [Link] P a g e 89
print(c)
d = [Link](p)
print(d)
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:-
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'}
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)
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:-
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:-
PythonwithVenkat@[Link] [Link] P a g e 95
Output:-
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
OOPL
------
--> Abstraction
--> Encapsulation
--> Inheritance
--> Polymorphism
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
---------------------------
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 ")
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 ( )
class Amazon:
@staticmethod
def search(productname):
print(" Your Products ")
def buyNow(self):
print(" You can buy now ")
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):
..............
.............
--> 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
--> 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 sudent marks then cal total then display
read( ) --> Read s1,s2, s3 marks
calTotal( ) --> cal 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):
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( )
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.
Instance Variable:
When data is changing from one object to another object then we have
to use Instance variables.
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.
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
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
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"
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
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
Polymorphism
Ability to have multiple forms
They are two types
i. Method Overloading
Method with same name and with different parameters is said to
be "Method Overloading".
[Link] Overloading
[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.
i. Method Overriding
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]()
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):
Assignments:
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()
a=10 [Link]=100
print(a) [Link]='Raju'
print(a) print(self.__dict__)
e=Employee()
print(t.__dict__)
t.m1()
print(t.__dict__)
del t.c
print(t.__dict__)
class Test:
def __init__(self):
self.a=11
t1=Test()
t1.a=777
t1.b=999
t2=Test()
print('t1:',t1.a,t1.b)
print('t2:',t2.a,t2.b)
self
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):
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()
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?
Expected O/P:-
[Link] A:
def Sub(self,x,y):
return x-y
obj=A()
print([Link](20,10))
Expected O/P:-
[Link] A:
def CalTotalMarks(m1,m2,m3):
total = m1 + m2 + m3
return total
print([Link](90,80,70))
Expected o/p:-
4. class A:
cbal = 5000
def Deposit(amt):
[Link] = [Link] + amt
return [Link]
print([Link](10000))
Expected o/p:-
5. class B:
def m1():
return B()
print(B.m1())
Expected o/p:-
Code snippets:
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)
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:
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( )
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
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:
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( )
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:-
Ex2:
class Test:
def __init__(self):
print(" Test class default constructor ")
class Demo(Test):
def __init__(self):
Output:
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
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]()
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
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)
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)
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
class ICICI(RBI):
def calFinalAmt(self,amt):
[Link] = amt + self.i
print(" Final Amount is : ",[Link])
Poly Morphism
---------------------
Poly morphism means many forms
def add(a,b):
c=a+b
print( c )
add(5, 9) # 14
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):
Output:-
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")
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]()
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?
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__)
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?
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()
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
Output2:
Enter any Number : 10
Enter any Number : 0
ZeroDivisionError: integer division or modulo by zero
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:-
Syntax:
try
-----
try:
Statement-1
Statement-2
except
----------
1) except :
Statement
2) except ExceptionName:
Statement-1
Statement-2
Statement -2
Ex:
x = int(input("Enter any Number : "))
y = int(input("Enter any Number : "))
try:
z = x // y
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
Output:
Enter any Number : 10
Enter any Number : 0
integer division or modulo by zero
Thank you
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
---------------------
finally
---------
--> finally block contain a group of statements which can perform code cleanup activites
like releasing the files, memory, connection etc..
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 ")
--> For one try block we can write more than one except blocks
try:
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")
finally :
................
-->An else block can be followed by except
Ex:
try:
............
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:
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:
Userdefined Exceptions
---------------------------------
--> The exceptions that are created by Programmer is called as user-defined exceptions
Ex:-
class SmallAgeException(Exception):
def __init__(self,msg):
[Link] = msg
Ex2:-
class SmallAgeException(Exception):
def __init__(self,msg):
[Link] = msg
except SmallAgeException as e:
print(e)
else:
print(" Apply job ")
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?
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
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
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 :
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
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)
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
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
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.
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]()
calendar module
--------------------
1) calendar(year) : - This function displays calendar of the specified year
Ex:-
import calendar as c
print([Link](2020))
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:
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])
Code Snippets:
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)
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")
Chapter-4
Regular Expressions
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.” )
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
Ex3:-
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)
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)
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
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:-
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:
Chapter-5
Database Connectivity
Programming
Download Software :
Link : [Link]
Version :- 5.7.29 or any version
Select version, operating system, then download software
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.
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.
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.
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.
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.
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.
Step 15:
It is prompting you to select the authentication method, leave it as the default recommended method and click on Next.
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.
Step 19:
Press Execute to apply the configurations on the previous step.
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.
except:
print(" Unable to Establish Connection ")
[Link]()
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
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
Query in SQL
Select * from Client
Query in NOSQL
[Link]()
[Link]()
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)
Update Records
Example:
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 ")
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")
Operators
Operation Syntax