Python PDF
Python PDF
1
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : 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
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
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
O. QUESTION ANSWER
Open source
2 Python is language.
6
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
Detail :-
In python programming user can input the data as well as get the output asa
result of data.
7
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : 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’)
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”
13
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : 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 −
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
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
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()
23
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
Detail :-
o Localscope of variable
o Globalscope of variable
o Example :-
def
my_function()
a=10
print(“a=” , a)
return
>>>my_func()
>>>print(a) # name error : name ‘a’ is not defined
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
My_var = 20
def my_function()
print(“a=” , a)
return
>>>print(a)
>>>my_function()
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 :-
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
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)
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 –
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.
29
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
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
– ‘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.
To write data from the file , we need to open it into write mode.
To write data into file , write() can be used.
32
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
33
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
Detail :-
Example :-
T1=(‘a’,’b’,’c’,’d’,’e’)
T2=(1,2,3,4,5)
T3=(17,25,”hi”,”how”,4)
34
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
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]
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
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
.
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
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)
Example :-
D1 = {‘name’ : ‘zara’ , ‘city’ : ‘rajkot’ , ‘age’ : 5)
Print (“D1[‘name’]:” , D1[‘name’]) o/p :- zara
Example :-
D1 = {‘name’ : ‘zara’ , ‘city’ : ‘rajkot’ , ‘age’ : 5)
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
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
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
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.
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.
48
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : 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.
When the interpreter identifies a statement that has an error, syntax errors occur.
Consider the following scenario:
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
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
Output:
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.
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.
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:-
Output:
53
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
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.
Code:-
# Python program to show how to use else clause with try and except clauses
Output:-
0 .25
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.
Code:-
54
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
# Python code to show the use of finally clause
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.
class ClassName:
# Statement
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.
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.
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
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.
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 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()
59
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
class Dog:
# Class
Variable
animal =
'dog'
# Instance
Variable
[Link] = breed
[Link] = color
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])
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.
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
class ClassName(ABC):
62
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
class Triangle(Polygon):
class Pentagon(Polygon):
class Hexagon(Polygon):
class Quadrilateral(Polygon):
# 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:
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:
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.
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:
class
Child(Parent)
: def
func2(self):
print("This function is in child
class.") # Driver's code
object = Child()
object.func1()
object.func2()
class Person(object):
# Constructor
def init (self, name, id):
[Link] = name
[Link] = id
69
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
class Emp(Person):
def Print(self):
print("Emp class called")
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
def parents(self):
# 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:
[Link] = grandfathername
# Intermediate class
class Father(Grandfather):
def init (self, fathername, grandfathername):
[Link] = fathername
grandfathername)
# Derived
class class
Son(Father):
[Link]) print("Father
# 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:
# Hierarchical inheritance
# Base class
class Parent:
def func1(self):
# Derived class1
class Child1(Parent):
def func2(self):
# Derivied class2
class Child2(Parent):
def func3(self):
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:
# 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.
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.
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:
[Link] = name
[Link] = rank
[Link] = points
# custom
function def
demofunc(self
):
print("I am
"+[Link]) print("I
# create 4 objects
st1 = Students("Steve", 1, 100)
77
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
created above [Link]()
[Link]
nc()
[Link]
nc()
[Link]
nc()
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.
# 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
79
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
# Python program to
# demonstrate protected members
# Protected
member self._a =
2
# Calling
constructor of #
Base class
Base. init (self)
print("Calling protected member of base
class: ", self._a)
obj1 =
Derived() obj2
= Base()
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]()
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
== 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
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.
87
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
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.
Sorting Techniques
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
5} First Pass:
The largest element is placed in its correct position, i.e., the end of the array.
Second Pass:
Third Pass:
91
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
def
bubbleSort(ar
r): n =
len(arr)
swapped = False
1):
92
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
element
if (swapped ==
False): break
bubbleSort(arr)
print("Sorted
array:") for i in
range(len(arr)):
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
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
for i in range(len(A)-1):
# unsorted array
min_idx = i
min_idx = j
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
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
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
100
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
Example :
def insertionSort(arr):
if n <= 1:
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
j = i-1
while j >= 0 and key < arr[j]: # Move elements greater than key one
position ahead
j -= 1
insertionSort(arr)
print(arr)
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
To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value.
Example
# Declare a dictionary
its key
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
104
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
'First'} dict['Age'] = 8; # update
Output
105
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
When the above code is executed, it produces the
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
in dict
dictionary print
"dict['Age']: ",
dict['Age']
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>
object is unsubscriptable
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()
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
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
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 −
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.
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()
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
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)
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))
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]
120
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : 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.
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
123
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
1 [Link]()
2 [Link]()
This method sets up and start TCP listener.
3 [Link]()
This passively accept TCP client connection, waiting until connection
arrives (blocking).
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
[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)
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.
We are going to use the following methods in this section to open a given url
using a Python program:
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.
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:
128
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
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.
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.
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.
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:
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
Example
import requests
url =
'[Link]
co' r = [Link](url,
allow_redirects=True)
Result
open('[Link]', 'wb').write([Link])
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.
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.
Stream Sockets
Datagram Sockets
Raw Sockets
Sequenced Packet Sockets
Stream sockets and datagram sockets are the two most popular choices.
Uses TCP (Transmission Control Protocol) Used UDP (User Datagram Protocol)
Distributed Systems are built using the concept of Client Service architectures.
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
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.
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.
Now let’s look at an example Python program on how to write a simple script to
setup a TCP/IP server and client.
import socket
# 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]()
import socket
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
Example Link:
[Link]
server-and-client/
[Link]
139
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
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
[Link](msgFromServer) #
UDPServerSocket = [Link](family=socket.AF_INET,
[Link]((localIP,
listening")
while(True):
bytesAddressPair =
[Link](bufferSize)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
Client:{}".format(message) clientIP =
"Client IP Address:{}".format(address)
print(clientMsg)
print(clientIP)
nd, address)
Output:
Address:("[Link]", 51696)
import socket
msgFromClient = "Hello
[Link](msgFromClient)
144
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
serverAddressPort = ("[Link]", 20001)
bufferSize = 1024
UDPClientSocket = [Link](family=socket.AF_INET,
socket
[Link](bytesToSend,
serverAddressPort) msgFromServer =
[Link](bufferSize) msg =
{}".format(msgFromServer[0]) print(msg)
Output:
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)
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)
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]()
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]()
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
#!/usr/bin/python
import smtplib
MIME-Version: 1.0
Content-type: text/html
<h1>This is headline.</h1>
"""
try:
smtpObj = [Link]('localhost')
except SMTPException:
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.
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]"
fo = open(filename, "rb")
filecontent = [Link]()
sender = 'webmaster@[Link]'
reciever = '[Link]@[Link]'
marker = "AUNIQUEMARKER"
body ="""
153
Vivekananda College of Computer Science and Mgt. Developed By : Dhara Sagparia
Subject : Python
"""
MIME-Version: 1.0
--%s
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
Content-Transfer-Encoding:base64
%s
--%s--
154
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
try:
smtpObj = [Link]('localhost')
[Link](sender, reciever,
except Exception:
155
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
GUI Programming
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 −
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.
163
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
from tkinter import *
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 *
# 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 *
# 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 *
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)
# 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 *
# 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
167
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
168
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
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:
# login screen
169
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
import tkinter as tk
root=[Link]()
[Link]("600x400")
name_var=[Link]()
passw_var=[Link]()
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)
name_var.set("")
passw_var.set("")
171
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# creating a button using the widget
# 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)
[Link]()
Example :
172
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
from tkinter import *
root = Tk()
frame = Frame(root)
# geometry method
[Link]()
# inside root
[Link]()
[Link]()
Widget Classes
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
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
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.
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
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
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:
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"
cursorObject = [Link]()
# creating database
# importing required
library import
[Link]
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
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]()
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
);
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():
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()
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]()
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.
[Link](s
ql, val) [Link]()
191
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
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]
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]
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]()
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:
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
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.
import [Link]
dataBase = [Link](
host = "localhost",
user = "user",
199
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
passwd = "pswrd",
database = "geeks" )
cursorObject = [Link]()
# creating table
BRANCH VARCHAR(50),
SECTION VARCHAR(5),
AGE INT
)"""
# table created
[Link](studentRecord)
[Link](query, attrValues)
[Link](query, attrValues)
[Link](query, attrValues)
200
Vivekananda College of Computer Science and Mgt. Developed By : Dhara
Sagparia
Subject : Python
# deleting query
[Link](query, attrValues)
[Link]()
[Link]()
Example 2: Let us look at another example for queries in a table.
# importing required
library import
[Link]
# 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)
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
import [Link]
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]()
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:
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]()
208