0% found this document useful (0 votes)
2 views208 pages

Python PDF

The document outlines a Python programming course for B.C.A. and B.Sc(I.T) students, covering topics such as basic elements of Python, object-oriented programming, plotting with PyLab, network programming, and database connectivity. It includes detailed explanations of Python concepts like data types, variables, syntax, strings, and operators, along with examples and exercises. The course aims to provide a comprehensive understanding of Python programming and its applications.

Uploaded by

zoraronak101
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)
2 views208 pages

Python PDF

The document outlines a Python programming course for B.C.A. and B.Sc(I.T) students, covering topics such as basic elements of Python, object-oriented programming, plotting with PyLab, network programming, and database connectivity. It includes detailed explanations of Python concepts like data types, variables, syntax, strings, and operators, along with examples and exercises. The course aims to provide a comprehensive understanding of Python programming and its applications.

Uploaded by

zoraronak101
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

Vivekananda College of Computer Science and Mgt.

Developed By : Dhara Sagparia


Subject : Python

CS – 33 : Programming in Python –B.C.A. & [Link](I.T) –SEM -5

[Link]. Topic Detail


1 Introduction to  Basic Element of Python
Python  Branching Programs
 String and Input
 Iteration
 Function and Scoping
 Specifications
 Recursion
 Global Variables
 Modules
 Files
 Tuples
 List & Mutability
 Functions as Object
 Strings
 Dictionaries

2 OOP Handling Exception


using Exception as Control Flow
Python Assertion
Abstract Data Type
Class
Inheritance
Encapsulation
Information hiding
Search Algorithm
Sorting Algorithm
Hash table

1
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

3 Plotting using PyLab  Plotting using PyLab


 Plotting Mortgages
 Extended Example
 Fibonacci Sequence Revisited
 Dynamic Programming
 0/1 Knapsack Algorithm
 Dynamic Programming with Divide and
Conquer
Network  Network Programming:
Programmin  Protocol, Sockets,
g and GUI  Knowing IP Address,
usingPython  URL, Reading the Source Code of a
Web Page,
 Downloading a Web Page from Internet,
 Downloading an Image from Internet,
 A TCP/IP Server, A TCP/IP Client,
 A UDP Server, A UDP Client,
 File Server, File Client,
 Two-Way Communication between
Server and Client,
 Sending a Simple Mail.
 GUI Programming:
 Event-driven programming paradigm;
 creating simple GUI;
 buttons, labels, entry fields, dialogs;
 o widget attributes - sizes, fonts, colors
,layouts, nested frames
5 Connecting  Verifying the MySQL dB Interface
with Installation,
Database  Working with MySQL Database,
 Using MySQL from Python,
 Retrieving All Rows from a Table,
 Inserting Rows into a Table,
 Deleting Rows from a Table,
 Updating Rows in a Table,
 Creating Database Tables through
Python

2
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

CHAPTER-1
Introduction to Python
 Basic Element of Python
 Branching Programs
 String and Input
 Iteration
 Function
 Scoping
 Specifications
 Recursion
 Global Variables
 Modules
 Files
 Tuples
 List & Mutability
 Functions as Object
 Strings
 Dictionaries

3
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Q-1 What is Python ? Explain Basic Elements of Python :

Detail :-
 Python is popular programming language.
 It was created in 1991 by Guido Van Rossum.
 It is used for :
o Web Development (server side)
o Software Development
o System Scripting
o Mathematics
 Python support following elements to perform perfect programming:

1. Data Type :
 Python support integer and float data type to hold numbers.
 Python interpreter can produce the result of numeric values.

4
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

2. Variable :
 Unlike other programming language , python have no command
for declaring variable.
 You can create variable by assigning value directly to it.
o EX :- x = 50
Name = “hello”

3. Syntax :
 Python syntax can be executed by writing directly at the
command line like,
 >>> print (“hello”)

4. String :-
 String is a collection of different characters.
 You can write string in signle quotes(‘ ‘) as well as in
doublequotes (“ “).
o EX :- a=
‘hello’b=” “

5. Tuples :-
 In the case of tuples , it is collection of different elements and
values supported by python data types.
 Tuples are enclosed in round brackets ().
o EX :- a = (‘abc’ , ‘jkl’ , ‘xyz’,18)
o
6. List :-
 In the case of , It is collection of element or values supported by
python data types.
 List are enclosed in square brackets ().
o EX :- a = [1,2,3,4,5]

7. Dictionary :-

5
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 A Dictionary is a collection which is unordered , changeable and


indexed.
 Dictionary can be enclosed in curly brackets { } with key &
valuepair.
o EX :- dict = {name = “snehal” , surname = “pandya”}

8. Operators :-
 An operators are used to perform operations on variable or value.
 Python support following operators :
o Arithmatic
o Assignment
o Comparison
o Logical
o Membership
o Bitwise
o Identity

1 Word Question – Answer

O. QUESTION ANSWER

1 Python was developed by Guido Van Rossum

Open source
2 Python is language.

6
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Q-2How to input and output value in the python:

Detail :-
 In python programming user can input the data as well as get the output asa
result of data.

How to input value :


 To input value python provide one of the built – in function named
input().
 You can ask user to input particular value from userside.
 You can call input () and wait for user to enter the data.
 In python2 you can use row_input() to get value from userside , while
in python3 you have input() to get value from user.
o EX :- num = input (“enter number”)
name = input(“enter name”)

How to ouput / print value :


 Python provide print() to get output to the file.

7
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Print() support message of the user as well as value of variable they


want to print.
o EX :- a=5
>>> print (a)
Output :- 5
o EX :- b=10
>>> print (“value of b is =” ,b)
Output :- value of b is = 10

1 Word Question – Answer

SR. QUESTION ANSWER


NO.
To input value in the python Input()
function can be used.
To print output on the screen _ Databse Access
function can be used.
Python prompt can be represented by >>>
_

Q-3Expalin Braching Statements in python:

8
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Detail :-
 If statement support generally the logical expression.
 In this statement first of all we have to give condition.
 If condition become true then statement following if will be execute
otherwise condition will be terminated.
 Syntax :-
If (<condition>):
<statement>

 Example :-
A=10
If(A>0):
Print(‘yes’)

9
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

If ….. Else :-
 In this statement first of all condition will be check.
 If condition become true then statement following if will be execute.
 But if condition become false then statement following else will be execute.

 Syntax :-
If (<condition>):
<statement>
Else:
<statement>

 Example :-
A=10
If(A>0):
Print(‘yes’)
Else:
Print(‘no’)

10
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Elif :-
 The elif statement is used to support multiple conditions at the same time.
 At a time only one condition will become true.
 In this case if no any condition become true then finally the statement
following else will be execute.

 Syntax :-
If (<condition>):
<statement>
Elif(<condition>):
<statement>
Elif(<condition>):
<statement>
Else:
<statement>

11
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Example :-
a=10,b=20,c=30
if(a>b and a>c):
print(‘a is max’)
elif(b>a and b>c):
print(‘b is max’)
else:
print(‘c is max’)

1 Word Question – Answer

[Link] QUESTION ANSWER


.
1 Python provide one of the important If statement
branching statement that is .
2 In if statement the condition is followed by Colon(:)
.
3 If condition become false then statement Else :
followed by _ will be execute.
4 _ statement can be used to elif
support multiple conditions at the same time.

Q-4 Explain String in Python.

12
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Detail :-
 Pythondoesnotsupportcharactertype.
 String is mostpopular datatype in python.
 Stringisacollectionof differentcharacterandsymbols.
 We cancreate or declare astring by enclosing “ “(Double Quotes) aswellas ‘
‘Single Quotes
forthestatements.
 Let’ssee, how to declare astringvalue in python:
o Example:- var1 =“hello”

How to Access Characters from particular String :-


 We can accessdifferentcharactersfromgivenstring using indexing.
 Inpython stringindex willstart from 0(zero).
 We can notdelete or removethecharacters fromthestringbut deletingentire string is
possible using del keyword.
o Example:- var1 =“helloworld”
Var2 =“ pythonprogramming”
Print (“var1[0]:”, var1[0]) output:- h
Print(“var2[1:5]”,var2[1:5]) output:- ytho

13
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

How to Concatenate ( join) two strings :-

 To join or concatenatetwo strings in python , (+) plusoperatorcan be used.


o Example:- var1 =“hello ”
Var2 =“ pythonprogramming”
Print(var1 +var2) output:- hellopythonprogramming

How to update existing string :-


 You can "update" an existing string by (re)assigning a variable to another
string.
 The new value can be related to its previous value or to a completely
different string altogether.
o Example :- var1 = ‘hello world’
Print (‘updated string:-‘ , var1[:6] + ‘python’)
output :hello python

1 Word Question – Answer

SR.N QUESTION ANSWER


O.
1 In python ,String can be represented by Single quotes & double
quotes
2 To access substring ,we have to use : (Colon)
index number with _ Operator.

Q-5 Explain String Operators in Python.

14
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

15
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Assume string variable a holds 'Hello' and variable b holds 'Python', then −

Operato Descriptio Example


r n
+ Concatenation - Adds values on either side of a + b will
the operator give
HelloPython
* Repetition - Creates new strings, concatenating a*2 will give
multiple copies of the same string -HelloHello
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the a[1:4] will
given range giveell
in Membership - Returns true if a character exists H in a will give
in the given string 1
not in Membership - Returns true if a character does M not in a
not exist in the given string willgive 1

Detail :-
 The string operators can be used to perform different types of operations on
the string.
 There are three types of string operators supported by python.
o Basic Operator
o Membership Operator

Basic Operator:-
 String operator support two types of basic operators :
(i) Concatenate Operator :-
o The concatenate operator can be used to combines two two or more
string Values.

16
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

o Plus(+) operator can be used as concatenate operator inpython.


o Example :-
>>> “hello” + “hi”
Output :- Hellohi

(ii) Replication Operator :-


o The Replication operator (*) is used to repeat particular
string , character or symbol for given number of time .
o In this operator we have to give one integer paramter
and string value.
o Example :-
>>> 5 * “hi ”
Output :- hi hi hi hi hi
Membership Operator:-
 Membership operator is used to indicate possibilities of available members.
 There are two types of membership operators:
(i) in Operator :-

o The in operator returns true if particular character or


string available in the given string otherwise false.

(ii) Not in Operator :-


o This operator returns true if particular character or string does
not exist in given string otherwise returnfalse.

17
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

o Example :-
>>> str1 = “java programming”
>>> str2 = “HNS IT”
>>> str3 = “SEO Material”
>>> str4 = “java”
>>> str5 = “IT”
>>> str4 in str1 Output :- True
>>> str5 in str2 Output :- False
>>> str4 not in str1 Output :- False

1 Word Question – Answer


[Link] QUESTION ANSWER
.
1 string operator can be used for +
concatenation of multiple strings or words
2 string operator can be used for *
repetition of multiple strings or characters
3 string operator can be used to return :
characters from given range.
4 & are known as membership In & not in
operators.

Q- 6 Write note on Iteration OR Looping Statements.

18
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Detail :-
 Generally the statements are executed sequentially.
 When user want to execute group of the statements at that time looping
statements are used.
 The main use of loop is to repeat the statements for number of times.
 Python programming support following types of looping statements:

o While Loop
o For Loop
Loop Type Description
while loop Repeats a statement or group of statements while a
given condition is TRUE. It tests the condition before
executing the loop body.
for loop Executes a sequence of statements multiple times
and abbreviates the code that manages the loop
variable.

While Loop :-
 While loop is known as entry – control loop.
 In this loop first of all condition will be checked and then after statementwill
be execute.
 If condition become true then the statement following while will be
execute otherwise loop will be terminated.

o Syntax :-
<initialization>
While(<condition>):
<statement>
<increment / decrement>

19
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

o Example :-
i=1

while(i<=10):
Print(i)
i=i+1

 For Loop :-
 For loop is used to execute block of the code for given number of times.
 First of all condition will be check and then after statement will be execute.
 For loop will iterate for the particular collection or list items.

o Syntax :-
For <variable> in <sequence>:
<statement>

o Example
:-i=1
fruits = [‘apple’ , ‘banana’ , ‘mango’]

20
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

for i in fruits:
print(i)
 If a sequence contains an expression list, it is evaluated first.
 Then, the first item in the sequence is assigned to the iterating
variable iterating_var.
 Next, the statements block is executed.
 Each item in the list is assigned to iterating_var, and the statement(s)
block is executed until the entire sequence is exhausted.

21
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Nested Loop :-

22
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 If you want to create one loop inside another loop then it is called
nested loop or nesting of loop.
 First of all outer loop will be execute first and then after inner loop
will be execute.
o Syntax :-
For <variable> in <sequence>:
<statements>
<statements>

o Example :-
i=1
for I in range(1,10):
for j in range(1,10):
print (j)
print()

1 Word Question – Answer


[Link] QUESTION ANSWER
.

1 Python support & looping While & for


statements.
2 is loop inside body of another Nested loop
loop
3 In looping statement , the expression or : (Colon)
condition must be followed by .
4 Looping statements are also known as Iterative
statements
5 The loop inside another loop is called Inner loop
loop

23
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Q-7 What is Scoping ? Explain.

Detail :-

 Variable is acontainer thatuse to storedifferent values.


 Variable can onlyreachthearea in whichtheyaredefine , which is calledscope.
 Pythonsupporttwotypes of variable scopes:

o Localscope of variable
o Globalscope of variable

 Thescope of variable is used to decide placewhere you can access variable.


 If you define variable at the top level of your script or module then it is
always global variable.

 Local scope of variable :-

 If youdeclarevariable inside the functionthen it is called local scope.


 Local variable have limited scope , it can be accessed by only the
function in which it is declare.

o Example :-
def
my_function()
a=10
print(“a=” , a)
return
>>>my_func()
>>>print(a) # name error : name ‘a’ is not defined

 Global scope of variable :-

 If you declare variable at the top of your script or module then it is always global.

24
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Global variable can be easily access anywhere within

your script. o Example :-

My_var = 20
def my_function()
print(“a=” , a)
return
>>>print(a)
>>>my_function()

1 Word Question – Answer

[Link] QUESTION ANSWER


.

1 In python , scope of variable can be _ Local & Global


& .
2 The variable that declare inside function block Local scope
and can be access within function is called
.
3 The variable that declare outside the function Global scope
and can be access anywhere in the script is
called

Q-7 What is Recursion ? Explain with example.

Detail :-
 Pythonprogramming supportrecursion as programmingconcept.
 Whenthefunctioncall itself againand again then it is calledrecursion.
 Recursionworklikealoop, you canconvert any loo to recursion.

25
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Recursive Function :-

 Recursive function is called byexternalcode.


 If the base condition is available then the program do something meaningful otherwise
exit.
 Functionhave to do somerequiredprocessingandthencall itself to continuerecursion.

o Example :-
#Factorial using
recursion
def fact(n):
if(n==0):
return 1
else:
returnn*fact(n-1)
#callingfunction
Print(fact(0))
Print(fact(5))
 Nowtry to execute above function like afollowing:-
o Example:-
Print (fact(2000))

26
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Youwillgetfollowingerror at runtime:-
o Runtimeerror:- Maximumrecursion depthexceeded in comparison.

 The above error is available because python stop calling recursive function after 1000
calls bydefault.
 To change it you need to add following lines to starting of code.

Import Sys
[Link](3000)
1 Word Question – Answer
[Link] QUESTION ANSWER
1 When the function call itself recursion

again and againthen it is called .


2 function is called by external recursive

