Python Final Material With Program Bca 6-2022
Python Final Material With Program Bca 6-2022
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
B.C.A. – SEMESTER -6
SUB :- CS – 33 :- PROGRAMMING IN PYTHON
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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
double quotes (“ “).
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 :-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Detail :-
In python programming user can input the data as well as get the output as a
result of data.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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’)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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’)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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>
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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’)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Detail :-
Pythondoesnotsupportcharactertype.
String is mostpopular datatype in python.
Stringis acollectionof 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”
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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 t wo or more
string Values.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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 statement will
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>
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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’]
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Nested Loop :-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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()
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Recursive Function :-
o Example :-
#Factorial using
recursion
def fact(n):
if(n==0):
return 1
else:
return n*fact(n-1)
#calling function
Print(fact(0))
Print(fact(5))
Nowtry to execute above function like afollowing:-
o Example:-
Print (fact(2000))
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Youwillgetfollowingerror at runtime:-
o Runtimeerror:- Maximumrecursion depthexceeded in comparison.
The above error is available because python stop calling recursive function after 1000
calls by default.
To change it you need to add following lines to starting of code.
Import Sys
Sys.setrecursionlimit(3000)
1 Word Question – Answer
SR.NO QUESTION ANSWER
1 When the function call itself recursion
again and againthen it is called .
2 function is called by external recursive
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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 – support.py]
Def print_func(x):
Print(“hello:”,x)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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 module is
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 Sys.path.
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.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Q-9What is file? Explain How to open , read , write and close the file –[file
handling]
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
– ‘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.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Detail :-
Example :-
T1=(‘a’,’b’,’c’,’d’,’e’)
T2=(1,2,3,4,5)
T3=(17,25,”hi”,”how”,4)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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
SR.NO QUESTION ANSWER
.
1 List is object in python. mutable
2 List can be represented by [ ] (square )
brackets.
3 To remove particular element from the list del
statement can be used.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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 { }.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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)
D1.clear() # remove all entries in dictionary Print(D1)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Detail:-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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 the function.
o Syntax :-
<function name> (parameters):
o Example :-
Sp()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Passing parameters to function :-
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
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
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)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Unlike tuple , the list is mutable it means we can change the value by
assigning new value directly.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
CHAPTER-2
OOP Using Python
Handling Exception
Exception as Control Flow
Assertion
Abstract Data Type
Class
Inheritance
Encapsulation
Information hiding
Search Algorithm
Sorting Algorithm
Hash table
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Detail :-
An exception is event that available during execution of a
program.
python have many built-in exception.
Python provide two very important features to handle an
unexpected error in your program.
1. Exception handling
2. Assertion
Exception handling
If you have some doubtful code that create exception at that time you
need to handle the exception.
Python provide try ,except else and finally keyword to store and solve
the error.
o Syntax :-
Try :
Do your operations here
Except Exception1:
If there is exception1 , than execute this block
Except Exception2:
If there is exception2 , then execute this block
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Else:
If there is no exception , than execute this block
o Example:-
Try :
F=open(“testfile”,”w”)
f.write(“hello friends”)
Except:
print (“error , can not find file”)
Else:
print(“written successfully”)
f.close()
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Detail :-
An Assertion is rule based checking that you can turn on and turn
off when you done with your testing of program.
Assertions are carried out by assert statement.
You have to place assert statement at the starting of your option to
check for valid input.
Assert Statement:
When interpreter encounter asserts statement , python execute the
given expression which is true.
But if the expression is false then python raised AssertionError
Exception.
o Syntax :-
Assert Expression [ , arguments ]
def no(i)
Assert (i>=0) , “no is less than
zero” Return (i)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
#calling function
Print (no(5))
Print (no(-5))
D etail :-
Abstract data type is a type or class for the object whose behavior is define d
by set of values.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
Abstract data type indicate “what’s operations are to be perform but not
how the operations will be implemented.
Abstractions is most powerful idea in python.
Abstract data type provide very important feature called “modularity”.
Classes are python representation for abstract data type.
Abstract data type include both data and operation at the same time.
There are following abstract data type available in python :
o Stack ADT
o Queue ADT
o List ADT
Stack ADT
A stack contains elements of same type arranged in sequential order.
Stack all the operatio ns are performed at top of the stack.
1. Stack():-
2. Push( item):-
Add new item to the t op of the stack it needs the item and
retu rn nothing.
3. Pop ()
Remove the top item from the stack. Return the item The stack
is modified.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
o Example:-
class Stack:
def init (self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.insert(0,item)
def peek(self):
return self.items[0]
def pop(self):
return self.items.pop(0)
def front(self):
return self.item[(self.items)]
def size(self):
return len(self.item s)
s = Stack()
s.push('hello')
s.push('true')
s.push('bca6b')
print(s.items)
print(s.size())
print(s.peek())
print(s.pop())
print(s.items)
Queue ADT:-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
1. Queue()
Create a new queue that is empty.
It need no parameters and return an empty queue.
2. Enqueue(items)
Add a new item to the rear of the queue.
It need the item and returns nothing.
3. Dequeue()
Remove the item from the front of the queue.
The queue is modified.
Example:-
class Queue:
def init (self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, it em):
self.items.insert(0,item)
return self.item[len(self.items)-1]
def size(self):
return len(self.it ems)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645
q=Queue()
q.enqueue(4)
q.enqueue('dog')
q.enqueue(True)
print(q.size())
List ADT:-
1. get()
It return eleme nt from the list at given position.
2 2.Insert()
Insert a new el ement of any position of list.
3. Remove ()
It remove first element from non empty list.
4. Replace()
Replace element of any position by other element.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot
Ph.No–(0281)2440478,2472590 - 360001
Ph.No–(0281)2471645
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Detail :-
Python does not have private keyword unlike oop language but
encapsulation can be take place.
A class variable that should not directly access must be prefixed with
(Double underscore).
o Example :-
Class
abc(object): Def init (self):
Self.a = 123
Self.b=123
Self c=123
Return
Obj = abc()
Print(obj.a)
Print(obj.b)
Print(obj.__c)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Detail :-
Inheritance is a feature of object oriented programming.
It is use to specify that one class will get all the features of other class.
It is a powerful feature that provide facility to create new class with few
modification to existing class.
The Main class from which child class inherit the property is called parent
class or base class.
The class that get all the features of parent class or base class is called Child
class or derived class.
The main purpose of inheritance is re-usability.
o Syntax :-
Class derivedclass (baseclass name):
<statement 1>
<statement 2>
……
……
<statement N>
o Example :-
Class animal :
Def eat(self):
Print (‘eating……’)
Class dog(animal):
Def break(self):
Print(‘barking……’)
#calling
d.dog()
d.eat()
d.bark()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Multiple inheritance:-
Multilevel inheritance:-
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Linear search:-
In this type of search , the sequential order must be follow by all the
elements.
Every list item is checked , if match is found then the particular list item
will be return.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Search_at =0
Search_Res=false
#match value with element
While (search_at < len(values) and search_res is false):
If (value[search_at]==search_for ):
search_res = true
else:
search_at=search_at + 1
return search_res
l = [64,34,25, 12,22,10,90]
print(linear_search(l,12))
print(linear_search(l,91))
o Output :-
True
False
Interpolationsearch
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
o Example :-
Def inter_search(values , x):
idx =0
idxn = (len(values)-1)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
o Output :-
Found 2 at index 0
Detail :-
Sorting is used to arrange data in particular format.
Sorting algorithm specify a way to arrange data in particular order.
Sorting support following implementation in python.
o Bubble Sort
o Merge Sort
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
o Selection Sort
o Shell Sort
o Intertion Sort
Bubble Sort:-
List[idx]= list[idx+1]
List[idx+1] = temp
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
List=[19,2,31,45,6,11,121,27]
Bubblesort(list)
Print(list)
o/p :- 2,6,11,19,27,31,45,121
Merge Sort:-
Merge sort first devide the array into equal parts then combine them
into sort manner.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
o Example :-
def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Selection Sort:-
In selection sort we can start sorting of elements by finding
minimum value.
Then we can move it to the sortest list.
We can repeat the process for each of the remaining element from
unsorted
List.
o Example :-
def selectisn_sort(input_list):
for idx in range (len(input_list)):
min_idx = idx
for j in range(idx+1 , len(input_list)):
if input_list[min_idx]<input_list[1]:
input_list[min_idx] = input_list[idx]
l=[19,2,31,45,30,11,121,27]
selection_sort(l)
print(l)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
D etail :-
Hash tables are type of data structure in which index value of data
isgenerated from hash table.
It makes data accessing faster because index value behave as a key.
In other words hash table store key-value pair but key will be generate d from
hash function.
In hashtable key-value pair become the index of array which store the value.
In python dictionary data type represent implementation of hash table.
The key of dictionary are known as hash table , which generates uniqu e
result for each unique value supplied to the hash function.
The order of data elements in a dictionary is not fixed.
Performing Operations on Hash tables using Dictionaries:
o Accessing Values
o Updating Values
o Deleting Element
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
o EXAMPLE:
OUTPUT: ‘001′
Using functions:
There are a number of built-in functions that can be used such as get(),
keys(), values(), etc.
EXAMPLE:
1
2 my_dict={'Dave' : '001' , 'Ava': '002' , 'Joe':'003'}
3 print(my_dict.keys())print(my_dict.values())
print(my_dict.get('Dave'))
OUTPUT:
Updating Values:
Dictionaries are mutable data type and therefore, you can update them as
and when required.
For example, if I want to change the ID of the employee named Dave from
‘001’ to ‘004’ and if I want to add another key-value pair to my dictionary,
Ican do as follows:
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
o EXAMPLE:
o EXAMPLE:
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot
Rajkot –
– 360001
360001 Rajkot - 360001
Rajkot - 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
CHAPTER-3
Plotting Using PyLab
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Detail :-
PyLab is a module inside MATPLOTLIB library.
MATPLOTLIB was developed by John . D. Hunter in 2003.
MATPLOTLIB has it’s roots in MATLAB which need to decide PyLab.
MATLAB support many built – in function for users to develop the code.
It become easy for MATLAB user who don’t want to use import statement.
PyLab having number of functions and classes for generating the drawings.
MATPLOTLIB in python having 1000 lines of code to create quality graphics.
MATPLOTLIB :-
Example :-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Detail :-
Mortgage is a simple calculation to find out or understand true cost of any
loan or interest.
To install mortgage you have to write following command at CMD prompt.
The above package can provide easy way to compare different mortgages.
It you are consider in mortgage loan , you should understand all the dtails
about how principal and interest will be calculated.
It will be also easy to find out monthly payment system for mortgage loan
which include following :
o HOA :- [ Home Owner Association fee ]
o PMI :- [Private Mortgage Insurance fee ]
o Home Owner Insurance
o Taxes
Here are some common tricks to find out mortgage loan calculation :-
1. Provide sales price of house.
2. Enter down payment.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
sr.
no
. is a simple calculation
1 to find Mortgage
out or understand true cost of any loan or
interest.
To install mortgage you have to write
Pip install mortgage
command.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Detail :-
One of the most common type of math based technical challenges are ones
that deal with Fibonacci sequence.
Each new term in the Fibonacci sequence is generated by adding the
previous two terms.
For example , starting with 1 and 2 ,the first 10 numbers in the sequence
would be :
o 1,2,3,5,8,13,21,34,55,89
One of the favourite challenge that deals with Fibonacci sequence is one that
asks for index value of some high number in the sequence.
It might be good idea to record the value returned by the first call , and then
look it up rather than compute it each time it is needed.This is called
“memorization”.
“Memorization” is key idea behind any dynamic programming.
Normally , easy way to go about doing something like would be to put all
the numbers in array and then cycle them with for loop.
First it requires two different functions , one function to generate Fibonacci
sequence and second function to cycle through all the numbers we have
generated.
Let’s see ,implementation of Fibonacci sequence by following figure.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
As above figure , look at tree of calls associated with the invocation fib(6).
Notice that we are computing same values over & over again.
oExample :-
Def
fib_seq(n)
A=0
B=1
If n==1:
Print(a)
Elif n==2:
Print(a,b)
Else:
Print(a,b,end=” “)
For I in range(n-2):
c=a+b
a=b
b=c
print(c , end=” “)
#calling
fib_seq(10)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Detail :-
In 0-1 knapsack , items can not be broken.
It means if 1 than cover all the elements and if 0 than leave all the
elements.
This is the main reason behind calling it as 0-1 knapsack.
In case of 0-1 knapsack , the value of xi can be either 0 or 1 where other
elements remains same.
Let’s consider the capacity of the knapsack is w=25 and the items as shown
in the following table.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
ITEM A B C D
PROFIT 24 18 18 10
WEIGHT 24 10 10 7
Here , profit per unit weight = (pi/wi).
First item A will be selected as it will contribute maximum profit among
all the elements.
After selecting item A , no more item will be selected.
Here , for this given set of items total profit is 24.
The optimal solution can be achieved by selecting items , B and C , where
total profit is 18+18=36.
In this example , the items are selected based on ratio (pi/wi).
Let’s us consider capacity of knapsack is w=60 and the items are as shown
in following table.
ITEM A B C
PRICE 100 280 120
WEIG 10 40 20
HT
RATIO 10 7 8
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
o CONQUER(Solve) :-
It include process of recursively solve the sub – problems.
This step receives a lot of smaller sub – problem to be solved.
Generally , at this level , the problems are considered as
“solved”.
o COMBINE (Merge):-
It combines the appropriate answers as well as results.
When smaller sub – problems are solved , this stage recursively
combines them until they found solution of original problem.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
o Example :-
def bsearch(list ,val):
list_size = len(list) -1
idx0 = 0
idxn = list_size #find middle most value
While idx0 < = idxn :
Midval = (idx0 _ idxn)/2
If list[midval] == val:
Return midval
#compare value – middle most value
If val > list[midval]:
Idx0 = midval +1
Else:
Idxn = midval – 1
If idx0 > idxn:
Return none
#calling
l1 = [55,44,2,4,9,8]
Print (bsearch(l1,4)
A classic example of divide & conquer is merge sort which demonstrated
below.
In merge sort , we divide array into two halves & sort the two halves
recursively & then finally merge the sored halves.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
CHAPTER-4
Network Programming and
GUI using Python
Network Programming:
Protocol, Sockets,
Knowing IP Address,
URL, Reading the Source Code of a Web Page,
Downloading a Web Page from Internet,
Downloading an Image from Internet,
A TCP/IP Server, A TCP/IP Client,
A UDP Server, A UDP Client,
File Server, File Client,
Two-Way Communication between Server and
Client,
Sending a Simple Mail.
GUI Programming:
Event-driven programming paradigm;
creating simple GUI;
buttons, labels, entry fields, dialogs;
widget attributes - sizes, fonts, colors ,layouts,nested
frames
.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Detail :-
What is Sockets?
To create a socket, you must use the socket.socket() function available in socket
module, which has the general syntax −
s = socket.socket (socket_family, socket_type,
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
This module is also used for performing wide range of operation like
arithmetic, comparison, etc to manipulate the IP addresses.
Detail :
Validating IP Addresses
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
# Import module
import ipaddress
Output :
175.198.42.211
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Output :
2001:db8:85a3:2bfe:70d:8a2e:370:7334
Operations on IP Address-
Various operations like arithmetic, comparison, type, etc can be performed on
the IP addresses with the help of ipaddress module. Some operations are listed
below:
# Import module
import ipaddress
# IPv4 address
print(type(ipaddress.ip_address(u'175.198.42.211')))
print(type(ipaddress.ip_address(u'5.0.0.1')))
# IPv6 address
print(type(ipaddress.ip_address(u'2001:0db8:85a3:2bfe:070d:8a2e:0
370:7334')))
print(type(ipaddress.ip_address(u'0000:f0f0::7b8a:ffff')))
1 Word Question – Answer
QUESTION ANSWER
Detail :-
The Internet Protocol is designed to implement a uniform system of
addresses on all of the Internet-connected computers everywhere and to
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
make it possible for packets to travel from one end of the Internet to the
other.
A program like the web browser should be able to connect to a host
anywhere without ever knowing which maze of network devices each
packet is traversing on its journey.
There are various categories of internet protocols.
These protocols are created to serve the needs of different types of data
communication between different computers in the internet.
Python has several modules to handle each of these communication
scenarios.
The methods and functions in these modules can do the simplest job of just
validating a URL or also the complex job of handling the cookies and
sessions.
In this chapter we will look at the most prominent python modules used for
internet protocols.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
1 _ is designed to Internet protocol
implement a uniform system of
addresses
2 Protocol can be used to HTTP
open HTTP url.
3 _ protocol helps to support FTP
different file operations
Detail :
URL stands for Uniform resource locator.
The requests module can help us build the URLS and manipulate the
URL value dynamically.
Any sub-directory of the URL can be fetched programmatically and then
some part of it can be substituted with new values to build new URLs.
What is urllib?
urllib is a Python module that can be used for opening URLs. It defines
functions and classes to help in URL actions.
With Python you can also access and retrieve data from the internet like
XML, HTML, JSON, etc. You can also use Python to work with this
data directly.
In this tutorial we are going to see how we can retrieve data from the web.
For example, here we used a guru99 video URL, and we are going to access
this video URL using Python as well as print HTML file of this URL.
Steps :-
Import urllib
Define your main function
Declare the variable webUrl
Then call the urlopen function on the URL lib library
The URL we are opening is guru99 tutorial on youtube
Next, we going to print the result code
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Result code is retrieved by calling the getcode
function on the webUrl variable we have created
We going to convert that to a string, so that it can be concatenated with
our string “result code”
This will be a regular HTTP code “200”, indicating http request is
processedsuccessfully
import requests
url = input('Webpage to grab source from: ')
html_output_name = input('Name for html file: ')
req = requests.get(url, 'html.parser')
Detail :-
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
implement them using classes.
Sockets can be configured to act as a server and listen for incoming messages,
or connect to other applications as a client. After both ends of a TCP/IP socket
are connected, communication is bi-directional.
Hence, we’ll keep our focus only on the workflow and example code of the
Python TCP server and client.
The sample contains the source code for a TCP server and client. For practice,
you can extend it to build a small chat system or a local attendance tracking
system.
TCPServer class – It follows the (Internet) TCP protocol that allows continuous
streams of data between the server and client.
The socketserver module has more classes to handle sockets.
Now let’s see the example of the Python TCP Server.
Python-TCP-Server.py
import socketserver
class
Handler_TCPServer(socketserver.BaseRequestHandler):
"""
The TCP Server class for demonstration.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
print("{}
sent:".format(self.client_address[0]))
print(self.data)
# just send back ACK for data arrival confirmation
self.request.sendall("ACK from TCP Server".encode())
# Init the TCP server object, bind it to the localhost on 9999 port
tcp_server = socketserver.TCPServer((HOST, PORT),
Handler_TCPServer)
In the next example code, you’ll see the Python TCP client module
code to communicate with the TCP server.
Python-TCP-Client.py
import socket
try:
# Establish connection to TCP server and exchange data
tcp_client.connect((host_ip, server_port))
tcp_client.sendall(data.encode())
# Read data from the TCP server and close the connection
received = tcp_client.recv(1024)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
finally:
tcp_client.close()
You can run both the server and client in separate Python instances. We
recommend that you use Python version 3 for executing the above
modules.
Next, you would first run the server module followed by the client. See
below the output of both the client and the server.
RESTART:
C:\Users\Techbeamers\AppData\Local\Programs\Python\Python35\Python-
TCP- Server.py
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Detail :-
UDP like TCP is a protocol for packet transfer from 1 host to another, but
has some important differences.
It means a UDP server just catches incoming packets from any and many
hosts without establishing a reliable pipe kind of connection.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
On the other hand, UDP messages must fit within a single packet
import socket
sock.bind((udp_host,udp_port))
while True:
print "Waiting for client..."
data,addr = sock.recvfrom(1024) #receive data from client
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Output of the above script is as follows. Keep it running and than fire up
the client.py module.
import socket
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
And here is what happened to our server after the client sends the request:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Here, you have placed a basic e-mail in message, using a
triple quote, taking care to format the headers correctly.
An e-mail requires a From, To, and Subject header, separated from the body
of the e-mail with a blank line.
QUESTION ANSWER
A simple file transfer server written in Python 3, that allows the user to
download files located on the server.
The server can handle and serve multiple clients at the same time and send
files in the same/child directories.
Usage
Run the server.py file, entering the port you wish for the server to
run on.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
Now, users can run the client.py file and connect to the server by
entering the IP address and port displayed on your server.
A user can enter the name of a file on the server (in the same folder as
the server.py) and download that file - the file will appear in the same
directory as the client.py file, named from_server+filename.
file transfer is based on server client model to use socket programming in
python3+.
Basic Set up Diagram:
File requirements:
We need server.py and this file should be present at server system. In
our case server.py should be at B_server system.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
File transfer is the process of copying or
moving a file from a computer to another over a network or
Internet connection.
On the other hand, the client will try to connect to the server and
send a file of any type.
Here is the code to send a file from a local server to a local client.
# server.py
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
print 'Got connection from', addr
data = conn.recv(1024)
print('Done sending')
conn.send('Thank you for connecting')
conn.close()
# client.py
s.connect((host, port))
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
s.send("Hello server!")
with open('received_file', 'wb') as f:
print 'file opened'
while True:
print('receiving data...')
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
Server listening....
Got connection from ('192.168.56.10', 62854)
('Server received', "'Hello server!'")
('Sent ', "'1 1234567890\\n)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
file opened
receiving data...
data=1 1234567890
2 1234567890
...
103 1234567890
104 123
receiving data...
data=4567890
105 1234567890
106 1234567890
...
299 1234567890
receiving data...
data=300 1234567890
Thank you for connecting
receiving data...
data=Successfully get the file
connection closed
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
So we will design both server and client model so that each can
communicate with them. The steps can be considered like this.
1. Python socket server program executes at first and wait for any request
2. Python socket client program will initiate the conversation at first.
3. Then server program will response accordingly to client requests.
4. Client program will terminate if user enters “bye” message.
A Simple Server
A socket object is then usedto call other functions to setup a socket server.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
A Simple Client
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
informations.com/about.htm")
print(html.read())
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
downloadFile(URL_from_file)
import urllib.request
...
url = 'http://example.com/'
response = urllib.request.urlopen(url)
data = response.read() # a `bytes` object
text = data.decode('utf-8') # a `str`; this step can't be used if data is binary
import urllib.request
...
# Download the file from `url` and save it locally under
`file_name`:
urllib.request.urlretrieve(url, file_name)
import urllib.request
...
# Download the file from `url`, save it in a temporary directory and get
the # path to it (e.g. '/tmp/tmpb48zma.txt') in the `file_name` variable:
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
method is a Python
1 module for fetching URLs. urllib.request
module provide a way to
2 download a file is over HTTP urllib
method can open the URL url,
3 which can be either a string or a Request urlopen()
object.
The standard Python library for accessing websites via your program is
urllib. It is also used by the requests module.
import urllib.request
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
It is important to note that on some systems and a lot of websites, the above
code will result in an error: HTTPError: HTTP Error 403: Forbidden.
This is because a lot of websites don’t appreciate random programs
accessing their data.
Some programs can attack the server by sending a large number of
requests. This prevents the server from functioning.
We say that an event is fired whenever the user does something – for
example, clicks on a button or types a keyboard shortcut.
Our application needs to monitor, or listen for, all the events that we
find interesting, and respond to them in some way if they occur.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
to build our interface – such as buttons, menus and various kinds of entry
fields and display areas.
We call these elements widgets. We are going to construct a tree of
widgets for our GUI – each widget will have a parent widget, all the way
up to the root window of our application.
For example, a button or a text field needs to be inside some kind of
containing window.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
class MyFirstGUI:
def init (self, master):
self.master = master
master.title("A simple GUI")
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
There are two main methods used which the user needs to remember
while creating the Python application with GUI.
import tkinter
m =
tkinter.Tk() '''
widgets are added here
m.mainloop()
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Widgets are the bread and butter of the Python GUI framework Tkinter.
They are the elements through which users interact with your program.
Each widget in Tkinter is defined by a class. Here are some of the
widgets available:
There are various controls, such as buttons, labels, scrollbars,
radiobuttons, and text boxes used in a GUI application.
These little
components or controls of Graphical User Interface (GUI) are
known as widgets in Tkinter.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
There are also simple dialogues, asking the user to enter string, integers or
float numbers.
Let's look at a typical GUI Session with Dialogues and Message boxes.
There might be a button starting the dialogue, like the "quit" button in the
following window:
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Let's assume that we want to warn users that the "quit" functionality is
not yet implemented. In this case we can use the warning message to
inform the user, if he or she pushes the "yes" button:
Let's go back to our first Dialogue with the "quit" and "answer" buttons. If the
"Answer" functionality is not implemented, it might be useful to use the following
error message box:
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
def answer():
mb.showerror("Answer", "Sorry, no answer
available") def callback():
if mb.askyesno('Verify', 'Really quit?'):
mb.showwarning('Yes', 'Not yet
implemented')
else:
mb.showinfo('No', 'Quit has been cancelled')
tk.Button(text='Quit', command=callback).pack(fill=tk.X)
tk.Button(text='Answer', command=answer).pack(fill=tk.X)
tk.mainloop()
Message Boxes
The message dialogues are provided by the 'messagebox' submodule
oftkinter.
'messagebox' consists of the following functions, which correspond
to dialog windows:
askokcancel(title=None, message=None, **options)
Ask if operation should proceed; return true if the answer is ok
askquestion(title=None, message=None,
**options) Ask a question
askretrycancel(title=None, message=None, **options)
Ask if operation should be retried; return true if the answer is yes
askyesno(title=None, message=None, **options) Ask
a question; return true if the answer is yes
askyesnocancel(title=None, message=None, **options)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
import tkinter as tk
from tkinter import filedialog as fd
def callback():
name= fd.askopenfilename()
print(name)
errmsg = 'Error!'
tk.Button(text='File Open',
tk.mainloop()
The code above creates a window with a single button with the text
"FileOpen".
If the button is pushed, the following window appears:
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
The above example was created using a gnome desktop under Linux. If
we start the same program under Windows 7, it looks like this:
Choosing a Colour
There are applications where the user should have the possibility to select
a colour.
Tkinter provides a pop-up menu to choose a colour. To this purpose
we have to import the 'tkinter.colorchooser' module and have to use
the method askColor:
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
If the user clicks "Cancel" the method returns the tuple (None, None).
import tkinter as tk
from tkinter.colorchooser import askcolor
def callback():
result = askcolor(color="#6A9662",
title = "Bernd's Colour Chooser")
print(result)
root = tk.Tk()
text='Choose Color',
fg="darkgreen",
command=callback).pack(side=tk.LEFT, padx=10)
tk.Button(text='Quit',
command=root.quit,
fg="red").pack(side=tk.LEFT, padx=10)
tk.mainloop()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
The look and feel depends on the operating system (e.g. Linux
or Windows) and the chosen GUI (GNOME, KDE and so on).
The following windows appear, if you use Gnome:
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Using the same script under Windows 7 gives us the following result.
and height.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
o Tkinter fonts
Tkinter has a tkinter.font module for working with fonts. It has some
built- in fonts such as TkTooltipFont, TkDefaultFont, or TkTextFont.
The font is set with the font attribute.
o Tkinter cursors
The cursor is a small icon that shows where the mouse pointer is
located. The cursor in Tkinter is set with the cursor attribute.
In the example, we have four labels. Different cursors are used for
eachof the labels.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Absolute positioning
absolute.py
#!/usr/bin/env
python3
"""
ZetCode Tkinter tutorial
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
class Example(Frame):
def init
(self):
super(). init ()
self.initUI()
def initUI(self):
self.master.title("Absolute
positioning") self.pack(fill=BOTH,
expand=1)
Style().configure("TFrame", background="#333")
bard = Image.open("bardejov.jpg")
bardejov=
ImageTk.PhotoImage(bard)
label1=Label(self, image=bardejov)
We use Image and ImageTk from the Python Imaging Library (PIL) module.
style = Style()
style.configure("TFrame", background="#333")
bard = Image.open("bardejov.jpg")
bardejov = ImageTk.PhotoImage(bard)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
label1.image = bardejov
We must keep the reference to the image to prevent image from being
garbage collected.
label1.place(x=20, y=20)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
There are number of options which are used to change the format of
this widget.
Number of options can be passed as parameters separated by
commas. Some of them are listed below.
Title: To set the title of the widget.
activebackground: to set the background color when widget
is under the cursor.
activeforeground: to set the foreground color when widget
is under the cursor.
bg: to set he normal
backgrouSteganographyBreak.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the widget.
master = Tk()
var1 = IntVar()
Checkbutton(master, text='male', variable=var1).grid(row=0,
sticky=W)
var2 = IntVar() Checkbutton(master, text='female',
variable=var2).grid(row=1, sticky=W)
mainloop()
Output :-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Entry:It is used to input the single line text entry from the user..
For multi-line text input, Text widget is used.
Label(master,text='Last Name').grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output :-
Frame: It acts as a container to hold the widgets. It is used for grouping and
organizing the widgets.
The general syntax is:
w = Frame(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of
the widget.
import * root =
Tk()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
root.mainloop()
Output:-
Label: It refers to the display box where you can put any text or image which
canbe updated any time as per the code.
The general syntax is:
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
w=Label(master, option=value)
from tkinter
import * root =
Tk()
w = Label(root, text='GeeksForGeeks.org!')
w.pack()
root.mainloop()
Output :-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Listbox: It offers a list to the user from which the user can accept any number
ofoptions.
The general syntax is:
w = Listbox(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of
the widget.
Number of options can be passed as parameters separated by
commas. Some of them are listed below.
from tkinter
import * top =
Tk()
Lb =
Listbox(top)
Lb.insert(1,
'Python')
Lb.insert(2,
'Java')
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Lb.insert(3, 'C++')
Lb.insert(4, 'Any
other') Lb.pack()
top.mainloop()
Output :-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
CHAPTER – 5
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
MySQL
Oracle Database
SQL server
Sybase
Informix
IBM db2
NO SQL
Among all these databases, MySQL is one of the easiest databases to work with.
Let me walk you through about this in detail.
What is MySQLdb?
Detail :-
It is very simple to connect Python with the database.
Refer the below image which illustrates a Python connection with the
database where how a connection request is sent to MySQL connector
Python, gets accepted from the database and cursor is executed with result
data.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
MySQL server
All available connectors
MySQL Workbench
MySQL Notifier
Tools for Excel and Microsoft Visual Studio
MySQL Sample Databases
MySQL Documentation
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Detail :-
Install mysql.connector
https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7
b8660d09f91d8d5411298bcacbd309f96/mysql-connector-python-8.0.13.tar.gz
Open the terminal (CMD for windows) and change the present
workingdirectory to the source code directory.
$ cd mysql-connector-python-8.0.13/
1. Run the file named setup.py with python (python3 in case you
have also installed python 2) with the parameter build.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
install
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Detail :-
Database Connection
In this section ,we will discuss the steps to connect the python application
tothe database.
There are the following steps to connect a python application to our database.
Connection-Object= mysql.connector.connect(host =
<host- name> , user = <username> , passwd =
<password> )
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user =
"root",pass wd = "google")
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output:
<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>
Here, we must notice that we can specify the database name in the
connect() method if we want to connect to a specific database.
<my_cur> = conn.cursor()
Example :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google", database = "mydb")
4. #printing the connection object
5. print(myconn)6.
6. creating the cursor
object
7. cur = myconn.cursor()
8. print(cur)
Output :-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Detail :-
In this section , we will create the new database PythonDB.
We can get the list of all the databases by using the following MySQL query.
> show database
Example :-
1.import
mysql.connector2.
3. #Create the connection object
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
7. try:
8. dbs = cur.execute("show databases")
9. except:
10. myconn.rollback()
11.for x in cur:
12. print(x)
13.myconn.close()
('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mysql',)
('performance_schema',)
('testDB',)
The new database can be created by using the following SQL query.
name> Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #creating a new database
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
11. except:
12.
myconn.rollback
()13.for x in cur:
14. print(x)
15.myconn.close()
Output :-
('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)
('information_schem
a',) ('javatpoint',)
('javatpoint1',)
('mydb',)
('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)
1 Word Question – Answer
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Detail :-
Creating the table
primary key, salary float not null, Dept_Id int not null)
Example :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Creating a table with name Employee having four columns i.e.,
name, id, s alary, and department id
8. dbs = cur.execute("create table Employee(name varchar(20) not null, id int
(20) not null primary key, salary float not null, Dept_id int not null)")
9. except:
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
10. myconn.rollback()
11. Myconn.close()
Now, we may check that the table Employee is present in the database.
Alter
Table
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Detail :-
Insert Operation - Adding a record to the table
The INSERT INTO statement is used to add a record to the table. In python, we can
mention the format specifier (%s) in place of values
We provide the actual values in the form of tuple in the execute() method
of the cursor.
Example :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (
%s, %s, %s, %s, %s)"
7. #The row values are provided in the form of tuple8.
8. val = ("John", 110, 25000.00, 201, "Newyork")
9. try:
10. #inserting the values into the table
11. cur.execute(sql,val)
12. #commit the transaction
13. myconn.commi
t() 14. except:
15. myconn.rollback()
16.print(cur.rowcount,"record
inserted!") 17.myconn.close()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output :-
1 record inserted!
We can also insert multiple rows at once using the python script.
The multiple rows are mentioned as the list of various tuples.
Each element of the list is treated as one particular row, whereas each
element of the tuple is treated as one particular column value
(attribute).
Example :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output :-
3 records inserted!
Row ID
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (
%s, %s, %s, %s, %s)"
7. val = ("Mike",105,28000,202,"Guyana")
8. try:
9. #inserting the values into the table
10. cur.execute(sql,val)
11. #commit the transaction
12. myconn.commit()
13. #getting rowid
14. print(cur.rowcount,"recordinserted! id:",cur.lastrowid)
15. except:
16.myconn.rollback
()17.myconn.close()
Output :-
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Detail :-
Read Operation
You can use either fetchone() method to fetch single record or fetchall()
method to fetech multiple values from a database table.
fetchone() − It fetches the next row of a query result set. A result set is
anobject that is returned when a cursor object is used to query a table.
fetchall() − It fetches all the rows in a result set. If some rows have
already been extracted from the result set, then it retrieves the remaining
rows from the result set.
rowcount − This is a read-only attribute and returns the number of rows
that were affected by an execute() method
The SELECT statement is used to read the values from the databases.
We can restrict the output of a select query by using various clause in
SQL like where, limit, etc.
Python provides the fetchall() method returns the data stored inside the
tablein the form of rows. We can iterate the result to get the individual
rows.
In this section of the tutorial, we will extract the data from the
database by using the python script. We will also format the
output to print it on the console.
Example :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",
passwd= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select * from Employee")
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
In the following example, we will read the name, id, and salary
from the Employee table and print it on the console.
Example :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",
4. passwd= "google",database = "PythonDB")
5. #creating the cursor object
6. cur = myconn.cursor()
7. try:
8. #Reading the Employee data
9. cur.execute("select name, id, salary from Employee")
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
9.
10. #fetching the rows from the cursor object
11. result = cur.fetchall()
12. #printing the result
13. for x in result:
14. print(x);
15.except:
16.
myconn.rollbac
k()17.myconn.close()
Output :-
('John', 101, 25000.0)
('John', 102, 25000.0)
('David', 103, 25000.0)
('Nick', 104, 90000.0)
('Mike', 105, 28000.0)
The fetchone() method is used to fetch only one row from the table.
The fetchone() method returns the next row of the result-set.
Example :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee")
9. #fetching the first row from the cursor object
10. result = cur.fetchone()
11. #printing the result
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
12. print(result)
13.except:
14. myconn.rollback()
15. myconn.close()
Output :-
'John', 101, 25000.0)
We can format the result by iterating over the result produced by the
fetchall() or fetchone() method of cursor object since the result exists as
the tuple object which is not readable.
Example :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee")
9. #fetching the rows from the cursor object
10. result = cur.fetchall()
11. print("Name id Salary");
12. for row in result:
13. print("%s %d
%d"%(row[0],row[1],row[2])) 14.except:
15. myconn.rollback()
16. myconn.close()
Output :-
Name Id Salary
John 101 25000
John 102 25000
David103 25000
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee where name like 'J%'")
Name id
Salary John
101
25000
John 102 25000
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Example :-
16.myconn.close()
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output:
Name id
Salary
David 103
25000
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000
Order by DESC
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee order by name desc")
9. #fetching the rows from the cursor object
10. result = cur.fetchall()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output:
Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000
Detail :-
Update Operation
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
The UPDATE-SET statement is used to update any column inside the table.
The following SQL query is used to update a column.
UPDATE Operation on any database means to update one or more
records, which are already available in the database.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Detail :-
Delete Operation
The following SQL query is used to delete the employee detail whose id
is 110from the table.
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Deleting the student details whose rollno is 4
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
10.except:
11.myconn.rollback
()12.myconn.close()
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
Hello
World
Hello
World
Hello World
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
12
12.56
Hello
True
Output
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Integer : 12
Float : 12.56
String : Hello
Boolean : True
# global variable
a = 100
# main code
if __name__ == '__main__':
# local variable of main
c = 200
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
a: 100
c: 200
a: 100 b: 200
a: 110
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
# input a number
num = int(input("Input a value: "))
Output
Input a value: 10
num = 10
# input a number
num = float(input("Input a value: "))
Output
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
num1 = 10
num2 = 20
# finding sum
sum = num1 + num2
# printing sum
print("sum of ", num1, " and ", num2, " is = ", sum)
Output
sum of 10 and 20 is = 30
Enter first number: 100
Enter second number: 200
sum of 100 and 200 is = 300
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
First run:
Enter the principle amount : 10000
Enter the rate of interest : 3.5
Enter the time in the years: 1
Principle amount: 10000.0
Interest rate : 3.5
Time in years : 1.0
Simple Interest : 350.0
Second run:
Enter the principle amount : 250000
Enter the rate of interest : 36
Enter the time in the years: 1
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
RUN 1:
Enter the value of year: 2020
The given year is a leap year.
RUN 2:
Enter the value of year: 2000
The given year is a leap year.
if (num % 2 == 0):
print(num," is EVEN")
else:
print(num," is ODD")
# main code
CheckEvenOdd(11)
CheckEvenOdd(22)
CheckEvenOdd(33)
CheckEvenOdd(44)
Output
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
11 is ODD
22 is EVEN
33 is ODD
44 is EVEN
# input age
age = int(input("Enter Age : "))
Output
Enter Age : 19
You are Eligible for Vote.
# input choice
ch=int(input("Enter Choice(1-4): "))
if ch==1:
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
a=int(input("Enter A:"))
b=int(input("Enter B:"))
c=a+b
print("Sum = ",c)
elif ch==2:
a=int(input("Enter A:"))
b=int(input("Enter B:"))
c=a-b
print("Difference = ",c)
elif ch==3:
a=int(input("Enter A:"))
b=int(input("Enter B:"))
c=a*b
print("Product = ",c)
elif ch==4:
a=int(input("Enter A:"))
b=int(input("Enter B:"))
c=a/b
print("Quotient = ",c)
else:
print("Invalid Choice")
Output
Calculator
1.Add
2.Substract
3.Multiply
4.Divide
Enter Choice(1-4): 3
Enter A:10
Enter B:20
Product = 200
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
print("Type 1")
for i in range(10): # start=0 , end=10,step=1
print(i,end=" ")
print("\nType 2")
for i in range(1,11): # start=1 , end=10,step=1
print(i,end=" ")
print("\nType 3")
for i in range(1,11,3): # start=1 , end=10,step=3
print(i,end=" ")
print("\nType 4")
for i in range(10,0,-1): # start=10 , end=0,step=-1
print(i,end=" ")
Output
Type 1
0 1 2 3 4 5 6 7 8 9
Type 2
1 2 3 4 5 6 7 8 9 10
Type 3
1 4 7 10
Type 4
10 9 8 7 6 5 4 3 2 1
n=int(input("Enter N: "))
for i in range(1,n+1):
print(i)
Output
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Enter N: 5
1
2
3
4
5
n=int(input("Enter N: "))
for i in range(1,11):
print(n,"x",i,"=",i*n)
Output
Enter N: 2
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
n=int(input("Enter N: "))
s=0
for i in range(1,n+1):
s=s+i
print("Sum = ",s)
Output
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Enter N: 10
Sum = 55
4. Print factorial of n
n=int(input("Enter N: "))
f=1
for i in range(n,0,-1):
f=f*i
print("Factorial = ",f)
Output
Enter N: 4
Factorial = 24
Output
<class 'list'>
apple
mango
guava
grapes
pinapple
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Example 1:
i=1
While (i<=5):
Print(i)
i=i+1
Output
1
2
3
4
5
Example 1:
for i in range(1,11):
if(i==6):
break
print(i)
Output
1
2
3
4
5
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
H
e
l
l
o
Example 1:
for i in range(1,11):
if(i==6):
continue
print(i)
Output
1
2
3
4
5
7
8
9
10
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
H
e
l
l
o
w
o
r
l
d
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
# main code
if __name__ == '__main__':
#input the number
x = int(input("Enter an integer number: "))
print("Factorial of ", x, " is = ", factorial(x))
Output
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
# infinite loop
while True:
try:
input() #For ENTER
start_time = time.time()
print("Stopwatch started...")
except KeyboardInterrupt:
print("Stopwatch stopped...")
end_time = time.time()
print("The total time:", round(end_time - start_time, 2),"seconds")
break # breaking the loop
Output
Stopwatch started...
^CStopwatch stopped...
The total time: 15.81 seconds
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
# printing list1
print "List element are: ", list1
# printing list2
print "List elements are: ", list2
#printing elements of list2 by index
print "Element @ 0 index:",list2 [0]
print "Element @ 1 index:",list2 [1]
print "Element @ 2 index:",list2 [2]
print "Element @ 3 index:",list2 [3]
#printing list3
print "List elements are: ", list3
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
7.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
8. except Exception as e:
9. print(e)
10. # trying to access elements through the index of floating data type
11. try:
12. print(tuple_[1.0])
13. except Exception as e:
14. print(e)
15.
16. # Creating a nested tuple
17. nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
18. # Accessing the index of a nested tuple
19. print(nested_tuple[0][3])
20. print(nested_tuple[1][1])
Output
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
1
6
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
# Main code
# declare string and assign value
str = "Hello World How are you?"
Output
Hello ( 5 )
World ( 5 )
How ( 3 )
are ( 3 )
you? ( 4 )
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
# declare count
count = 0
# print count
print "Total vowels are: ", count
Output
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output:
good
morning
Example - 1
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output:
Def print_func(x):
Print(“hello:”,x)
Return
Output:
Hello: zara
1. # Python code to catch an exception and handle it using try and except codeblocks
2. a = ["Python", "Exceptions", "try and except"]
3. try:
4. #looping through the elements of the array a, choosing a range that goes
beyond the length of the array
5. for i in range( 4 ):
6. print( "The index and element from the array is", i, a[i] )
7. #if an error occurs in the try block, then except block will be executed by the
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Python interpreter
8. except:
9. print ("Index out of range")
Output:
Output:
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
class Message(object):
def __init__(self):
# assign none to variable
self.msg = None
def assignValue(self):
# assign any value
self.msg = "Hello World"
def printValue(self):
# print the value
print "msg = ",self.msg
# Main code
# creating object of the class
# Here, M is object nae
M = Message()
# print value
print "value after init. the object..."
M.printValue();
# assign value
M.assignValue()
# print value
print "value after assignValue ()...."
M.printValue();
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
def printValues(self):
print "Name: ",self.name
print "Age : ",self.age
# Main code
# declare object
p = person()
# print
p.printValues();
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output
Name: XYZ
Age : 0
Name: Amit
Age : 21
emp.setData(1,'pankaj','male','delhi',55000)
emp.showData()
if __name__=="__main__":
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
main()
Output
Id : 1
Name : pankaj
Gender : male
City : delhi
Salary : 55000
#Abstract Class
class Vehicle:
def start(self,name=""):
print(name,"is Started")
def acclerate(self,name=""):
pass
def park(self,name=""):
pass
def stop(self,name=""):
print(name,"is stopped")
class Bike(Vehicle):
def acclerate(self, name=""):
print(name,"is accelrating @ 60kmph")
def park(self, name=""):
print(name,"is parked at two wheeler parking")
class Car(Vehicle):
def acclerate(self, name=""):
print(name,"is accelrating @ 90kmph")
def park(self, name=""):
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
def main():
print("Bike Object")
b=Bike()
b.start("Bike")
b.acclerate("Bike")
b.park("Bike")
b.stop("Bike")
print("\nCar Object")
c = Car()
c.start("Car")
c.acclerate("Car")
c.park("Car")
c.stop("Car")
if __name__=="__main__":main()
Output
Bike Object
Bike is Started
Bike is accelrating @ 60kmph
Bike is parked at two wheeler parking
Bike is stopped
Car Object
Car is Started
Car is accelrating @ 90kmph
Car is parked at four wheeler parking
Car is stopped
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
class Details:
def __init__(self):
self.__id="<No Id>"
self.__name="<No Name>"
self.__gender="<No Gender>"
def setData(self,id,name,gender):
self.__id=id
self.__name=name
self.__gender=gender
def showData(self):
print("Id\t\t:",self.__id)
print("Name\t\t:", self.__name)
print("Gender\t\t:", self.__gender)
if __name__=="__main__":
main()
Output
Id : 101
Name : Prem Sharma
Gender : Male
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
class Details:
def __init__(self):
self.__id=0
self.__name=""
self.__gender=""
def setDetails(self):
self.__id=int(input("Enter Id: "))
self.__name=input("Enter Name: ")
self.__gender=input("Enter gender: ")
def showDetails(self):
print("Id: ",self.__id)
print("Name: ",self.__name)
print("Gender: ",self.__gender)
class Employee(Details):
def __init__(self):
self.__company=""
self.__desig=""
def setEmployee(self):
self.setDetails()
self.__company=input("Enter Compmany Name: ")
self.__desig=input("Enter Designation: ")
def showEmployee(self):
self.showDetails()
print("Company: ",self.__company)
print("Designation: ",self.__desig)
class Doctor(Details):
def __init__(self):
self.__hospital=""
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
self.__dept=""
def setDoctor(self):
self.setDetails()
self.__hospital=input("Enter Hospital Name: ")
self.__dept=input("Enter Department: ")
def showDoctor(self):
self.showDetails()
print("Hospital: ",self.__hospital)
print("Department",self.__dept)
def main():
print("Employee Object: ")
e = Employee()
e.setEmployee()
e.showEmployee()
print("\nDoctor Object: ")
d=Doctor()
d.setDoctor()
d.showDoctor()
if __name__=="__main__":
main()
Output
Employee Object:
Enter Id: 101
Enter Name: Prem Sharma
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
class Personel:
def __init__(self):
self.__id=0
self.__name=""
self.__gender=""
def setPersonel(self):
self.__id=int(input("Enter Id: "))
self.__name = input("Enter Name: ")
self.__gender = input("Enter Gender: ")
def showPersonel(self):
print("Id: ",self.__id)
print("Name: ",self.__name)
print("Gender: ",self.__gender)
class Educational:
def __init__(self):
self.__stream=""
self.__year=""
def setEducational(self):
self.__stream=input("Enter Stream: ")
self.__year = input("Enter Year: ")
def showEducational(self):
print("Stream: ",self.__stream)
print("Year: ",self.__year)
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
class Student(Personel,Educational):
def __init__(self):
self.__address = ""
self.__contact = ""
def setStudent(self):
self.setPersonel()
self.__address = input("Enter Address: ")
self.__contact = input("Enter Contact: ")
self.setEducational()
def showStudent(self):
self.showPersonel()
print("Address: ",self.__address)
print("Contact: ",self.__contact)
self.showEducational()
def main():
s=Student()
s.setStudent()
s.showStudent()
if __name__=="__main__":main()
Output
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
# main code
if __name__=='__main__':
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
num = 6
found = binary_search(l, num)
if found[0]:
print('Number %d found at position %d'%(num, found[1]+1))
else:
print('Number %d not found'%num)
Output
6. if(list1[j]>list1[j+1]):
7. temp = list1[j]
8. list1[j] = list1[j+1]
9. list1[j+1] = temp
10. return list1
11.
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output:
file2.close()
+51426
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
print("file1 content...")
print(str1)
print("file2 content...")
print(str2)
Output
file1 content...
This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
Output
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
x = [1,2,3,4,5,6,7,8,9,10]
y = [3,9,6,12,5,1,10,5,4,9]
plt.plot(x,y, label='lineplots', color='b')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.legend()
plt.show()
Output
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
x = [2,4,6,8,10]
y=[3,9,11,2,6]
plt.bar(x,y,label ='Bars')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Bar Graph1')
plt.legend()
plt.show()
Output
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
x2=[1,3,5,7,9]
y2=[6,4,7,8,3]
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Bar Graph2')
plt.legend()
plt.show()
Output
y2=[6,4,7,8,3,4]
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
xvalues = np.arange(N)
plt.xlabel('Teams')
plt.ylabel('Scores')
plt.title('Stacked Bar Graphs')
plt.legend()
Output
x = [1,2,3,4,5,6,7,8,9,10]
y = [3,9,6,12,5,1,10,5,4,9]
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot')
plt.legend()
plt.show()
Output
days = [1, 2, 3, 4, 5]
slices = [7,2,2,13]
cols = ['r','y','g','b']
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
plt.pie(slices,
labels=my_labels,
colors = cols,
startangle=45,
explode =(0,0.2,0,0),
shadow = True,
autopct = '%1.1f%%')
plt.axis('equal')
plt.legend(loc=3)
plt.show()
Output
days=[1,2,3,4,5]
sleeping = [7,8,6,11,7]
eating = [2,3,4,3,2]
working = [7,8,7,2,2]
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
playing = [8,5,7,8,13]
plt.xlabel('Days')
plt.ylabel('Hours')
plt.title('Stack Plot1')
plt.xticks(days, ('Mon', 'Tue', 'Wed', 'Thur', 'Fri'))
plt.legend()
plt.show()
Output
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
import random
import pylab
val = []
for n in range(1004):
x = random.choice(range(0,90))
y = random.choice(range(0,90))
val.append(x+y)
Output:
from tkinter
import *root = Tk()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side =
BOTTOM )
redbutton = Button(frame, text = 'Red', fg
='red')redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()
Output :-
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
mainloop()
Output :-
Output :-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
from tkinter
import *top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()
top.mainloop()
Output :-
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
s.connect((host, port))
print s.recv(1024)
s.close() # Close the socket when done
Output :-
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user =
"root",pass wd = "google")
4. #printing the connection object
5. print(myconn)
Output:
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",
4. passwd= "google", database = "mydb")
5. #printing the connection object
6. print(myconn)
7.
7. #creating the cursor object
8. cur = myconn.cursor()
9. print(cr)
Output:
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google")
5. #creating the cursor object
6. cur = myconn.cursor()
7. try:
8. dbs = cur.execute("show databases")
9. except:
10. myconn.rollback()
11.
11.for x in cur:
12. print(x)
13.myconn.close()
Output:
('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mysql',)
('performance_schema',
)
('testDB',)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Creating a table with name Employee having four columns i.e.,
name, id, s alary, and department id
8. dbs = cur.execute("create table Employee(name varchar(20) not null, id int
(20) not null primary key, salary float not null, Dept_id int not null)")
9. except:
10. myconn.rollback()
11. Myconn.close()
12.
Output :
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4.
5. #creating the cursor object
6. cur = myconn.cursor()
7. try:
8. #adding a column branch name to the table Employee
Output :
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
Output :
1 record inserted!
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (
%s, %s, %s, %s, %s)"
Output :-
3 records inserted!
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select * from Employee")
9. #fetching the rows from the cursor object
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
Output :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #updating the name of the employee whose id is 110
8. cur.execute("update Employee set name = 'alex' where id = 110")
9. myconn.com
mit()10.except:
11. myconn.rollback()
12. myconn.close()
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",
passwd= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Deleting the student details whose rollno is 4
Output :-