Q-8 What is Module ? Explain

27
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Detail :-
 Moduleallow you to logically organizeyourpythoncode.
 To grouprelatedcodeintothemodule makes thecodeeasier to understand and us d.
 Simplymodule is a file having thepythoncode.
 Modulecan define function, variable and class.
 Modulecanalso incuderunnable code.
o Example:-
[module – [Link]]

Def print_func(x):
Print(“hello:”,x)

 Pythonprovidetwotypes of statements to load module:

28
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Import statement :-
 You can use any pyton file as a module by executing import statement in
other python file.
o Syntax :- import module 1 [,module 2 [,module N ] ]
 When interpreter find out import statement it import the module if moduleis
available.
o Example :- import module support
import support
Support.print_func(“zara”)
 Module is loaded only once , but number of times it will be imported.
 The module search the path which is stored in system module as [Link].

 From……import statement :-
 Python's from statement lets you import specific attributes from a module
into the current namespace.
 The from...import has the following syntax –

o Syntax :- from modname import name1[, name2[, ... nameN]]

 For example, to import the function fibonacci from the module fib, use the
following statement −
o Example :- from fib import Fibonacci

 This statement does not import the entire module fib into the current
namespace;
 it just introduces the item fibonacci from the module fib into the global
symbol table of the importing module.

 The from...import * Statement:-


 It is also possible to import all names from a module into the current
namespace by using the following import statement −

29
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

from modname import *


 This provides an easy way to import all the items from a module into the
current namespace.

Using the dir() Function


 There is a built-in function to list all the function names (or variable
names) in a module. The dir( ) function:
 module: import platform

o Example :-
x =
dir(platform)
print(x)
 Note: The dir() function can be used on all modules, also
theones you create yourself.
1 Word Question – Answer
[Link] QUESTION ANSWER
.
1 Module is a having python code. file
2 statement can be used to import import
code from the given module.
3 To import all the files from the particular Import *
module we can use

Q-9What is file? Explain How to open , read , write and close the file –[file
handling]

30
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Detail :-
 File is used to store related information permanently.
 When we want to read from or write to a file , we need to open it first.
 There are following file operations available:
o Open a file
o Read a file
o Write a file
o Close a file

Open a

31
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Python provide open() to open particular file.


 We have to provide file mode which can be read – ‘r’ , write – ‘r’ or append

– ‘a’.
 The default mode is reading mode.
 File Modes :-
(1) ‘R’ :- This file mode is used to open any file for reading purpose.
(2) ‘w :- This file mode is used to open any file for writing purpose.
(3) ‘a’ :- This file mode is used to open any file for appending data.

Example :- f = open (“[Link]”)


f = open (“[Link]”,”w”)

Write data to the file :-

 To write data from the file , we need to open it into write mode.
 To write data into file , write() can be used.

Example :- f = open (“[Link]”, “w”)


[Link](“hello”)
print(“written successfully”)
[Link]()

Read data from the file :-


 To read data from the file , we need too pen it into read mode.
 To read data from the file , read() is used.

Example :- f = open (“[Link]”, “r”)


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

32
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

How to close file :-


 When we complete all the related operations the new need to close it
properly.
 To close any file , close() is used.
Example :-
f = open (“[Link]”, “r”)
print ([Link]())
[Link]()

1 Word Question – Answer


QUESTION ANSWER
[Link]

1 is used to store related imformations file


permanently.
2 can be used to open particular file Open()
3 can be used to read data from Read()
particular file.
4 can be used to write data to the Write()
particular file.
5 _ can be used to close particular Close()
file.

Q-10 Write note on tuple .

33
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Detail :-

 Tuple is a sequence of immutable python object.


 Tuple is very similar to the list but there may be following difference
between list and tuple.
o Tuple can not be change or update during execution.
o We have to use round brackets( ) to represent tuple.
o User can create empty tuple by representing empty brackets ( ).
o Creating tuple is as simple as representing different values
supported by comma ( , ).

 Example :-
T1=(‘a’,’b’,’c’,’d’,’e’)
T2=(1,2,3,4,5)
T3=(17,25,”hi”,”how”,4)

 How to access value from the tuple :-


 To access value from the tuple use square bracket [ ] with particular index
number or range.
 Example :-
T1=(‘a’,’b’,’c’,’d’,’e’)
Print (“t1[2]:” , t1[2])
o/p:- c

 How to update value in the tuple :-


 In tuple it is not possible to change the value during execution.
 But it is possible to merge more than one tuples at the same time.
 Example :-
T1=(‘a’,’b’,’c’,’d’,’
e’)T2=(1,2,3,4,5)
T3= T1 + T2
Print (T3) o/p :- a,b,c,d,e,1,2,3,4,5

34
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 How to delete tuple :-


 To remove particular value of the tuple is not possible.
 So that we have to delete or remove entire tuple using del statement.
 Example :-
T1=(‘a’,’b’,’c’,’d’,’e’)
del (T1)
Print (T1)

1 Word Question – Answer


[Link] QUESTION ANSWER
.

1 Tuple is object in python. immutable


2 Tuple can be represented by brackets. ( ) (round)
3 statement can be used to remove entire del
tuple.

Q-11 Write note on List.

35
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Detail:-
 Thelist is mostversatile datatype in python.
 List can be represented by squarebracket[] , separated by comma( , ).
 Inpython youcan createsimplelistlike following:

 Example :-
L1 = [“abc” , “xyz” , 2000 ,1999]
L2 = [1,2,3,4,5,6,7]

 How to access value from the List :-


 To access value from the List , use square bracket [ ] with particular
indexnumber or range.

 Example :-
L1 = [“abc” , “xyz” , 2000 ,1999]
L2 = [1,2,3,4,5,6,7]
Print (“list1[0]:” , L1[0]) o/p :- abc
Print(“list2[1:5]:” , L2[1:5]) o/p :- 2,3,4,5

36
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 How to update value in the List :-


 You can update single or multiple elements of list by assigning new
valuefrom right to left.
Example :- L1 = [“abc” , “xyz” , 2000 ,1999]
Print (L1[2]) o/p :- 2000
L1[2] = 2005
Print (L1[2]) o/p :- 2005

 How to delete value in the List :-

 To remove list element , you can use del statement , if you know which
element you are going to delete.
 You can also use remove() , if you do not know which element you are
going to delete.

 Example :-
L1 = [“abc” , “xyz” , 2000 ,1999]
Print (L1[2])
del (L1[2])
Print (L1)
Del (L1)
Print(L1)
1 Word Question – Answer
[Link] QUESTION ANSWER
.

1 List is object in python. mutable


2 List can be represented by [ ] (square )
brackets.
3 To remove particular element from the list del
statement can be used.

37
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

38
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Q-12 Write note on Dictionary.

Detail:-
 In dictionary we have to manageourdata by key and valuepair.
 In dictionaryeach key is separatedfromitsvalue usingcolon(: ).
 In dictionarythe key and value pairs are separated by comma(, ).
 Thekeys are always unique but valuescannot be.
 We can createourdictionaryusingcurlybrackets { }.

39
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Example :-
D1 = {‘name’ : ‘zara’ , ‘city’ : ‘rajkot’ , ‘age’ : 5)

 How to access value from dictionary :-


 To access value from the dictionary , we have to use square bracket with
particular key.

 Example :-
D1 = {‘name’ : ‘zara’ , ‘city’ : ‘rajkot’ , ‘age’ : 5)
Print (“D1[‘name’]:” , D1[‘name’]) o/p :- zara

 How to update value in dictionary :-


 You can update dictionary by adding new entry or by modifying existing
entry.

 Example :-
D1 = {‘name’ : ‘zara’ , ‘city’ : ‘rajkot’ , ‘age’ : 5)

D1[‘school’] = ‘G.T. Girls’ # adding new entry


Print (D1)
D1[‘age’] = 1 #modifying existingentry
Print(D1)

 How to delete value in the dictionary :-


 You can remove particular element from dictionary as well as you can
clear entire dictionary.
 To remove all the entries from dictionary , clear() is used.

 Example :-
 D1 = {‘name’ : ‘zara’ , ‘city’ : ‘rajkot’ , ‘age’ : 5)
del (D1 [‘name’]) # removing single entry
print(D1)
del (D1) # deleting entire dictionary
print(D1)
[Link]() # remove all entries in dictionaryPrint(D1)

40
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

[Link] 1 Word Question – Answer


.
QUESTION ANSWER
1 Dictionay can be represented by _ { } (curly)
brackets.
2 In dictionary ,each key is separated from its : (colon)
values by .
3 Keys are always within dictionary. Unique
4 To remove an entire dictionary del
statement can be used.

Q-13 How to define function ? Explain.

41
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Detail:-

42
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Defining a Function :-
 Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
 You can place any number of arguments inside the brackets().
 The code block of every function must start with colon( : ).
 The statement of the block must be exit with ‘return’ keyword.

o Syntax :-
def <function name> (parameters):
<block of code>
Return
Example :-
def sp():
Print(“hello sp”)
return
 Calling a Function :-
oIf you create your own function , then you can execute it by calling the
function with its name.
oYou have to take care about name of the function and argument of thefunction.
o Syntax :-
<function name> (parameters):
o Example :-
Sp()

43
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Passing parameters to function :-

oYou can pass multiple arguments by separating it with comma (,) .


owhile passing multiple arguments always take care about number of
arguments and types of arguments.

o Syntax :-
def <function name> (p1,p2,p3,…..,pn):
<block of code>
Print Return
Example :-
def sp(str1 ,str2):
(“hello sp”)
Print(str1)
Print(str2)
Return

44
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

1 Word Question – Answer

def
keyword can be used to define
function.
The code block within every function starts Function name &
with & followed by . colon(:)
Function can be called by just providing Function name
.
User can pass some values with function Parameters
which known as _
To return some values by function _ return
statement can be used.

Q-14 Explain Mutability in brief.

45
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

46
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Detail :-
 Everything in python is an object.
 Python represent all it’s data as object.
 The mutability of object decided by its type.
 Some of the object like list and dictionary are mutable.
 Mutable means you can change the content without changing their
identity.
 Some other objects like tuple and string are immutable means that can
not be change.
 Variable in a python also support mutability , means if you call same
method with same variable can be muted anytime by other method.
 List object support mutability like following :

Example :-
My_list= [10,20,30]
Print (my_list)
My_list[0]=40
Print(my_list)

47
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Unlike tuple , the list is mutable it means we can change the value by
assigning new value directly.

1 Word Question – Answer

[Link] QUESTION ANSWER


.

1 is mutable object in python. List


2 is immutable object in python Tuple
3 means you can change the content Mutability
without changing their identity.

48
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Ch-2 OOP using Python

Handling exceptions

When a Python program meets an error, it stops the execution of the rest of the
program. An error in Python might be either an error in the syntax of an expression
or a Python exception.

An exception in Python is an incident that happens while executing a program that


causes the regular course of the program's commands to be disrupted.

When the interpreter identifies a statement that has an error, syntax errors occur.
Consider the following scenario:

#Python code after removing the syntax error


string = "Python Exceptions"

for s in string:
if (s != o:
print( s )

Output:

if (s != o:
^
SyntaxError: invalid syntax

In Python, we catch exceptions and handle them using try and except code blocks.
The try clause contains the code that can raise an exception, while the except
clause contains the code lines that handle the exception.
# Python code to catch an exception and handle it using try and except code blocks

a = ["Python", "Exceptions", "try and except"]


try:
#looping through the elements of the array a, choosing a range that goes beyond the length of the
array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Python interpreter
except:

49
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
DHIMESH PARMAR
1

50
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

print ("Index out of range")

Output:

The index and element from the array is 0 Python


The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range

If a condition does not meet our criteria but is correct according to the Python
interpreter, with intent raise an exception using the raise keyword. We can use a
customized exception in conjunction with the statement.

Python provides two very important features to handle any unexpected error in
your Python programs and to add debugging capabilities in them −
 Exception Handling − here is a list standard Exceptions available in
Python: Standard Exceptions.
 Assertions − This would be covered in Assertions in Python
 List of Standard Exceptions −
[Link]. Exception Name & Description
1 Exception
Base class for all exceptions

2 StopIteration
Raised when the next() method of an iterator does not point to any object.
3 SystemExit
Raised by the [Link]() function.

4 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
5
ArithmeticError
Base class for all errors that occur for numeric calculation.

6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.

51
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
7 FloatingPointError
Raised when a floating point calculation fails.

8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.
9 AssertionError
Raised in case of failure of the Assert statement.

10 AttributeError
Raised in case of failure of attribute reference or assignment.
11 EOFError
Raised when there is no input from either the raw_input() or input() function and the
end of file is reached.

12 ImportError
Raised when an import statement fails.

Assertions in Python

When we're finished verifying the program, an assertion is a consistency test that
we can switch on or off.

The simplest way to understand an assertion is to compare it with an if-then


condition. An exception is thrown if the outcome is false when an expression is
evaluated.

Assertions are made via the assert statement, which was added in Python 1.5 as the
latest keyword.

Assertions are commonly used at the beginning of a function to inspect for valid
input and at the end of calling the function to inspect for valid output.

52
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Assert Statement

Python examines the adjacent expression, first true when it finds an assert
statement. Python throws an AssertionError exception if the result of the
expression is false.

The syntax for the assert clause is −

assert Expressions[, Argument]

Python uses ArgumentException, if the assertion fails, as the argument for the
AssertionError. We can use the try-except clause to catch and handle
AssertionError exceptions, but if they aren't, the program will stop, and the Python
interpreter will generate a traceback.

Code:-

#Python program to show how to use assert keyword


# defining a function
def square_root(Number):
assert (Number>0), "Give a positive integer" return
Number**(1/2)

#Calling function and passing the values print(


square_root(25) )
#print( square_root( -36 ) )

Output:

7 #Calling function and passing the values


----> 8 print( square_root( 36 ) )
9 print( square_root( -36 ) )

Input In [23], in square_root(Number)


3 def square_root( Number ):
----> 4 assert ( Number < 0), "Give a positive integer"
5 return Number**(1/2)

AssertionError: Give a positive integer

53
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Try with Else Clause

Python also supports the else clause, which should come after every except clause,
in the try, and except blocks. Only when the try clause fails to throw an exception
the Python interpreter goes on to the else block.

Here is an instance of a try clause with an else clause.

Code:-

# Python program to show how to use else clause with try and except clauses

# Defining a function which returns reciprocal of a number


def reciprocal( num1 ):
try:
reci = 1 / num1
except ZeroDivisionError:
print( "We cannot divide by zero" )
else:
print ( reci )
# Calling the function and passing values
reciprocal( 4 )
reciprocal( 0 )

Output:-

0 .25

We cannot divide by zero

Finally Keyword in Python

The finally keyword is available in Python, and it is always used after the try-
except block. The finally code block is always executed after the try block has
terminated normally or after the try block has terminated for some other reason.

Here is an example of finally keyword with try-except clauses:

Code:-

54
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
# Python code to show the use of finally clause

# Raising an exception in try block


try:
div = 4 // 0
print( div )
# this block will handle the exception raised
except ZeroDivisionError:
print( "Atepting to divide by zero" )
# this will always be executed no matter exception is raised or not
finally:
print( 'This is code of finally clause' )

Python Classes and Objects


A class is a user-defined blueprint or prototype from which objects are created. Classes
provide a means of bundling data and functionality together.

Creating a new class creates a new type of object, allowing new instances of that type to
be made.

Each class instance can have attributes attached to it for maintaining its state. Class
instances can also have methods for modifying their state.

Syntax: Class Definition

class ClassName:

# Statement

Syntax: Object Definition

obj = ClassName()

print([Link])

Class creates a user-defined data structure, which holds its own data members and
member functions, which can be accessed and used by creating an instance of that class.
A class is like a blueprint for an object.

Some points on Python class:


 Classes are created by keyword class.

55
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator.
Eg.: [Link]
Defining a class
# Python3 program to
# demonstrate defining
# a class
class Dog:
pass

Class Objects
An Object is an instance of a Class. A class is like a blueprint while an instance is a
copy of the class with actual values.
An object consists of :
 State: It is represented by the attributes of an object. It also reflects the
properties of an object.
 Behaviour: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to
interact with other objects.

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e.
the state are unique for each object. A single class may have any number of instances.
Example:

56
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Declaring an object

# Python3 program to
# demonstrate
instantiating # a class

class Dog:

# A simple
class #
attribute
attr1 =
"mammal"
attr2 = "dog"

# A sample method
def fun(self):
print("I'm a",
self.attr1) print("I'm a",
self.attr2)

# Driver code
# Object instantiation
Rodger = Dog()
57
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

# Accessing class attributes


# and method through
objects
print(Rodger.attr1)
[Link]()

The self
Class methods must have an extra first parameter in the method definition. We do not
give a value for this parameter when we call the method, Python provides it.
If we have a method that takes no arguments, we still have one argument.
This is similar to this pointer in C++ and this reference in Java.

When we call a method of this object as [Link](arg1, arg2), this is


automatically converted by Python into [Link](myobject, arg1, arg2) – this is
all the special self is about.

init method
The init method is similar to constructors in C++ and Java. Constructors are used
to initialize the object’s state. Like methods, a constructor also contains a collection of
statements(i.e. instructions) that are executed at the time of Object creation. It runs as
soon as an object of a class is instantiated. The method is useful to do any initialization
you want to do with your object.
Example:

# Sample class with init method


class Person:

# init method or constructor


def init (self, name):
[Link] = name

# Sample Method
def say_hi(self):
print('Hello, my name is', [Link])

58
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
p = Person('Nikhil')
p.say_hi()

Class and Instance Variables


Instance variables are for data, unique to each instance and class variables are for
attributes and methods shared by all instances of the class. Instance variables are
variables whose value is assigned inside a constructor or method with self whereas class
variables are variables whose value is assigned in the class.
Defining instance variables using a constructor.
Example:

59
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

# Python3 program to show that the variables


with a value # assigned in the class declaration,
are class variables and # variables inside methods
and constructors are instance
# variables.

# Class for Dog

class Dog:

# Class
Variable
animal =
'dog'

# The init method or constructor


def init (self, breed, color):

# Instance
Variable
[Link] = breed
[Link] = color

# Objects of Dog class


Rodger = Dog("Pug",
"brown") Buzo =
Dog("Bulldog", "black")

print('Rodger details:')
print('Rodger is a',
[Link])
print('Breed: ',
[Link])
print('Color: ',
60
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
[Link])

print('\nBuzo details:')
print('Buzo is a',
[Link])
print('Breed: ',
[Link]) print('Color:
', [Link])

# Class variables can be accessed


using class # name also
print("\nAccessing class variable using class
name") print([Link])

61
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Abstraction in Python

Abstraction is used to hide the internal functionality of the function from the users.
The users only interact with the basic implementation of the function, but inner
working is hidden.

User is familiar with that "what function does" but they don't know "how it
does."

In simple words, we all use the smartphone and very much familiar with its
functions such as camera, voice-recorder, call-dialing, etc., but we don't know how
these operations are happening in the background.

In Python, an abstraction is used to hide the irrelevant data/class in order to reduce


the complexity. It also enhances the application efficiency.

abstraction can be achieved by using abstract classes and interfaces.

A class that consists of one or more abstract method is called the abstract class.
Abstract methods do not contain their implementation.

Abstract class can be inherited by the subclass and abstract method gets its
definition in the subclass. Abstraction classes are meant to be the blueprint of the
other class. An abstract class can be useful when we are designing large functions.
An abstract class is also helpful to provide the standard interface for different
implementations of components. Python provides the abc module to use the
abstraction in the Python program. Let's see the following syntax.

Syntax

from abc import ABC

class ClassName(ABC):

Abstract Base classes work :


By default, Python does not provide abstract classes. Python comes with a
module that provides the base for defining Abstract Base classes(ABC) and that
module name is ABC. ABC works by decorating methods of the base class as

62
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

abstract and then registering concrete classes as implementations of the abstract


base. A method becomes abstract when decorated with the keyword
@abstractmethod. For Example –

# Python program showing


# abstract base class work

from abc import ABC, abstractmethod

class Polygon(ABC):

@abstractmethod
def noofsides(self):
pass

class Triangle(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 3 sides")

class Pentagon(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 5 sides")

class Hexagon(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 6 sides")

class Quadrilateral(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 4 sides")

# Driver code
63
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

R = Triangle()
[Link]()

K = Quadrilateral()
[Link]()

R = Pentagon()
[Link]()

K = Hexagon()
[Link]()

Other Example:

# Python program showing


# abstract base class work

from abc import ABC, abstractmethod


class Animal(ABC):

def move(self):
pass

class Human(Animal):

def move(self):
print("I can walk and run")

class Snake(Animal):

def move(self):
print("I can crawl")

class Dog(Animal):

def move(self):
print("I can bark")

class Lion(Animal):

64
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

def move(self):
print("I can roar")

# Driver code
R = Human()
[Link]()

K = Snake()
[Link]()

R = Dog()
[Link]()

K = Lion()
[Link]()
Concrete Methods in Abstract Base Classes :
Concrete classes contain only concrete (normal)methods whereas abstract classes
may contain both concrete methods and abstract methods. The concrete class
provides an implementation of abstract methods, the abstract base class can also
provide an implementation by invoking the methods via super().

Example:

# Python program invoking a


# method using super()

import abc
from abc import ABC, abstractmethod

class R(ABC):
def rk(self):
print("Abstract Base Class")
class K(R):
def rk(self):
super().rk()
print("subclass ")
# Driver code
r = K()

65
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

[Link]()
Inheritance in Python
One of the core concepts in object-oriented programming (OOP) languages is inheritance. It is
a mechanism that allows you to create a hierarchy of classes that share a set of properties and
methods by deriving a class from another class. Inheritance is the capability of one class to
derive or inherit the properties from another class.

Benefits of inheritance are:


 It represents real-world relationships well.
 It provides the reusability of a code. We don’t have to write the same code again
and again. Also, it allows us to add more features to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from another class A,
then all the subclasses of B would automatically inherit from class A.
 Inheritance offers a simple, understandable model structure.
 Less development and maintenance expenses result from an inheritance.

Python Inheritance

Syntax Class

BaseClass:

66
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
{Body}

Class DerivedClass(BaseClass):

67
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

{Body}

Example:

# Python program to demonstrate


# single
inheritance #
Base class
class Parent:
def func1(self):
print("This function is in parent

class.") # Derived class

class
Child(Parent)
: def
func2(self):
print("This function is in child
class.") # Driver's code
object = Child()
object.func1()
object.func2()

Creating a Parent Class


Creating a Person class with Display methods.
Python3

# A Python program to demonstrate inheritance

class Person(object):

# Constructor
def init (self, name, id):
[Link] = name
[Link] = id

# To check if this person is an employee


def Display(self):
68
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
print([Link], [Link])
# Driver code
emp = Person("Satyam", 102) # An Object of Person
[Link]()

Creating a Child Class


Here Emp is another class which is going to inherit the properties of the Person class(base
class).

69
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

class Emp(Person):

def Print(self):
print("Emp class called")

Emp_details = Emp("Mayank", 103)

# calling parent class function


Emp_details.Display()

# Calling child class function


Emp_details.Print()

Multiple Inheritance:
When a class can be derived from more than one base class this type of inheritance is
called multiple inheritances. In multiple inheritances, all the features of the base classes
are inherited into the derived class.

Example:
Python3
# Python program to demonstrate

# multiple inheritance

# Base class1

class Mother:

mothername = ""

def mother(self):

70
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

print([Link])

# Base class2

class Father:

fathername = ""

def father(self):

print([Link])

# Derived class

class Son(Mother, Father):

def parents(self):

print("Father :", [Link])

print("Mother :", [Link])

# Driver's code

s1 = Son()

[Link] = "RAM"

[Link] = "SITA"

[Link]()

Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a child
and a grandfather.

Example:

71
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

# Python program to

demonstrate # multilevel

inheritance

# Base class

class Grandfather:

def init (self, grandfathername):

[Link] = grandfathername

# Intermediate class

class Father(Grandfather):
def init (self, fathername, grandfathername):

[Link] = fathername

# invoking constructor of Grandfather

class Grandfather. init (self,

grandfathername)

# Derived

class class

Son(Father):

def init (self, sonname, fathername,

grandfathername): [Link] = sonname

# invoking constructor of Father class

Father. init (self, fathername,

grandfathername) def print_name(self):


72
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
print('Grandfather name :',

[Link]) print("Father

name :", [Link]) print("Son

name :", [Link])

# Driver code
s1 = Son('Narayan', 'Ram',

'Krishna')

print([Link])

s1.print_name()

73
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Hierarchical Inheritance:
When more than one derived class are created from a single base this type of
inheritance is called hierarchical inheritance. In this program, we have a parent (base)
class and two child (derived) classes.

Example:

# Python program to demonstrate

# Hierarchical inheritance

# Base class

class Parent:

def func1(self):

print("This function is in parent class.")

# Derived class1

class Child1(Parent):

def func2(self):

print("This function is in child 1.")

# Derivied class2

class Child2(Parent):

def func3(self):

print("This function is in child 2.")

74
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
object1 = Child1()

object2 = Child2()

object1.func1()

object1.func2()

object2.func1()

object2.func3()

Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.

Example:

# Python program to demonstrate


# hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")

# Driver's code
object = Student3()
object.func1()
object.func2()

75
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Encapsulation in Python
Encapsulation is one of the fundamental concepts in object-oriented programming
(OOP). It describes the idea of wrapping data and the methods that work on data within
one unit.

This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an object’s variable can
only be changed by an object’s method. Those types of variables are known as private
variables.

A class is an example of encapsulation as it encapsulates all the data that is member


functions, variables, etc.

The goal of information hiding is to ensure that an object’s state is always valid by
controlling access to attributes that are hidden from the outside world.

Consider a real-life example of encapsulation, in a company, there are different sections


like the accounts section, finance section, sales section etc. The finance section handles
all the financial transactions and keeps records of all the data related to finance.
Similarly, the sales section handles all the sales-related activities and keeps records of
all the sales. Now there may arise a situation when due to some reason an official from
the finance section needs all the data about sales in a particular month. In this case, he
is not allowed to directly access the data of the sales section. He will first have to
contact some other officer in the sales section and then request him to give the
particular data. This is what encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a single name “sales section”.
Using encapsulation also hides the data.

Implement Encapsulation with a Class in Python

76
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Encapsulation can be a class because a class combines data and methods into a
single unit. Here, the custom function demofunc() displays the records of students
wherein we can access public data member. Using the objects st1, st2, st3, st4, we
have access ed the public methods of the class demofunc()

Example:

class Students:

def init (self, name, rank, points):

[Link] = name

[Link] = rank

[Link] = points

# custom

function def

demofunc(self

):

print("I am

"+[Link]) print("I

got Rank ",+[Link])

# create 4 objects
st1 = Students("Steve", 1, 100)

st2 = Students("Chris", 2, 90)

st3 = Students("Mark", 3, 76)

st4 = Students("Kate", 4, 60)

# call the functions using the objects

77
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
created above [Link]()

[Link]

nc()

[Link]

nc()

[Link]

nc()

Access modifiers in Python to understand the concept of Encapsulation and data


hiding −
 public
 private
 protected

78
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
The public member is accessible from inside or outside the class.

The private Access Modifier


The private member is accessible only inside class. Define a private member by prefixing the
member name with two underscores, for example −
age
Example:
# Python program to
# demonstrate private members
# Creating a Base class
class Base:
def init (self):
self.a = "HVC TY Students"
self. c = "HVC FY Students"

# Creating a derived class


class Derived(Base):
def init (self):

# Calling constructor of
# Base class
Base. init (self)
print("Calling private member of base class: ")
print(self. c)
# Driver code
obj1 = Base()
print(obj1.a)
# Uncommenting print(obj1.c) will
# raise an AttributeError
# Uncommenting obj2 = Derived() will
# also raise an AtrributeError as
# private member of base class
# is called inside derived class

The protected Access Modifier


The protected member is accessible. from inside the class and its sub-class. Define a protected
member by prefixing the member name with an underscore, for example −
_points
Example:

79
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

# Python program to
# demonstrate protected members

# Creating a base class


class Base:
def init (self):

# Protected
member self._a =
2

# Creating a derived class


class Derived(Base):
def init (self):

# Calling
constructor of #
Base class
Base. init (self)
print("Calling protected member of base
class: ", self._a)

# Modify the protected variable:


self._a = 3
print("Calling modified protected member outside
class: ", self._a)

obj1 =
Derived() obj2
= Base()

# Calling protected member


# Can be accessed but should not be done due to
convention print("Accessing protected member of
obj1: ", obj1._a)
# Accessing the protected variable outside
print("Accessing protected member of obj2:
80
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
", obj2._a)

Information hiding in Python

Data hiding is a concept which underlines the hiding of data or information from
the user. It is one of the key aspects of Object-Oriented programming strategies. It
includes object details such as data members, internal work.

Data hiding also minimizes system complexity for increase robustness by limiting
interdependencies between software requirements. Data hiding is also known as
information hiding. In class, if we declare the data members as private so that no
other class can access the data members, then it is a process of hiding data.

81
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
Data Hiding in Python:
The Python document introduces Data Hiding as isolating the user from a part of
program implementation. Some objects in the module are kept internal, unseen, and
unreachable to the user. Modules in the program are easy enough to understand
how to use the application, but the client cannot know how the application
functions.
Data hiding imparts security, along with discarding dependency. Data hiding in
Python is the technique to defend access to specific users in the application. Python
is applied in every technical area and has a user-friendly syntax and vast libraries.
Data hiding in Python is performed using the double underscore before done
prefix.

This makes the class members non-public and isolated from the other classes.
Example:

class Solution:
privateCounter = 0

def sum(self):
self _ privateCounter += 1
print(self. privateCounter)

count =
Solution()
[Link]()
[Link]()

# Here it will show error because it


unable # to access private member
print(count. privateCount)
Output:
Traceback (most recent call last):
File "/home/[Link]", line 11, in
<module> print(count. privateCount)
AttributeError: 'Solution' object has no attribute ' privateCount'

To rectify the error, we can access the private member through the class name :
82
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
class Solution:
privateCounter = 0

def sum(self):
self _ privateCounter += 1
print(self. privateCounter)
count = Solution()
[Link]()

83
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

[Link]()
# Here we have accessed the
private data # member through
class name. print(count._Solution
privateCounter) Advantages of
Data Hiding:
1. It helps to prevent damage or misuse of volatile data by hiding it from the
public.
2. The class objects are disconnected from the irrelevant data.
3. It isolates objects as the basic concept of OOP.
4. It increases the security against hackers that are unable to access
important data.
Disadvantages of Data Hiding:
1. It enables programmers to write lengthy code to hide important data
from common clients.
2. The linkage between the visible and invisible data makes the objects
work faster, but data hiding prevents this linkage.
Searching Algorithms In Python

Searching is a very basic necessity when you store data in different data structures.
The simplest approach is to go across every element in the data structure and match
it with the value you are searching for This is known as Linear search.

It is inefficient and rarely used, but creating a program for it gives an idea about
how we can implement some advanced search algorithms.

Linear Search

In this type of search, a sequential search is made over all items one by one. Every
item is checked and if a match is found then that particular item is returned,
otherwise the search continues till the end of the data structure.
Example

def linear_search(values,

search_for): search_at = 0

search_res = False

# Match the value with each data element


84
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
while search_at < len(values) and

search_res is False: if values[search_at]

== search_for:

search_res =

True else:

85
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

search_at = search_at

+ 1 return search_res

l = [64, 34, 25, 12, 22, 11, 90]

print(linear_search(l, 12))
print(linear_search(l, 91))

Interpolation Search

This search algorithm works on the probing position of the required value. For this
algorithm to work properly, the data collection should be in a sorted form and
equally distributed. Initially, the probe position is the position of the middle most
item of the collection. If a match occurs, then the index of the item is returned. If
the middle item is greater than the item, then the probe position is again calculated
in the sub-array to the right of the middle item. Otherwise, the item is searched in the subarray to
the left of the middle item. This process continues on the sub-array as well until the size of
subarray reduces to zero.
Example:
Example
There is a specific formula to calculate the middle position which is indicated in
the program below

Example:
# Python3 program to
implement # interpolation
search
# with recursion

# If x is present in arr[0..n-
1], then # returns index of
it, else returns -1.

def interpolationSearch(arr, lo, hi, x):


86
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

# Since array is sorted, an element present


# in array must be in range defined by corner
if (lo <= hi and x >= arr[lo] and x <= arr[hi]):

# Probing the position with


keeping # uniform
distribution in mind.
pos = lo + ((hi - lo) // (arr[hi] - arr[lo]) *
(x - arr[lo]))

87
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

# Condition of target found


if arr[pos] == x:
return pos

# If x is larger, x is in right subarray


if arr[pos] < x:
return interpolationSearch(arr,
pos + 1, hi, x)

# If x is smaller, x is in left subarray


if arr[pos] > x:
return interpolationSearch(arr, lo,
pos - 1, x)
return -

1 # Driver

code

# Array of items in
which # search will
be conducted
arr = [10, 12, 13, 16, 18, 19, 20,
21, 22, 23, 24, 33, 35, 42, 47]
n = len(arr)

# Element to be
searched x = 18
index = interpolationSearch(arr, 0, n - 1, x)

if index != -1:
print("Element found at index", index)
else:
print("Element not found")

88
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
Sorting Algorithms in Python
Sorting is defined as an arrangement of data in a certain order. Sorting techniques
are used to arrange data(mostly numerical) in an ascending or descending order. It
is a method used for the representation of data in a more understandable format.
It is an important area of Computer Science. Sorting a large amount of data can take a
substantial amount of computing resources if the methods we use to sort the data are
inefficient. The efficiency of the algorithm is proportional to the number of items it is
traversing.

89
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
For a small amount of data, a complex sorting method may be more trouble than it is
worth. On the other hand, for larger amounts of data, we want to increase the efficiency
and speed as far as possible. We will now discuss the several sorting techniques and
compare them with respect to their time complexity.

Some of the real-life examples of sorting are:


 Telephone Directory: It is a book that contains telephone numbers and
addresses of people in alphabetical order.
 Dictionary: It is a huge collection of words along with their meanings in
alphabetical order.
 Contact List: It is a list of contact numbers of people in alphabetical order on
a mobile phone.
The different types of order are:
 Increasing Order: A set of values are said to be increasing order when every
successive element is greater than its previous element. For example: 1, 2, 3,
4, 5. Here, the given sequence is in increasing order.
 Decreasing Order: A set of values are said to be in decreasing order when
the successive element is always less than the previous one. For Example: 5,
4, 3, 2, 1. Here the given sequence is in decreasing order.
 Non-Increasing Order: A set of values are said to be in non-increasing order
if every ith element present in the sequence is greater than or equal to its (i-
1)th element. This order occurs whenever there are numbers that are being
repeated. For Example: 1, 2, 2, 3, 4, 5. Here 2 repeated two times.
 Non-Decreasing Order: A set of values are said to be in non-decreasing
order if every ith element present in the sequence is less than or equal to its (i-
1)th element. This order occurs whenever there are numbers that are being
repeated. For Example: 5, 4, 3, 2, 2, 1. Here 2 repeated two times.

Sorting Techniques

The different implementations of sorting techniques in Python are:


 Bubble Sort

90
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 Selection Sort
 Insertion Sort

Bubble Sort

Bubble Sort is a simple sorting algorithm. This sorting algorithm repeatedly compares
two adjacent elements and swaps them if they are in the wrong order. It is also known
as the sinking sort. It has a time complexity of O(n2) in the average and worst cases
scenarios and O(n) in the best-case scenario. Bubble sort can be visualized as a queue
where people arrange themselves by swapping with each other so that they all can stand
in ascending order of their heights.
Example

nput: arr[] = {6, 0, 3,

5} First Pass:

The largest element is placed in its correct position, i.e., the end of the array.

Second Pass:

Place the second largest element at correct position

Third Pass:

Place the remaining two elements at their correct positions.

91
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

# Python3 program for Bubble Sort Algorithm

Implementation # Optimized Python program for

implementation of Bubble Sort

def

bubbleSort(ar

r): n =

len(arr)

# Traverse through all array

elements for i in range(n):

swapped = False

# Last i elements are already

in place for j in range(0, n-i-

1):

# Traverse the array from 0 to n-i-1

# Swap if the element found is

greater # than the next

92
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

element

if arr[j] > arr[j+1]:


arr[j], arr[j+1] = arr[j+1],

arr[j] swapped = True

if (swapped ==

False): break

# Driver code to test above


if name == " main ":

arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print("Sorted

array:") for i in

range(len(arr)):

print("%d" % arr[i], end=" ")

# This code is modified by Suraj krushna Yadav

Time Complexity: O(n2)


Auxiliary Space: O(1)

93
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Selection Sort

This sorting technique repeatedly finds the minimum element and sort it in order.
Bubble Sort does not occupy any extra memory space. During the execution of this
algorithm, two subarrays are maintained, the subarray which is already sorted, and the
remaining subarray which is unsorted. During the execution of Selection Sort for every
iteration, the minimum element of the unsorted subarray is arranged in the sorted
subarray. Selection Sort is a more efficient algorithm than bubble sort. Sort has a Time-
Complexity of O(n2) in the average, worst, and in the best cases.
Example

Set the first element as minimum

Compare minimum with the second element. If the second element is smaller
than minimum, assign the second element as minimum.

Compare minimum with the third element. Again, if the third element is
smaller, then assign minimum to the third element otherwise do
nothing. The process goes on until the last element.

94
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

After each iteration, minimum is placed in the front of the unsorted list.

For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated until all
the elements are placed at their correct positions.

95
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

96
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
# Python program for implementation of Selection

# Sort

A = [64, 25, 12, 22, 11]

# Traverse through all array elements

for i in range(len(A)-1):

# Find the minimum element in remaining

# unsorted array

min_idx = i

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

if A[min_idx] > A[j]:

min_idx = j

# Swap the found minimum element with

# the first element

A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above

print ("Sorted array")

for i in range(len(A)):

print(A[i],end=" ")

97
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Insertion Sort

This sorting algorithm maintains a sub-array that is always sorted. Values from the
unsorted part of the array are placed at the correct position in the sorted part. It is more
efficient in practice than other algorithms such as selection sort or bubble sort. Insertion
Sort has a Time-Complexity of O(n2) in the average and worst case, and O(n) in the best
case.
Working of Insertion Sort

Suppose we need to sort the following array.

Initial array

The first element in the array is assumed to be sorted. Take the second element and store it
separately in key.

Compare key with the first element. If the first element is greater than key, then key is placed in

front of the first element.

Now, the first two elements are sorted.

Take the third element and compare it with the elements on the left of it. Placed it just behind the

98
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

element smaller than it. If there is no element smaller than it, then place it at
the beginning of the array.

99
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Similarly, place every unsorted element at its correct position.

100
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Example :

def insertionSort(arr):

n = len(arr) # Get the length of the array

if n <= 1:

return # If the array has 0 or 1 element, it is already sorted, so return

for i in range(1, n): # Iterate over the array starting from the second

101
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
element

key = arr[i] # Store the current element as the key to be inserted in


the right position

j = i-1

while j >= 0 and key < arr[j]: # Move elements greater than key one
position ahead

arr[j+1] = arr[j] # Shift elements to the right

j -= 1

arr[j+1] = key # Insert the key in the correct position

# Sorting the array [12, 11, 13, 5, 6] using insertionSort

arr = [12, 11, 13, 5, 6]

insertionSort(arr)

print(arr)

Time Complexity: O(n2)


Auxiliary Space: O(1)

Hash tables in Python


Hash tables are a type of data structure in which the address or the index value of
the data element is generated from a hash function. That makes accessing the data
faster as the index value behaves as a key for the data value.

In other words Hash table stores key-value pairs but the key is generated through a
hashing function.

So the search and insertion function of a data element becomes much faster as the
key values themselves become the index of the array which stores the data.

In Python, the Dictionary data types represent the implementation of hash tables.
The Keys in the dictionary satisfy the following requirements.
 The keys of the dictionary are hash able i.e. the are generated by hashing
102
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
function which generates unique result for each unique value supplied to the
hash function.

103
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

 The order of data elements in a dictionary is not fixed.


So we see the implementation of hash table by using the dictionary data types as
below.

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value.

Example

# Declare a dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class':

'First'} # Accessing the dictionary with

its key

print "dict['Name']: ", dict['Name']

print "dict['Age']: ", dict['Age']


Output

When the above code is executed, it produces the

following result − dict['Name']: Zara

dict['Age']: 7

Updating Dictionary

You can update a dictionary by adding a new entry or a key-value pair, modifying
an existing entry, or deleting an existing entry as shown below in the simple
example −
Example
# Declare a dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class':

104
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
'First'} dict['Age'] = 8; # update

existing entry dict['School'] = "DPS

School"; # Add new entry print

"dict['Age']: ", dict['Age']

print "dict['School']: ", dict['School']

Output

105
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
When the above code is executed, it produces the

following result − dict['Age']: 8

dict['School']: DPS School

Delete Dictionary Elements

You can either remove individual dictionary elements or clear the entire
contents of a dictionary. You can also delete entire dictionary in a single
[Link] explicitly remove an entire dictionary, just use the del
statement.
Example

dict = {'Name': 'Zara', 'Age': 7,

'Class': 'First'} del dict['Name'];

# remove entry with key 'Name'

[Link](); # remove all entries

in dict

del dict ; # delete entire

dictionary print

"dict['Age']: ",

dict['Age']

print "dict['School']: ", dict['School']

Output

This produces the following result. Note that an exception is raised because
after del dict dictionary does not exist anymore.

dict['Age']:
Traceback (most recent

106
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
call last): File

"[Link]", line 8, in

<module>

print "dict['Age']: ",

dict['Age']; TypeError: 'type'

object is unsubscriptable

Ch 3 Plotting using PyLab


107
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
Installation Step of numpy, matlib

108
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
PyLab is a procedural interface to the Matplotlib object-oriented plotting
library. Matplotlib is the whole package; [Link] is a module in
Matplotlib; and PyLab is a module that gets installed alongside Matplotlib.
PyLab is a convenience module that bulk imports [Link] (for
plotting) and NumPy (for Mathematics and working with arrays) in a single
name space. Although many examples use PyLab.

Basic Plotting

Plotting curves is done with the plot command. It takes a pair of same-length
arrays (or sequences) −
from numpy import *
from pylab import *
x = linspace(-3, 3, 30)
y = x**2
plot(x, y)
show()

The above line of code generates the following output −

Matplotlib is one of the most popular Python packages used for data
visualization. It is a cross-platform library for making 2D plots from data in
arrays.
It provides an object-oriented API that helps in embedding plots in applications
using Python GUI toolkits.
Matplotlib has a procedural interface named the Pylab, which is designed to
resemble MATLAB, a proprietary programming language developed by
MathWorks. Matplotlib along with NumPy can be considered as the open
source equivalent of MATLAB.
Matplotlib and its dependency packages are available in the form of wheel
packages on the standard Python package repositories and can be installed on
Windows, Linux as well as MacOS systems using the pip package manager.

109
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
pip3 install matplotlib
Optionally, you can also install a number of packages to enable better user
interface toolkits.
 tk
 PyQt4
 PyQt5
 pygtk
 wxpython
 pycairo
 Tornado
[Link] is a collection of command style functions that make
Matplotlib work like MATLAB. Each Pyplot function makes some change to a
figure. For example, a function creates a figure, a plotting area in a figure, plots
some lines in a plotting area, decorates the plot with labels, etc.

Types of Plots

[Link] Function & Description

1 Bar
Make a bar plot.

2 Barh
Make a horizontal bar plot.

3 Boxplot
Make a box and whisker plot.

4 Hist
Plot a histogram.

5 hist2d
Make a 2D histogram plot.

110
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
6 Pie
Plot a pie chart.

7 Plot
Plot lines and/or markers to the Axes.

8 Polar
Make a polar plot..

9 Scatter
Make a scatter plot of x vs y.

10 Stackplot
Draws a stacked area plot.

11 Stem
Create a stem plot.

12 Step
Make a step plot.

13 Quiver
Plot a 2-D field of arrows.

Axis Functions

[Link] Function & Description

1 Axes
Add axes to the figure.

111
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
2 Text
Add text to the axes.

3 Title
Set a title of the current axes.

4 Xlabel
Set the x axis label of the current axis.

5 Xlim
Get or set the x limits of the current axes.

6 Xscale
.

7 Xticks
Get or set the x-limits of the current tick locations and labels.

8 Ylabel
Set the y axis label of the current axis.

9 Ylim
Get or set the y-limits of the current axes.

10 Yscale
Set the scaling of the y-axis.

11 Yticks
Get or set the y-limits of the current tick locations and labels.

Figure Functions

112
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
[Link] Function & Description

1 Figtext
Add text to figure.

2 Figure
Creates a new figure.

3 Show
Display a figure.

4 Savefig
Save the current figure.

5 Close
Close a figure window.

We shall now display a simple line plot of angle in radians vs. its sine value in
Matplotlib. To begin with, the Pyplot module from Matplotlib package is
imported, with an alias plt as a matter of convention.
import [Link] as plt
Next we need an array of numbers to plot. Various array functions are defined in
the NumPy library which is imported with the np alias.
import numpy as np
We now obtain the ndarray object of angles between 0 and 2π using the arange()
function from the NumPy library.
x = [Link](0, [Link]*2, 0.05)
The ndarray object serves as values on x axis of the graph. The corresponding
sine values of angles in x to be displayed on y axis are obtained by the
following statement –

y = [Link](x)
The values from two arrays are plotted using the plot() function.

113
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
[Link](x,y)
You can set the plot title, and labels for x and y axes.
You can set the plot title, and labels for x and y axes.
[Link]("angle")
[Link]("sine")
[Link]('sine wave')
The Plot viewer window is invoked by the show() function −
[Link]()
The complete program is as follows −
from matplotlib import pyplot as plt
import numpy as np
import math #needed for definition of pi
x = [Link](0, [Link]*2, 0.05)
y = [Link](x)
[Link](x,y)
[Link]("angle")
[Link]("sine")
[Link]('sine wave')
[Link]()
When the above line of code is executed, the following graph is displayed −

Display Fibonacci Sequence Using Recursion


The term Recursion can be defined as the process of defining something in terms of
itself. In simple words, it is a process in which a function calls itself directly or
indirectly.

A Fibonacci sequence is a sequence of integers which first two terms are 0 and 1 and all other
terms of the sequence are obtained by adding their preceding two numbers.

For example: 0, 1, 1, 2, 3, 5, 8, 13 and so on...

114
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
See this example:

def fibonacci(n):
if n <= 0:
return "Invalid input. The input should be a positive integer."
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)

def print_fibonacci_series(n):
if n <= 0:
print("Invalid input. The input should be a positive integer.")
else:
print("Fibonacci Series:")
for i in range(1, n + 1):
print(fibonacci(i), end=" ")
print()

# Get user input


n_terms = int(input("Enter the number of terms for the Fibonacci series: "))
print_fibonacci_series(n_terms)

Dynamic Programming in Python


Dynamic Programming(DP) is an algorithmic technique for solving an
optimization problem by breaking it down into simpler subproblems and
utilizing the fact that the optimal solution to the overall problem depends upon
the optimal solution to the subproblems.
If an issue can be broken down into subproblems, which are then broken down
into smaller subproblems, and if these subproblems overlap, the answers to
these subproblems can be preserved for future use.

115
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
Dynamic programming works by saving the results of subproblems so that we
don’t have to recalculate them when their solutions are needed.
Example: Fibonacci Series

Dynamic programming works by storing the result of subproblems so that when


their solutions are required, they are at hand and we do not need to recalculate
them.

This technique of storing the value of subproblems is called memoization. By


saving the values in the array, we save time for computations of sub-problems we
have already come across.

Dynamic programming by memoization is a top-down approach to dynamic


programming. By reversing the direction in which the algorithm works i.e. by
starting from the base case and working towards the solution, we can also
implement dynamic programming in a bottom-up manner.

Recursion vs Dynamic Programming


Dynamic programming is mostly applied to recursive algorithms. This is not a
coincidence, most optimization problems require recursion and dynamic
programming is used for optimization.

But not all problems that use recursion can use Dynamic Programming. Unless
there is a presence of overlapping subproblems like in the fibonacci sequence
problem, a recursion can only reach the solution using a divide and conquer
approach.

That is the reason why a recursive algorithm like Merge Sort cannot use Dynamic
Programming, because the subproblems are not overlapping in any way.

Example:
# Function to implement Fibonacci Series
def fibMemo(n, memo):
if n == 1:
return 0
if n == 2:
return 1

116
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
if not n in memo:
memo[n] = fibMemo(n-1, memo) + fibMemo(n-2, memo)
return memo[n]

tempDict = {}
fibMemo(6, tempDict)

#Printing the elements of the Fibonacci Series


print("0")
print("1")
for element in [Link]():
print(element)

Dynamic Programming — 0/1 Knapsack (Python Code)

Dynamic Programming is an algorithmic technique for solving an optimization problem by


breaking it down into simpler subproblems and utilizing the fact that the optimal solution to
the overall problem depends upon the optimal solution to its subproblems.
0/1 Knapsack is perhaps the most popular problem under Dynamic Programming. It is also a
great problem to learn in order to get a hang of Dynamic Programming.
Given weights and values of n items, put these items in a knapsack of capacity W to get
the maximum total value in the knapsack.
we have a weight array that has the weight of all the items. We also have a value array that
has the value of all the items and we have a total weight capacity of the knapsack.
Given this information, we need to find the maximum value we can get while staying in the
weight limit.

The problem is called 0/1 knapsack because we can either include an item as a whole or
exclude it. That is to say, we can’t take a fraction of an item.
Take the following input values.
val = [50,100,150,200]
wt = [8,16,32,40]
W = 64

117
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
Here we get the maximum profit when we include items 1,2 and 4 giving us a total of
200 + 50 + 100 = 350.
Therefore the total profit comes out as :
350

Example:
#Returns the maximum value that can be stored by the bag
def knapSack(W, wt, val, n):
# initial conditions
if n == 0 or W == 0 :
return 0
# If weight is higher than capacity then it is not included
if (wt[n-1] > W):
return knapSack(W, wt, val, n-1)
# return either nth item being included or not
else:
return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1))
# To test above function
val = [50,100,150,200]
wt = [8,16,32,40]
W = 64
n = len(val)
print (knapSack(W, wt, val, n))

Dynamic programming and divide and conquer


In divide and conquer approach, the problem in hand, is divided into smaller sub-problems and then
each problem is solved independently. When we keep on dividing the subproblems into even smaller
sub-problems, we may eventually reach a stage where no more division is possible. Those "atomic"
smallest possible sub-problem (fractions) are solved. The solution of all sub-problems is finally
merged in order to obtain the solution of an original problem.

118
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

Divide/Break
This step involves breaking the problem into smaller sub-problems. Sub-problems should
represent a part of the original problem. This step generally takes a recursive approach to divide
the problem until no sub-problem is further divisible. At this stage, sub-problems become
atomic in nature but still represent some part of the actual problem.

Conquer/Solve
This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the
problems are considered 'solved' on their own.

Merge/Combine
When the smaller sub-problems are solved, this stage recursively combines them until they
formulate a solution of the original problem. This algorithmic approach works recursively and
conquer &s; merge steps works so close that they appear as one.

Examples
The following program is an example of divide-and-conquer programming approach where
the binary search is implemented using python.
def bsearch(list, val):
list_size = len(list) - 1
idx0 = 0
idxn = list_size
# Find the middle most value
while idx0 <= idxn:
midval = (idx0 + idxn)// 2
if list[midval] == val:
return midval
# Compare the value the middle most value
if val > list[midval]:
idx0 = midval + 1
else:
idxn = midval - 1
if idx0 > idxn:
return None

119
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
# Initialize the sorted list
list = [2,7,19,34,53,72]

# Print the search result


print(bsearch(list,72))
print(bsearch(list,11))

120
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Unit -4 Network Programming and GUI using Python

Python provides two levels of access to network services. At a low level, you can
access the basic socket support in the underlying operating system, which allows
you to implement clients and servers for both connection-oriented and
connectionless protocols.
Python also has libraries that provide higher-level access to specific application-
level network protocols, such as FTP, HTTP, and so on.

Python Internet protocols

A list of some important modules in Python Network/Internet programming.

Protocol Common function Port No Python module


HTTP Web pages 80 httplib, urllib, xmlrpclib
NNTP Usenet news 119 nntplib
FTP File transfers 20 ftplib, urllib
SMTP Sending email 25 smtplib
POP3 Fetching email 110 poplib
IMAP4 Fetching email 143 imaplib
Telnet Command lines 23 telnetlib
Gopher Document transfers 70 gopherlib, urllib

What are Sockets?


A socket is the end-point in a flow of communication between two programs or
communication channels operating over a network. They are created using a set
of programming requests called socket API (Application Programming
Interface). Python's socket library offers classes for handling common transports
as a generic interface.

Sockets use protocols for determining the connection type for port-to-port
communication between client and server machines. The protocols are used for:

121
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
 Domain Name Servers (DNS)
 IP addressing
 E-mail
 FTP (File Transfer Protocol) etc...
 Sockets are the endpoints of a bidirectional communications channel.
Sockets may communicate within a process, between processes on the
same machine, or between processes on different continents.

122
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
 Sockets may be implemented over a number of different channel types:
Unix domain sockets, TCP, UDP, and so on. The socket library provides
specific classes for handling the common transports as well as a generic
interface for handling the rest.
Sockets Vocabulary
Sockets have their own set

Term Description
Domain The set of protocols used for transport mechanisms like
AF_INET, PF_INET, etc.
Type Type of communication between sockets
Protocol Identifies the type of protocol used within domain and type.
Typically it is zero
Port The server listens for clients calling on one or more ports. it can be
a string containing a port number, a name of the service, or a
Fixnum port
Hostnam Identifies a network interface. It can be a
e
 a string containing hostname, IPv6 address, or a
double-quad address.
 an integer
 a zero-length string
 a string “<broadcast>”

Socket Programming
Socket programming is a way of connecting two nodes on a network to
communicate with each other. One socket(node) listens on a particular port at
an IP, while the other socket reaches out to the other to form a connection.
The server forms the listener socket while the client reaches out to the server.
They are the real backbones behind web browsing. In simpler terms, there is a
server and a client. We can use the socket module for socket programming.
For this, we have to include the socket module –

import socket

to create a socket we have to use the [Link]() method.


Once you have socket object, then you can use required functions to create your
client or server program. Following is the list of functions required −

Server Socket Methods

123
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

[Link]. Method & Description

1 [Link]()

This method binds address (hostname, port number pair) to socket.

2 [Link]()
This method sets up and start TCP listener.

3 [Link]()
This passively accept TCP client connection, waiting until connection
arrives (blocking).

Client Socket Methods

[Link]. Method & Description


1 [Link]()
This method actively initiates TCP server connection.

General Socket Methods

[Link]. Method & Description


1 [Link]()
This method receives TCP message

2 [Link]()
This method transmits TCP message

3 [Link]()
This method receives UDP message

4 [Link]()
This method transmits UDP message

124
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

5 [Link]()
This method closes socket

6 [Link]()
Returns the hostname.

A Simple Client
Let us write a very simple client program which opens a connection to a given
port 12345 and given host. This is very simple to create a socket client using
Python's socket module function.
The [Link](hosname, port ) opens a TCP connection to hostname on
the port. Once you have a socket open, you can read from it like any IO object.
When done, remember to close it, as you would close a file.

Example:
#!/usr/bin/python # This is [Link] file

import socket # Import socket module

s = [Link]() # Create a socket object


host = [Link]() # Get local machine name
port = 12345 # Reserve a port for your service.

[Link]((host, port))
print [Link](1024)
[Link]() # Close the socket when done

Python IP Address
An IP(Internet Protocol) address is an identifier assigned to each computer and other
device(e.g., router, mobile, etc.) connected to a TCP/IP network that is used to locate
and identify the node in communication with other nodes on the network. IP addresses
are usually written and displayed in human-readable notation such as [Link] in
IPv4(32-bit IP address).
Using the socket library to find IP Address
Step 1: Import socket library
IP = [Link](hostname)
Step 2: Then print the value of the IP into the print() function your IP address.
print("Your Computer IP Address is:" + IPAddr)

125
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Example:
# Python Program to Get IP Address
import socket
hostname = [Link]()

126
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

IPAddr = [Link](hostname)

print("Your Computer Name is:" +


hostname) print("Your Computer IP
Address is:" + IPAddr)

URL in Python
Python is a very strong and advanced programming language, and we can
perform various tasks and functions using Python. One of such tasks that we can
easily do with the help of Python is opening a url with a Python program. In this
tutorial, we are going to discuss the methods or ways which we can use to open
a url in Python.

Opening url in Python


We can use a Python program to open a url using the Python script, and for this,
we can use a different set of libraries. We have different methods in which we
will use different libraries and their functions to open a url given in the program.

We are going to use the following methods in this section to open a given url
using a Python program:

1. Using Urllib library function

2. Using webbrowser library function

3. Using selenium library function

In all three libraries, as we have mentioned above, the first two libraries are
generally coming pre-installed with the latest Python versions. We are going to
discuss all three methods and we will use a Python program in each to better
understand their implementation.

Method 1: Using urllib library function


Urllib is an inbuilt Python module that we can use to work on urls and open url
using a Python program. In the urllib module, various classes and functions are
defined, which help us to perform various url actions using a Python program.

We will use the urlopen() method by importing [Link] library in the


program, and then we give url inside this function so that it will open in the

127
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
browser of our device. To better understand the implementation of this method
of using urlopen().

Example 1: Look at the following Python program where we using urlopen() function:

# Importing urllib request module in the program


import [Link]
# Using urlopen() function with url in it
webUrl = [Link](' [Link]

128
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

We have opened the url of 'Python tutorial in JavaTpoint' in our browser by


giving the url link inside the urlopen() function in the program.

Method 2: Using webbrowser library function:


Now, we will use the webbrowser library, which is a library in Python to work
with the web- based content. An environment is created for the user by using the
webbrowser module that enables the user to display various web-based contents
in the Python application itself.

Before we start working with the webbrowser library, we should make sure that
it is properly installed in our system where we are running Python. And, if the
webbrowser library is not present in the system, then we can install the same by
using the following command in the command prompt of our device.

pip install webbrowser

we will start working with the webbrowser library and open url with the
webbrowser library; we will use the open() function of it in the program. To
better understand the implementation of this method of using the webbrowser
library for opening url in Python, we will use it in an example Python program
and open a link through it.

Example 2: Look at the following Python program:

1. # Import webbrowser module in the program


2. import webbrowser
3. # Add a URL of JavaTpoint to open it in a browser
4. url= '[Link]
5. # Open the URL using open() function of module
6. webbrowser.open_new_tab(url)

Accessing HTML source code using Python Selenium


Selenium is an open-source testing tool, which means it can be downloaded from
the internet without spending anything. Selenium is a functional testing tool and
also compatible with non-functional testing tools as well.
129
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

To start, install the selenium module for Python.


pip install selenium
We can access HTML source code with Selenium webdriver. We can
take the help of the page_source method and print the value obtained from it
in the console.
Syntax
src = driver.page_source

130
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

We can also access the HTML source code with the help of Javascript commands
in Selenium. We shall take the help of execute_script method and pass the
command return [Link] as a parameter to the method.

Selenium get HTML

You can retrieve the HTML source of an URL with the code shown below.
It first starts the web browser (Firefox), loads the page and then outputs the HTML
code.

The code below starts the Firefox web rbowser, opens a webpage with the get()
method and finally stores the webpage html with browser.page_source.

Example:

from selenium import webdriver


import time

# start web browser


browser=[Link]()

# get source code


[Link]("[Link]
html = browser.page_source
[Link](2)
print(html)

# close web browser


[Link]()

Downloading files from web using Python?


Python provides different modules like urllib, requests etc to download files
from the web. I am going to use the request library of python to efficiently
download files from the URLs.
Let’s start a look at step by step procedure to download files using URLs using request
library−
1. Import module
import requests
2. Get the link or url

131
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

url =
'[Link]
co' r = [Link](url,
allow_redirects=True)

132
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

3. Save the content with name.


open('[Link]', 'wb').write([Link])
save the file as [Link].

Example
import requests
url =
'[Link]
co' r = [Link](url,
allow_redirects=True)
Result
open('[Link]', 'wb').write([Link])

We can see the file is downloaded(icon) in our current working directory.


But we may need to download different kind of files like image, text, video etc
from the web. So let’s first get the type of data the url is linking to−
>>> r = [Link](url, allow_redirects=True)
>>> print([Link]('content-
type')) image/png
However, there is a smarter way, which involved just fetching the headers of a
url before actually downloading it. This allows us to skip downloading files
which weren’t meant to be downloaded.
>>>
print(is_downloadable('[Link]
_dqFGI')) False
>>> print(is_downloadable('[Link]
To restrict the download by file size, we can get the filezie from the content-
True
length header and then do as per our requirement.
contentLength = [Link]('content-length', None)
if contentLength and contentLength > 2e8: # 200 mb
approx return False
Get filename from an URL
To get the filename, we can parse the url. Below is a sample routine which
133
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
fetches the last string after backslash(/).

134
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
url= "[Link]
if [Link]('/'):
print([Link]('/', 1)[1]
Above will give the filename of the url. However, there are many cases where
filename information is not present in the url for example –
[Link] In such a case, we need to get the Content-Disposition
header, which contains the filename information.
import requests
import re

def getFilename_fromCd(cd):
"""
Get filename from content-disposition
"""
if not cd:
return None
fname = [Link]('filename=(.+)', cd)
if len(fname) == 0:
return None
return fname[0]
url = '[Link]
r = [Link](url, allow_redirects=True)
filename = getFilename_fromCd([Link]('content-disposition'))
open(filename, 'wb').write([Link])

The above url-parsing code in conjunction with above program will give you
filename from Content-Disposition header most of the time.

Python TCP/IP Server and Client?


Inter Process Communication (IPC)
IPC is a communication mechanism that an Operating System offers for processes
to communicate with each other. There are various types of IPCs such as:

 Pipes
 Sockets
 Files
 Signals
 Shared Memory
135
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
 Message Queues/ Message Passing

136
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
Sockets are used to send data over the network either to a different process on the
same computer or to another computer on the network.

There are four types of sockets namely,

 Stream Sockets
 Datagram Sockets
 Raw Sockets
 Sequenced Packet Sockets

Stream sockets and datagram sockets are the two most popular choices.

Stream Sockets Datagram Sockets

Guaranteed delivery No delivery guarantees

Uses TCP (Transmission Control Protocol) Used UDP (User Datagram Protocol)

Needs an open connection Don’t need to have an open connection

Distributed Systems are built using the concept of Client Service architectures.

 Clients send requests to servers


 Servers send back responses or error codes accordingly

The communication across servers and clients in a distributed system uses sockets
as a popular form of IPC. Sockets are nothing but a combination of

 IP Address. Ex: localhost


 Port number. Ex: 80

Each machine (with an IP address) has several applications running on it. We need
to know on which port an application is running in to send requests to it.

TCP stands for Transmission Control Protocol, a communications protocol for


computers to exchange information over a network.

IP stands for Internet Protocol. IP identifies the IP address of the applications or


devices to send data to and forms the Network Layer in the OSI stack. TCP defines

137
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
how to transport the data over the network. Ensuring delivery guarantee is still
TCP’s job.

When we send an HTTP request to a server, we first establish a TCP connection,


so HTTP sits on top of TCP as the transport layer. When a user types a URL into
the browser, the browser sets up a TCP socket using the IP address and port
number and starts sending data to that socket. This request is sent as bytes in the
form of data packets over the network. The server will then respond to the request.

The benefits of a TCP connection is that a server sends acknowledgement of each


packet based on which the client retransmits data in case some packets get
dropped. Each packet has a sequence number that the server uses to assemble them
upon receiving.

Now let’s look at an example Python program on how to write a simple script to
setup a TCP/IP server and client.

Python TCP/IP server

import socket

# Set up a TCP/IP server


tcp_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to server address and port 81


server_address = ('localhost', 81)
tcp_socket.bind(server_address)

# Listen on port 81
tcp_socket.listen(1)

while True:
print("Waiting for connection")
connection, client = tcp_socket.accept()

try:
print("Connected to client IP: {}".format(client))

# Receive and print data 32 bytes at a time, as long as the client is sending
something
while True:
data = [Link](32)
print("Received data: {}".format(data))

138
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

if not data:
break

finally:
[Link]()

Python TCP/IP Client

import socket

# Create a connection to the server application on port 81


tcp_socket = socket.create_connection(('localhost', 81))

try:
data = [Link](‘Hi. I am a TCP client sending data to the server’)
tcp_socket.sendall(data)

finally:
print("Closing socket")
tcp_socket.close()

Terminal Output

Waiting for connection


Connected to client IP: ('[Link]', 65483)
Received data: Hi. I am a TCP c
Received data: client sending da
Received data: ta to the server
Received data:
Waiting for connection

Example Link:
[Link]
server-and-client/

[Link]

User Datagram Client and Server


The user datagram protocol (UDP) works differently from TCP/IP. Where TCP
is a stream oriented protocol, ensuring that all of the data is transmitted in the

139
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

right order, UDP is a message oriented protocol.

140
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
UDP does not require a long-lived connection, so setting up a UDP socket is a
little simpler. On the other hand, UDP messages must fit within a single packet
(for IPv4, that means they can only hold 65,507 bytes because the 65,535 byte
packet also includes header information) and delivery is not guaranteed as it is
with TCP.
this is a lightweight protocol which has basic error checking mechanism with no
acknowledgement and no sequencing but very fast due to these reasons.
UDP makes use of Internet Protocol of the TCP/IP suit. In communications using
UDP, a client program sends a message packet to a destination server wherein the
destination server also runs on UDP.

Properties of UDP:
 The UDP does not provide guaranteed delivery of message packets. If for
some issue in a network if a packet is lost it could be lost forever.
 Since there is no guarantee of assured delivery of messages, UDP is
considered an unreliable protocol.
 The underlying mechanisms that implement UDP involve no connection-
based communication. There is no streaming of data between a UDP server
or and an UDP Client.
 An UDP client can send "n" number of distinct packets to an UDP server
and it could also receive "n" number of distinct packets as replies from the
UDP server.
 Since UDP is connectionless protocol the overhead involved in UDP is less
compared to a connection based protocol like TCP.
Example: UDP Server using Python

import socket

localIP = "[Link]"

141
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

localPort = 20001

bufferSize = 1024

142
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
msgFromServer = "Hello

UDP Client" bytesToSend =

[Link](msgFromServer) #

Create a datagram socket

UDPServerSocket = [Link](family=socket.AF_INET,

type=socket.SOCK_DGRAM) # Bind to address and ip

[Link]((localIP,

localPort)) print("UDP server up and

listening")

# Listen for incoming datagrams

while(True):

bytesAddressPair =

[Link](bufferSize)

message = bytesAddressPair[0]

address = bytesAddressPair[1]

clientMsg = "Message from

Client:{}".format(message) clientIP =

"Client IP Address:{}".format(address)

print(clientMsg)

print(clientIP)

# Sending a reply to client


143
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
[Link](bytesToSe

nd, address)

Output:

UDP server up and listening

Message from Client:b"Hello

UDP Server" Client IP

Address:("[Link]", 51696)

Example: UDP Client using Python

import socket

msgFromClient = "Hello

UDP Server" bytesToSend =

[Link](msgFromClient)

144
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
serverAddressPort = ("[Link]", 20001)

bufferSize = 1024

# Create a UDP socket at client side

UDPClientSocket = [Link](family=socket.AF_INET,

type=socket.SOCK_DGRAM) # Send to server using created UDP

socket

[Link](bytesToSend,

serverAddressPort) msgFromServer =

[Link](bufferSize) msg =

"Message from Server

{}".format(msgFromServer[0]) print(msg)

Output:

Message from Server b"Hello UDP Client"

File Transfer using TCP Socket


his is the most basic file transfer program that we can do using a client-server
architecture. Here, we are going to do the build a client and a server program
file, where the client read the data from a text file and send it to the server. The
server receives it and saves the data to another text file.

The overall procedure for the TCP file transfer is presented in the figure below.

145
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

Example: [Link]

imp
ort
soc
ket

IP =
[Link]([Link]())
PORT = 4455
ADDR = (IP, PORT)
FORMAT = "utf-8"
SIZE = 1024

def main():
""" Staring a TCP socket. """
client = [Link](socket.AF_INET,

146
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

socket.SOCK_STREAM)

""" Connecting to the server. """


[Link](ADDR)

""" Opening and reading the file data. """


file = open("data/[Link]", "r")
data = [Link]()

""" Sending the filename to


the server. """
[Link]("[Link]".encode(FO
RMAT))
msg =
[Link](SIZE).decode(FOR
MAT)
print(f"[SERVER]: {msg}")

""" Sending the file data to the


server. """
[Link]([Link](FOR
MAT))
msg =
[Link](SIZE).decode(FOR
MAT)
print(f"[SERVER]: {msg}")

""" Closing the file. """


[Link]()

""" Closing the connection


from the server. """
[Link]()

if name == " main ":


main()
Example: [Link]

imp
ort

147
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

soc
ket

IP = [Link]([Link]())
PORT = 4455
ADDR = (IP, PORT)
SIZE = 1024
FORMAT = "utf-8"

def main():
print("[STARTING] Server is starting.")
""" Staring a TCP socket. """
server = [Link](socket.AF_INET,
socket.SOCK_STREAM)
""" Bind the IP and PORT to the server. """
[Link](ADDR)

""" Server is listening, i.e., server is now waiting


for the client to connected. """
[Link]()
print("[LISTENING] Server is listening.")

while True:
""" Server has accepted the connection from the client.
"""
conn, addr = [Link]()
print(f"[NEW CONNECTION]
{addr} connected.")
""" Receiving the filename from
the client. """
filename =
[Link](SIZE).decode(FORMA
T)
print(f"[RECV] Receiving the
filename.")
file = open(filename, "w")
[Link]("Filename
received.".encode(FORMAT))
""" Receiving the file data from
the client. """
data =
[Link](SIZE).decode(FORMA
148
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python

T)
print(f"[RECV] Receiving the file
data.")
[Link](data)
[Link]("File data
received".encode(FORMAT))
""" Closing the file. """
[Link]()

""" Closing the connection from


the client. """
[Link]()
print(f"[DISCONNECTED] {addr}
disconnected.")
if name == " main ":
main()

Two-Way Communication between Server and Client in python


sockets can either be configured to act as a server or client, to achieve bi-
directional communication over TCP using the SOCK_STREAM family. In this
example, we shall implement a simple echo application that receives all
incoming data and sends them back to the sender. For that we will implement
both client and server sockets. Furthermore, we will use the local loopback
address [Link] or localhost for our connections.
A socket is one endpoint of a two-way communication link between two
programs running on ( a node in) a computer network. One socket (the
server) listens on a particular port on and IP address, while another socket(the
client) connects to the listening server to achieve communication.

Chat Program two way communication | Socket Programming in Python


[Link]
import socket
server_socket = [Link](socket.AF_INET,socket.SOCK_STREAM)

149
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
LOCALHOST = '[Link]'
port = 9990
server_socket.bind((LOCALHOST,por
t)) server_socket.listen(5)

print("Server started...")
client_sockets,addr=server_socke
[Link]() while True:
msg_received =
client_sockets.recv(1024)
msg_received =
msg_received.decode()
print("Client:", msg_received)
msg_send = input("Me:")
client_sockets.send(msg_send.encod
e("ascii"))

client_sockets.close()

[Link]
import socket
s=
[Link](socket.AF_INET,socket.SOCK_ST
REAM) LOCALHOST = '[Link]'
port = 9990

[Link]((LOCALHO
ST,port)) print("New
client created:")
while True:
client_message = input("Me: ")
[Link](client_message.encode())

msg_received =
[Link](1024) msg_received
= msg_received.decode()
print("Server:",msg_receive
d)

150
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
if msg_received == 'exit':
break;
[Link]()

Send Simple Email Using Python


Python’s built-in email package allows you to structure more fancy emails, which can
then be transferred with smtplib as you have done already. Below, you’ll learn how
use the email package to send emails with HTML content and attachments.

When you send a text message using Python, then all the content are treated
as simple text. Even if you include HTML tags in a text message, it is
displayed as simple text and HTML tags will not be formatted according to
HTML syntax. But Python provides option to send an HTML message as
actual HTML message.

151
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
While sending an e-mail message, you can specify a Mime version, content
type and character set to send an HTML e-mail.

Example

Following is the example to send HTML content as an e-mail:

#!/usr/bin/python

import smtplib

message = """From: From Person <from@[Link]>

To: To Person <to@[Link]>

MIME-Version: 1.0

Content-type: text/html

Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>

<h1>This is headline.</h1>

"""

try:

smtpObj = [Link]('localhost')

[Link](sender, receivers, message)

print "Successfully sent email"

except SMTPException:

print "Error: unable to send email"

Sending Attachments as an E-
mail

152
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
To send an e-mail with mixed content requires to set Content-type header to
multipart/mixed. Then, text and attachment sections can be specified within
boundaries.

A boundary is started with two hyphens followed by a unique number, which


cannot appear in the message part of the e-mail. A final boundary denoting the e-
mail's final section must also end with two hyphens.

Attached files should be encoded with the pack("m") function to have base64
encoding before transmission.

Example
Following is the example, which sends a file /tmp/[Link] as an attachment:

#!/usr/bin/python

import smtplib

import base64

filename = "/tmp/[Link]"

# Read a file and encode it into base64 format

fo = open(filename, "rb")

filecontent = [Link]()

encodedcontent = base64.b64encode(filecontent) # base64

sender = 'webmaster@[Link]'

reciever = '[Link]@[Link]'

marker = "AUNIQUEMARKER"

body ="""

This is a test email to send an attachement.

153
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
"""

# Define the main headers.

part1 = """From: From Person <me@[Link]>

To: To Person <[Link]@[Link]>

Subject: Sending Attachement

MIME-Version: 1.0

Content-Type: multipart/mixed; boundary=%s

--%s

""" % (marker, marker)

# Define the message action

part2 = """Content-Type: text/plain

Content-Transfer-Encoding:8bit

%s

--%s

""" % (body,marker)

# Define the attachment section

part3 = """Content-Type: multipart/mixed; name=\"%s\"

Content-Transfer-Encoding:base64

Content-Disposition: attachment; filename=%s

%s

--%s--

""" %(filename, filename, encodedcontent, marker)

message = part1 + part2 + part3

154
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
try:

smtpObj = [Link]('localhost')

[Link](sender, reciever,

message) print "Successfully sent email"

except Exception:

print "Error: unable to send email"

155
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

GUI Programming

Event-driven programming paradigm in python


Event-driven programming focuses on events. Eventually, the flow of program
depends upon events. Until now, we were dealing with either sequential or
parallel execution model but the model having the concept of event-driven
programming is called asynchronous model.
Event-driven programming depends upon an event loop that is always listening
for the new incoming events. The working of event-driven programming is
dependent upon events. Once an event loops, then events decide what to execute
and in what order.
Following flowchart will help you understand how this works −

Python Module – Asyncio


Asyncio module was added in Python 3.4 and it provides infrastructure for
writing single-threaded concurrent code using co-routines. Following are the
different concepts used by the Asyncio module −
The event loop
Event-loop is a functionality to handle all the events in a computational code. It
156
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
acts round the way during the execution of whole program and keeps track of
the incoming and execution of events. The Asyncio module allows a single
event loop per process. Followings are some methods provided by Asyncio
module to manage an event loop −
 loop = get_event_loop() − This method will provide the event
loop for the current context.

157
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
 loop.call_later(time_delay,callback,argument) − This method
arranges for the callback that is to be called after the given
time_delay seconds.
 loop.call_soon(callback,argument) − This method arranges for a
callback that is to be called as soon as possible. The callback is
called after call_soon() returns and when the control returns to the
event loop.
 [Link]() − This method is used to return the current time
according to the event loop’s internal clock.
 asyncio.set_event_loop() − This method will set the event loop for
the current context to the loop.
 asyncio.new_event_loop() − This method will create and return a
new event loop object.
 loop.run_forever() − This method will run until stop() method is
called.
Example
The following example of event loop helps in printing hello world by using the
get_event_loop() method. This example is taken from the Python official docs.
import asyncio

def hello_world(loop):
print('Hello World')
[Link]()

loop = asyncio.get_event_loop()

loop.call_soon(hello_world, loop)

loop.run_forever()
[Link]()
Output
Hello World

Futures
This is compatible with the [Link] class that represents a computation that
has not been accomplished. There are following differences between [Link]
and [Link] −
 result() and exception() methods do not take a timeout argument and raise an
exception when the future isn’t done yet.
 Callbacks registered with add_done_callback() are always called via the event
loop’s call_soon().
 [Link] class is not compatible with the wait() and
as_completed() functions in the [Link] package.
Example
158
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
The following is an example that will help you understand how to use [Link]
class.
import asyncio

159
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
async def Myoperation(future):
await [Link](2)
future.set_result('Future Completed')

loop = asyncio.get_event_loop()
future = [Link]()
asyncio.ensure_future(Myoperation(future))
try:
loop.run_until_complete(future)
print([Link]())
finally:
[Link]()
Output
Future Completed
Coroutines
The concept of coroutines in Asyncio is similar to the concept of standard Thread object under
threading module. This is the generalization of the subroutine concept. A coroutine can be
suspended during the execution so that it waits for the external processing and returns from the
point at which it had stopped when the external processing was done. The following two ways
help us in implementing coroutines −

async def function()


This is a method for implementation of coroutines under Asyncio module. Following is a
Python script for the same −
import asyncio

async def Myoperation():


print("First Coroutine")

loop = asyncio.get_event_loop()
try:
loop.run_until_complete(Myoperation())

finally:
[Link]()
Output
First Coroutine
@[Link] decorator
Another method for implementation of coroutines is to utilize generators with the
@[Link] decorator. Following is a Python script for the same −
import asyncio

@[Link]
def Myoperation():
print("First Coroutine")

loop = asyncio.get_event_loop()
try:
160
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
loop.run_until_complete(Myoperation())

finally:
[Link]()
Output
First Coroutine
Tasks
This subclass of Asyncio module is responsible for execution of coroutines within an event
loop in parallel manner. Following Python script is an example of processing some tasks in
parallel.
import asyncio
import time
async def Task_ex(n):
[Link](1)
print("Processing {}".format(n))
async def Generator_task():
for i in range(10):
asyncio.ensure_future(Task_ex(i))
int("Tasks Completed")
[Link](2)

loop = asyncio.get_event_loop()
loop.run_until_complete(Generator_task())
[Link]()
Output
Tasks Completed
Processing 0
Processing 1
Processing 2
Processing 3
Processing 4
Processing 5
Processing 6
Processing 7
Processing 8
Processing 9

Python offers multiple options for developing GUI (Graphical User Interface).
Out of all the GUI methods, tkinter is the most commonly used method. It is a
standard Python interface to the Tk GUI toolkit shipped with Python. Python
with tkinter is the fastest and easiest way to create the GUI applications.
Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.
1. Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python.
2. wxPython − This is an open-source Python interface for
wxWindows [Link]

161
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
3. JPython − JPython is a Python port for Java which gives Python scripts seamless
access to Java class libraries on the local machine [Link]
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides
a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented
interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −
1. Import the Tkinter module.
2. Create the GUI application main window.
3. Add one or more of the above-mentioned widgets to the GUI application.
4. Enter the main event loop to take action against each event triggered by the user.
Here are some common use cases for Tkinter in more detail:
Creating windows and dialog boxes: Tkinter can be used to create windows and
dialog boxes that allow users to interact with your program. These can be used
to display information, gather input, or present options to the user. To create a
window or dialog box, you can use the Tk() function to create a root window,
and then use functions like Label, Button, and Entry to add widgets to the
window.

Building a GUI for a desktop application: Tkinter can be used to create the
interface for a desktop application, including buttons, menus, and other
interactive elements. To build a GUI for a desktop application,
you can use functions like Menu, Checkbutton, and RadioButton to
create menus and interactive elements, and use layout managers like pack and
grid to arrange the widgets on the window.

Adding a GUI to a command-line program: Tkinter can be used to add a GUI to


a command-line program, making it easier for users to interact with the program
and input arguments. To add a GUI to a command-line program, you can use
functions like Entry and Button to create input fields and buttons, and use
event handlers like command and bind to handle user input.

Creating custom widgets: Tkinter includes a variety of built-in widgets, such as


buttons, labels, and text boxes, but it also allows you to create your own custom
widgets. To create a custom widget, you can define a class that inherits
from the Widget class and overrides its methods to define the behaviour and
appearance of the widget.

1. Import tkinter package and all of its modules.


2. Create a root window. Give the root window a title(using title()) and
dimension(using geometry()). All other widgets will be inside the root
window.
3. Use mainloop() to call the endless loop of the window. If you forget to call this
162
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
nothing will appear to the user. The window will wait for any user interaction
till we close it.
Example:
# Import Module

163
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
from tkinter import *

# create root window


root = Tk()

# root window title and dimension


[Link]("Welcome to Harivandana College")
# Set geometry (widthxheight)
[Link]('350x200')

# all widgets will be here


# Execute Tkinter
[Link]()

We’ll add a label using the Label Class and change its text configuration as
desired. The grid() function is a geometry manager which keeps the label in the
desired location inside the window. If no parameters are mentioned by default it
will place it in the empty cell; that is 0,0 as that is the first location.

Example:
# Import Module
from tkinter import *

# create root window


root = Tk()

# root window title and dimension


[Link]("Welcome to Harivandana College")
# Set geometry(widthxheight)
[Link]('350x200')

#adding a label to the root window


lbl = Label(root, text = "Are you a Geek?")
[Link]()

# Execute Tkinter
[Link]()

5. Now add a button to the root window. Changing the button configurations gives us
a lot of options. In this example we will make the button display a text once it is
clicked and also change the color of the text inside the button.

# Import Module
from tkinter import *

# create root window


root = Tk()
164
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# root window title and dimension
[Link]("Welcome to Harivanda College")
# Set geometry(widthxheight)
[Link]('350x200')

# adding a label to the root window


lbl = Label(root, text = "Are you a Student?")
[Link]()

# function to display text when


# button is clicked
def clicked():
[Link](text = "I just got clicked")

# button widget with red color text


# inside
btn = Button(root, text = "Click me" ,
fg = "red", command=clicked)
# set Button grid
[Link](column=1, row=0)

# Execute Tkinter
[Link]()

6. Using the Entry() class we will create a text box for user input. To display the user
input text, we’ll make changes to the function clicked(). We can get the user entered
text using the get() function. When the Button after entering of the text, a default text
concatenated with the user text. Also change button grid location to column 2
as Entry() will be column 1.

Example:
# Import Module
from tkinter import *

# create root window


root = Tk()

# root window title and dimension


[Link]("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
[Link]('350x200')

# adding a label to the root window


lbl = Label(root, text = "Are you a Geek?")
[Link]()

165
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# adding Entry Field
txt = Entry(root, width=10)
[Link](column =1, row =0)

# function to display user text when


# button is clicked
def clicked():

res = "You wrote" + [Link]()


[Link](text = res)

# button widget with red color text inside


btn = Button(root, text = "Click me" ,
fg = "red", command=clicked)
# Set Button Grid
[Link](column=2, row=0)

# Execute Tkinter
[Link]()

7. To add a menu bar, you can use Menu class. First, we create a menu, then we add
our first label, and finally, we assign the menu to our window. We can add menu items
under any menu by using add_cascade().

# Import Module
from tkinter import *

# create root window


root = Tk()

# root window title and dimension


[Link]("Welcome to GeekForGeeks")
# Set geometry(widthxheight)
[Link]('350x200')

# adding menu bar in root window


# new item in menu bar labelled as 'New'
# adding more items in the menu bar
menu = Menu(root)
item = Menu(menu)
item.add_command(label='New')
menu.add_cascade(label='File', menu=item)
[Link](menu=menu)

# adding a label to the root window


lbl = Label(root, text = "Are you a Geek?")
[Link]()
166
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# adding Entry Field
txt = Entry(root, width=10)
[Link](column =1, row =0)

# function to display user text when


# button is clicked
def clicked():

res = "You wrote" + [Link]()


[Link](text = res)

# button widget with red color text inside


btn = Button(root, text = "Click me" ,
fg = "red", command=clicked)
# Set Button Grid
[Link](column=2, row=0)

# Execute Tkinter
[Link]()

Widgets

Tkinter provides various controls, such as buttons, labels and text boxes used in
a GUI application. These controls are commonly called Widgets. The list of
commonly used Widgets are mentioned below –

S
No. Widget Description

The Label widget is used to provide a single-line caption for


1 Label other widgets. It can also contain images.

The Button widget is used to display buttons in your


2 Button application.

The Entry widget is used to display a single-line text field for


3 Entry accepting values from a user.

The Menu widget is used to provide various commands to a


4 Menu user. These commands are contained inside Menubutton.

167
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

The Canvas widget is used to draw shapes, such as lines,


5 Canvas ovals, polygons and rectangles, in your application.

The Checkbutton widget is used to display a number of


options as checkboxes. The user can select multiple options
6 Checkbutton at a time.

The Frame widget is used as a container widget to organize


7 Frame other widgets.

The Listbox widget is used to provide a list of options to a


8 Listbox user.

The Menubutton widget is used to display menus in your


9 Menubutton application.

The Message widget is used to display multiline text fields


10 Message for accepting values from a user.

The Radiobutton widget is used to display a number of


options as radio buttons. The user can select only one option
11 Radiobutton at a time.

12 Scale The Scale widget is used to provide a slider widget.

The Scrollbar widget is used to add scrolling capability to


13 Scrollbar various widgets, such as list boxes.

14 Text The Text widget is used to display text in multiple lines.

The Toplevel widget is used to provide a separate window


15 Toplevel container.

A labelframe is a simple container widget. Its primary


purpose is to act as a spacer or container for complex window
16 LabelFrame layouts.

This module is used to display message boxes in your


17 tkMessageBox applications.

168
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

The Spinbox widget is a variant of the standard Tkinter Entry


widget, which can be used to select from a fixed number of
18 Spinbox values.

A PanedWindow is a container widget that may contain any


19 PanedWindow number of panes, arranged horizontally or vertically.

The Entry Widget


The Entry Widget is a Tkinter Widget used to Enter or display a single line of
text.
Syntax :
entry = [Link](parent, options)
Parameters:

1) Parent: The Parent window or frame in which the widget to display.


2) Options: The various options provided by the entry widget are:

 bg : The normal background color displayed behind the label and indicator.
 bd : The size of the border around the indicator. Default is 2 pixels.
 font : The font used for the text.
 fg : The color used to render the text.
 justify : If the text contains multiple lines, this option controls how the
text is justified: CENTER, LEFT, or RIGHT.
 relief : With the default value, relief=FLAT. You may set this option to
any of the other styles like : SUNKEN, RIGID, RAISED, GROOVE
 show : Normally, the characters that the user types appear in the entry. To
make a .password. entry that echoes each character as an asterisk, set
show=”*”.
 textvariable : In order to be able to retrieve the current text from your
entry widget, you must set this option to an instance of the StringVar class.
Methods: The various methods provided by the entry widget are:
 get() : Returns the entry’s current text as a string.
 delete() : Deletes characters from the widget
 insert ( index, ‘name’) : Inserts string ‘name’ before the character at the
given index.

Example:

# Program to make a simple

# login screen

169
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

import tkinter as tk

root=[Link]()

# setting the windows size

[Link]("600x400")

# declaring string variable

# for storing name and password

name_var=[Link]()

passw_var=[Link]()

# defining a function that will

# get the name and password and

# print them on the screen

def submit():

name=name_var.get()

password=passw_var.get()

170
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
print("The name is : " + name)

print("The password is : " + password)

name_var.set("")

passw_var.set("")

# creating a label for

# name using widget Label

name_label = [Link](root, text = 'Username', font=('calibre',10, 'bold'))

# creating a entry for input

# name using widget Entry

name_entry = [Link](root,textvariable = name_var,


font=('calibre',10,'normal'))

# creating a label for password

passw_label = [Link](root, text = 'Password', font = ('calibre',10,'bold'))

# creating a entry for password

passw_entry=[Link](root, textvariable = passw_var, font =


('calibre',10,'normal'), show = '*')

171
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# creating a button using the widget

# Button that will call the submit function

sub_btn=[Link](root,text = 'Submit', command = submit)

# placing the label and entry in

# the required position using grid

# method

name_label.grid(row=0,column=0)

name_entry.grid(row=0,column=1)

passw_label.grid(row=1,column=0)

passw_entry.grid(row=1,column=1)

sub_btn.grid(row=2,column=1)

# performing an infinite loop

# for the window to display

[Link]()

Widget is an element of Graphical User Interface (GUI) that displays/illustrates


information or gives a way for the user to interact with
the OS. In Tkinter , Widgets are objects ; instances of classes that represent
buttons, frames, and so on.
Each separate widget is a Python object. When creating a widget, you must pass
its parent as a parameter to the widget creation function. The only exception is
the “root” window, which is the top-level window that will contain everything
else and it does not have a parent.

Example :

172
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
from tkinter import *

# create root window

root = Tk()

# frame inside root window

frame = Frame(root)

# geometry method

[Link]()

# button inside frame which is

# inside root

button = Button(frame, text ='Geek')

[Link]()

# Tkinter event loop

[Link]()

Widget Classes

Tkinter supports the below mentioned core widgets –


Widgets Description
Label It is used to display text or image on the screen
Button It is used to add buttons to your application
It is used to draw pictures and others layouts like texts, graphics
Canvas etc.
ComboBox It contains a down arrow to select from list of available options
It displays a number of options to the user as toggle buttons from
CheckButton which user can select any number of options.

173
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
It is used to implement one-of-many selection as it allows only one
Radio Button option to be selected

174
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
Entry It is used to input single line text entry from user
Frame It is used as container to hold and organize the widgets
It works same as that of label and refers to multi-line and non-
Message editable text
It is used to provide a graphical slider which allows to select any
Scale value from that scale
Scrollbar It is used to scroll down the contents. It provides a slide controller.
SpinBox It is allows user to select from given set of values
It allows user to edit multiline text and format the way it has to be
Text displayed
Menu It is used to create all kinds of menu used by an application

Geometry Management

Creating a new widget doesn’t mean that it will appear on the screen. To
display it, we need to call a special method: either grid, pack(example above),
or place.
Method Description

pack() The Pack geometry manager packs widgets in rows or columns.

The Grid geometry manager puts the widgets in a 2-dimensional table.


The master widget is split into a number of rows and columns, and each “cell”
grid() in the resulting table can hold a widget.

The Place geometry manager is the simplest of the three general geometry
managers provided in Tkinter.
It allows you explicitly set the position and size of a window, either in
place() absolute terms, or relative to another window.

175
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

Connecting with Database


Verifying the MySQL dB Interface Installation

Connect to MySQL database remotely using python. For any application, it is very
important to store the database on a server for easy data access. It is quite complicated to
connect to the database remotely because every service provider doesn’t provide remote
access to the MySQL database. Here I am using python’s MySQLdb module for connecting
to our database which is at any server that provides remote access.
What is MYSQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python. It
implements the Python Database API v2.0 and is built on top of the MySQL C API.
Packages to Install
mysql-connector-python
mysql-python
If using anaconda
conda install -c anaconda mysql-python
conda install -c anaconda mysql-connector-python
else
pip install MySQL-python
pip install MySQL-python-connector
Import-Package
import MYSQLdb
In Python, We can use the following modules to communicate with MySQL.

1. MySQL Connector Python


2. PyMySQL
3. MySQLDB
4. MySqlClient
5. OurSQL

How to connect to a remote MySQL database using python?


Before we start you should know the basics of SQL. Now let us discuss the methods used in
this code:
 connect(): This method is used for creating a connection to our database it has
four arguments:
1. Server Name
2. Database User Name
3. Database Password
176
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
4. Database Name
 cursor(): This method creates a cursor object that is capable of executing SQL
queries on the database.

177
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
 execute(): This method is used for executing SQL queries on the database. It
takes a sql query( as string) as an argument.
 fetchone(): This method retrieves the next row of a query result set and returns a
single sequence, or None if no more rows are available.
 close() : This method close the database connection.

Example:
'''This code would not be run on Online IDE because required module are not
installed on IDE. Also this code requires a remote MySQL database connection
with valid Hostname, Dbusername Password and Dbname'''
# Module For Connecting To MySQL
database import MySQLdb

# Function for connecting to MySQL


database def mysqlconnect():
#Trying to
connect try:
db_connection= [Link]
("Hostname","dbusername","password","d
bname")
# If connection is not
successful except:
print("Can't connect to
database") return 0
# If Connection Is Successful
print("Connected")
# Making Cursor Object For Query
Execution
cursor=db_connection.cursor()
# Executing Query

178
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
[Link]("SELECT
CURDATE();") # Above Query
Gives Us The Current Date #
Fetching Data
m = [Link]()
# Printing Result Of
Above print("Today's
Date Is ",m[0]) #
Closing Database
Connection
db_connection.close()

179
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

# Function Call For Connecting To Our


Database mysqlconnect()
Example with Table Data Show:

# Python code to illustrate and


create a # table in database
import [Link] as
mysql # Open database
connection
db =
[Link](host="localhost",user="root",password="tiger",databas
e="python") cursor = [Link]()
# Drop table if it already exist using execute()
[Link]("DROP TABLE IF EXISTS
EMPLOYEE") # Create table as per
requirement
sql = "CREATE TABLE EMPLOYEE ( FNAME CHAR(20) NOT NULL,
LNAME CHAR(20), AGE INT )"
[Link](sql) #table
created # disconnect from
server [Link]()

Advantages and benefits of MySQL Connector Python: –

 MySQL Connector Python is written in pure Python, and it is self-sufficient to


execute database queries through Python.
 It is an official Oracle-supported driver to work with MySQL and Python.
 It is Python 3 compatible, actively maintained.

Link: [Link]
180
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

Python MySQL
Creating Database
After connecting to the MySQL server let’s see how to create a MySQL database using
Python. For this, we will first create a cursor() object and will then pass the SQL command
as a string to the execute() method. The SQL command to create a database is –
MySQL database server from Python, we need to import the [Link] interface.
Syntax:

CREATE DATABASE DATABASE_NAME


Example:

181
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# importing required libraries

import [Link]

dataBase = [Link](

host ="localhost",

user ="user",

passwd ="gfg"

# preparing a cursor object

cursorObject = [Link]()

# creating database

[Link]("CREATE DATABASE geeks4geeks")


we want to create a table in the database, then we need to connect to a database. Below is a
program to create a table in the geeks4geeks database which was created in the above
program.

# importing required

library import
[Link]

# connecting to the database [Link]() # creating table

dataBase =
[Link](

# preparing a cursor
object cursorObject =

182
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
calhost", user =
"user", passwd

h = "admin",

o database =

s "hvc" )

"
l
o

studentRecord = """CREATE TABLE STUDENT (


NAME VARCHAR(20) NOT
NULL, BRANCH
VARCHAR(50),
ROLL INT NOT NULL,

183
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
SECTION
VARCHAR(5),
AGE INT
# table )"""
created
[Link](student
Record) # disconnecting
from server [Link]()

MySQL Create Table


Creating, Inserting, Updating and Deleting the data from the databases. SQL
commands are case insensitive i.e CREATE and create signify the same command.
Installation
Follow the below-mentioned process for installing the dependencies for python
MySQL
1. Navigate to the python script directory using the command prompt.
2. Execute the command

pip install mysql-connector


Python Mysql Connector Module Methods

1. connect(): This function is used for establishing a connection with the MySQL
server. The following are the arguments that are used to initiate a connection:
1. user: User name associated with the MySQL server used to authenticate
the connection
2. password: Password associated with the user name for authentication
3. database: Data base in the MySQL for creating the Table
2. cursor(): Cursor is the workspace created in the system memory when the SQL
command is executed. This memory is temporary and the cursor connection is
bounded for the entire session/lifetime and the commands are executed
3. execute(): The execute function takes a SQL query as an argument and executes.
A query is an SQL command which is used to create, insert, retrieve, update, delete
etc.
1. The table is a collection of data organized in the form of rows and
columns. Table is present within a database.
2. Rows are also called tuples
3. Columns are called the attributes of the table
184
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
SQL command for Creating Table :

CREATE TABLE
(

185
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
column_name_1 column_Data_type,
column_name_2 column_Data_type,
:
:
column_name_n column_Data_type
);

SQL Data types


Data types are used for defining the type of data that will be stored in the cell of the
table.
Different Types of the Datatypes

1. Numeric
2. Character/String
3. Date/time.
4. Unicode Character/String
5. Binary
Apart from the above-mentioned datatypes, there are other miscellaneous data types
in MySQL that include datatypes of CLOB, BLOB, JSON, XML.
Consider the below-mentioned python code for creating a table of the “student”
which contains two Columns Name, Roll number in the database “college”
previously created.
# Python code for creating Table in the
Database # Host: It is the server name.
It will be "localhost" # if you are using
localhost database

import [Link] as
SQLC def CreateTable():

# Connecting To the Database in


Localhost DataBase = [Link](
host ="server

186
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
name", user ="user
name", password
="password",
database
="College"
)

187
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# Cursor to the
database Cursor =
[Link]()
# Query for Creating the table
# The student table contains two columns
Name and # Name of data type varchar
i.e to store string
# and Roll number of the integer data type.
TableName ="CREATE TABLE Student
(

Name VARCHAR(255),
Roll_no int
);"

[Link](TableName)
print("Student Table is Created in the
Database") return
# Calling CreateTable
function CreateTable()

MySQL – Insert into Table


You can insert one row or multiple rows at once. The connector code is required to
connect the commands to the particular database.
Connector query
# Enter the server name
in host # followed by
your user and
# password along with the
database # name provided
by you.
188
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

import [Link]

mydb =
[Link](
host = "localhost",
user = "username",
password =
"password",

189
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
database = "database_name"
)

mycursor = [Link]()

Now, the Insert into Query can be written as follows:


Example: Let’s suppose the record looks like this

sql = "INSERT INTO Student (Name, Roll_no)


VALUES (%s, %s)" val = ("Ram", "85")
[Link](sql, val)
[Link]()
print([Link], "details

inserted") # disconnecting from


server
[Link]()

To insert multiple values at once, executemany() method is used. This method iterates
through the sequence of parameters, passing the current parameter to the execute
method.

sql = "INSERT INTO Student (Name, Roll_no)

VALUES (%s, %s)" val = [("Akash", "98"),


("Neel", "23"),
("Rohan", "43"),
("Amit", "87"),
("Anil", "45"),
("Megha", "55"),
("Sita", "95")]
190
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

[Link](s
ql, val) [Link]()

print([Link], "details inserted")

191
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python

# disconnecting from server


[Link]()

 The cursor() is used in order to iterate through the rows.


 Without the command [Link]() the changes will not be saved.

MySQL – Select Query


# importing required
library import
[Link]

# connecting to the database


dataBase =
[Link]( host =
"localhost",
user = "user",
passwd =
"pswrd",
# preparing a cursor database =
object cursorObject = "geeks" )
[Link]() #
disconnecting from server
[Link]()

The above program illustrates the connection with the MySQL database geeks in
which host-name is localhost, the username is user and password is pswrd.
Select Query
After connecting with the database in MySQL we can select queries from the tables

192
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
in it.
Syntax:
 In order to select particular attribute columns from a table, we write the
attribute names.
SELECT attr1, attr2 FROM table_name
 In order to select all the attribute columns from a table, we use the asterisk
‘*’ symbol.
SELECT * FROM table_name
Below is a program to select a query from the table in the database.

193
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# importing required
library import
[Link]

# connecting to the database

dataBase =
[Link]( host =
"localhost",
user = "user",
passwd =
"pswrd",
# preparing a cursor database =
object cursorObject = "geeks" )
[Link]()
print("Displaying NAME and ROLL columns from the
STUDENT table:") # selecting query
query = "SELECT NAME, ROLL FROM STUDENT"
[Link](query)

myresult =
[Link]() for x
in myresult:
print(x)
# disconnecting from server
[Link]()
Example 2: Let us look at another example for selecting queries in a table.
# importing required

194
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
library import

[Link]

# connecting to the database


dataBase =
[Link]( host =
"localhost",
user = "user",
passwd =
"pswrd",
# preparing a cursor database =
object cursorObject = "geeks" )
[Link]()

195
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
print("Displaying NAME and ROLL columns from the
STUDENT table:") # selecting query
query = "SELECT * FROM STUDENT"
[Link](query)
myresult =
[Link]() for x
in myresult:
print(x)
# disconnecting from server
[Link]()

MySQL – Where Clause


Where clause is used in MySQL database to filter the data as per the condition
required. You can fetch, delete or update a particular set of data in MySQL database
by using where clause.
Syntax

SELECT column1, column2, …. columnN FROM [TABLE NAME] WHERE


[CONDITION];

The above syntax is used for displaying a certain set of data following the condition.
Example: Consider the following database named college and having a table name
as a student.
Schema of the database:

Where Clause In Python

Steps to use where clause in Python is:

1. First form a connection between MySQL and Python program. It is done


by importing [Link] package and using
[Link]() method, for passing the user name, password,
host (optional default: localhost) and, database (optional) as parameters to
it.
2. Now, create a cursor object on the connection object created above by
using cursor() method. A database cursor is a control structure that enables
traversal over the records in a database.
196
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
3. Then, execute the where clause statement by passing it through execute()
method.
import [Link]

197
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
#Establishing connection
conn =
[Link](user='your_userna
me', host='localhost',
password
='your_password',
database='College')

# Creating a cursor

object using # the


cursor() method
mycursor =
[Link](); #
SQL Query
sql = "select * from Student where
Roll_no >= 3;" # Executing query
[Link](sql)
myresult =
[Link]() for
x in myresult:
print(x)
# Closing the connection
[Link]()

Deleting query from tables

After connecting with the database in MySQL we can create tables in it and can
manipulate them.
DELETE FROM TABLE_NAME WHERE ATTRIBUTE_NAME =
ATTRIBUTE_VALUE

198
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
Example 1: Below is a program to delete a query from the table in the database.

# importing required library

import [Link]

# connecting to the database

dataBase = [Link](

host = "localhost",

user = "user",

199
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
passwd = "pswrd",

database = "geeks" )

# preparing a cursor object

cursorObject = [Link]()

# creating table

studentRecord = """CREATE TABLE STUDENT (

NAME VARCHAR(20) NOT NULL,

BRANCH VARCHAR(50),

ROLL INT NOT NULL,

SECTION VARCHAR(5),

AGE INT

)"""

# table created

[Link](studentRecord)

# inserting data into the table

query = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)


VALUES (% s, % s)"

attrValues = ("Rituraj Saha", "Information Technology", "1706256", "IT-3", "20")

[Link](query, attrValues)

attrValues = ("Ritam Barik", "Information Technology", "1706254", "IT-3", "21")

[Link](query, attrValues)

attrValues = ("Rishi Kumar", "Information Technology", "1706253", "IT-3", "21")

[Link](query, attrValues)
200
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# deleting query

query = "DELETE FROM STUDENT WHERE ROLL = 1706256"

[Link](query, attrValues)

[Link]()

# disconnecting from server

[Link]()
Example 2: Let us look at another example for queries in a table.
# importing required
library import
[Link]

# connecting to the database


dataBase =
[Link]( host =
"localhost",
user = "user",
passwd =
"pswrd",
database =
"geeks" )

# preparing a cursor object


cursorObject =
[Link]()

# drop table if it already exists


201
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
[Link]("DROP TABLE IF EXISTS PHONE_RECORD")

# creating table
phoneRecord = """CREATE TABLE PHONE_RECORD (
NAME VARCHAR(20) NOT
NULL, PHONE VARCHAR(10)
NOT NULL
)"""

# table created

202
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
[Link](phoneRecord)

# inserting data into the table


query = "INSERT INTO PHONE_RECORD (NAME, PHONE) VALUES (% s,
% s)"
attrValues = ("Rituraj Saha",
"9163089075")
[Link](query,
attrValues)
# deleting query
query = "DELETE FROM STUDENT WHERE NAME = 'Rituraj Saha'"
[Link](query)
[Link]()
# disconnecting from server
[Link]()

MySQL – Drop Table

Drop command affects the structure of the table and not data. It is used to delete an
already existing table. For cases where you are not sure if the table to be dropped
exists or not DROP TABLE IF EXISTS command is used. Both cases will be dealt
with in the following examples.
Syntax:
DROP TABLE tablename;
DROP TABLE IF EXISTS tablename;

Example 1: Program to demonstrate drop if exists. We will try to drop a table which
does not exist in the above database.
# Python program to demonstrate
# drop clause
import [Link]
203
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# Connecting to the Database
mydb = [Link](
host ='localhost',
database ='College',
user ='root',
)

204
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
cs = [Link]()
# drop clause
statement = "Drop Table if exists Employee"
# Uncommenting statement ="DROP TABLE employee"
# Will raise an error as the table employee
# does not exists
[Link](statement)
# Disconnecting from the database
[Link]()
Example 2: Program to drop table Geeks

# Python program to demonstrate


# drop clause

import [Link]

# Connecting to the Database


mydb = [Link](
host ='localhost',
database ='College',
user ='root',
)

cs = [Link]()

# drop clause
statement ="DROP TABLE Geeks"
[Link](statement)
# Disconnecting from the database
[Link]()
Example 2: Program to drop table Geeks
# Python program to demonstrate
205
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# drop clause
import [Link]
# Connecting to the Database
mydb = [Link](
host ='localhost',
database ='College',
user ='root',
)
cs = [Link]()
# drop clause
statement ="DROP TABLE Geeks"
[Link](statement)
# Disconnecting from the database
[Link]()

MySQL – Update Query

The update is used to change the existing values in a database. By using update a
specific value can be corrected or updated. It only affects the data and not the
structure of the table.
The basic advantage provided by this command is that it keeps the table accurate.
Syntax:

UPDATE tablename SET ="new value" WHERE ="old value";


The following programs will help you understand this better.

Example 1: Program to update the age of student named Rishi Kumar.


# Python program to demonstrate
# update clause
import [Link]
# Connecting to the Database
mydb = [Link](
host ='localhost',
database ='College',
user ='root',
206
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
)

207
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
cs = [Link]() #
drop clause
statement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'"
[Link](statement)
[Link]()
# Disconnecting from the database
[Link]()

Example 2: Program to correct the spelling of an Student named SK


# Python program to demonstrate #
update clause
import [Link]
# Connecting to the Database mydb =
[Link]( host
='localhost',
database ='College', user
='root',
)
cs = [Link]() #
drop clause
statement ="UPDATE STUDENT SET Name = 'S.K. Anirban' WHERE Name ='SK Anirban'"
[Link](statement)
[Link]()
# Disconnecting from the database
[Link]()

208

You might also like