You are on page 1of 63

At: Mulagudari,Po: Gudari(B.O),Via: Khajuripada(S.

O),
Dist: Kandhamal-762012

A PROJECT DOCUMENTATION ON

Submitted For
PRACTICAL EXAMINATION AISSCE 2021

Submitted By:
MITRABHANU PRADHAN
ROLL No. : 29

Under the Guidance of :


MR. NABA KISHORE SETHI
PGT, COMP. SC., KV, KANDHAMAL
Page |2

CONTENTS

1. Certificate

2. Acknowledgment

3. Overview of Python (Concept Used)

4. Need for the Project

5. Requirements (hardware & Software)

6. Modules used in the Project

7. Library Functions Used (Description of functions and their purposes)

8. User Defined Functions Used (Description of functions and their purposes)

9. Source Code (listing of all the programs prepared as part of project. )

10. Testing & Output (Screen Snapshots of all the Output Screens)

11. Conclusion

12. Maintenance

13. Certificate (by External)

14. Bibliography
Page |3

At: Mulagudari, Po: Gudari(B.O),Via: Khajuripada(S.O),


Dist: Kandhamal-762012

CERTIFICATE

This is to certify that Mitrabhanu Pradhan student of XII

‘Sc’, Kendriya Vidyalaya Kandhamal has successfully completed his

project work “EMPLOYEE MANAGEMENT SYSTEM” under my

guidance in a period of 18 days from 26th June 2020 to 08th Jan, 2021

in the Computer Lab of Kendriya Vidyalaya Kandhamal. The project

has been performed in accordance with the requirements of AISSCE,

2021.

Under signed wishes you a happy and bright future.

Mr. N. SETHI Mr. S. NAYAK


PGT, Comp. Sc. PRINCIPAL
KV, KANDHAMAL KV, KANDHAMAL
Page |4

ACKNOWLEDGEMENT

I express my deepest gratitude towards Mr. Nabakishore Sethi,

PGT, Comp. Sc., Kendriya Vidyalaya, Kandhamal, for giving me his

valuable suggestions and help in the development of this project.

Secondly, I am very much thankful to Mr. S. Nayak,

PRINCIPAL, Kendriya Vidyalaya, Kandhamal, for giving me the

opportunity / independence to develop such Project.

Finally, I would like to thank all the other members for helping

me for completion of this project. And above all, I am very much

thankful to my friends who had helped me for the completion of this

project report.

. Finally, I would like to thank all the other Stock Entry System

employees for helping me for completion of this project.

Name: Mitrabhanu Pradhan


Date: 08 JAN. 2021
Place: Kendriya Vidyalaya, Kandhamal
Page |5

Overview of Techniques used


through Python Language
This software is developed by using various software methodologies,
involving the Interface Python with anD QL database connectivity to store and
retrieve data through PYTHON and MYSQL DBMS software to automate the
STOCK ENTRY SYSTEM.

Python Fundamentals
Developed by: Guido Van Rossum in early 1990

To Check the version of the python:


python - -version
Example: C:\Users\Your Name>python - - version
• The extension name of the python file is (.py) to execute in python interpreter.

Python Character Set:


➢ Letters: a to z and A to Z
➢ Digits : 0 to9
➢ Special Symbols: space, =,-,(), [], {}, ~@!#$%^&*
➢ White Space: Blank Space, Tabs, Carriage return, newline, formfeed
➢ Other Characters: Python can process all ASCII and UNICODE characters

Python Indentations
➢ In other programming languages the indentation in code is for readability only, in Python the
indentation is very important. Python uses indentation to indicate a block of code.
➢ Example: Python will give you an syntax error if you skip the indentation:
if 5 > 2:
print("Five is greater than two!")

Tokens:
➢ Keywords
➢ Identifiers (names)
➢ Literals
➢ Operators
➢ Punctuators

Keywords:
➢ These words are having special meaning for the compiler.
➢ Used for special purpose, can’t be taken as normal identifier names
Example: if, elif, else, while, for, class, from, True, False, and, or, not, with, as, in, finally, is,
return, None, continue, break, lambda, try, def, nonical, global, yield, import, assert, pass, except,
raise. In python version, 3.6 there are 37 keywards.

Variable Names/Identifier names:


- A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).

Rules for Python variables:


- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number or other special character.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
- Variable names are case-sensitive (age, Age and AGE are three different variables)
Page |6

- No specific length is for python for naming variables.

Example of some VALID Identifiers/Variables:


- ROLLNO, rollno, roll_NO, N1, NO1, No1, No1List, p_no, _Roll_No,
- IF, WHILE, BREAK, While, iF, true, switch, _True, _roll,

Example of some INVALID Identifiers/Variables:


- roll.no – special character like . (dot), @,#,$,%,^ are not allowed.
- 1NO - must not begins with number
- if, while, break, True, False – reserve words/Keyword not allowed
- Total*Tax - Special character like * are not allowed
- Total Tax - white spaces are not allowed
- class, finally – Keyword not allowed

Python Variables
• Used for Creating Variables. Unlike other programming languages,
• Python has no command for declaring a variable. A variable is created at the moment
you first assign a value to it.
Example:
x=5
y = "John"
z=float() #initialize with default float variable
r=str() ; p=int(); q=bool()
s=None; t=True
print(x); print(y); print(z);print(r)

• Variables do not need to be declared with any particular type and can even change
type after they have been set.
Example:
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Literals / Values:
Data items that have fixed / constant values. Python allows several kind of literals:

String Literals:
A string literal is a sequence of characters surrounded by quotes (single or double or triple
quotes).
>>> s1='ram' - valid
>>> s2=''ram'' (two single quote) -SyntaxError: invalid syntax
>>> s2="ram" (double quote) – valid
>>> s2=””ram”” (two double quote) - SyntaxError: invalid syntax
>>> s4=""ram"" (three single quote) Valid
>>> s4="""ram""" (three double quote) valid

String Literal:
➢ Single Line String: line of text enclosed in quotes. >>>str=” I am in the class room ”
➢ Multi Line String : each line last character must be a ‘\’ (backslash).
Example: >>> text=” I am in \
The class \
room “

Escape sequence: These are single characters / non graphic characters followed by \
(backslash). These can be included in a string.
Example:
Example: \\ → for single backslash (\) \’ → for a single quote (‘)
\” → for a double quote(“) \a → for audible bell \b → Back space
\f → Form feed \n→New line character \r → Carriage return \t → Horizontal Tab
\N{name}→ character named name in the Unicode database (Unicode only)
Page |7

\uxxxx →for 16 bit hexa value \Uxxxxxxxx→for 32 bit hexa value


Link to see Unicode names: https://www.compart.com/en/unicode/category/So
Example:
>>>print("\N{Cross Mark}")
>>>print ("\N{SOLIDUS} \N{BLACK SPADE SUIT}")
>>> print("\N{Baseball} \N{Soccer Ball}") OUTPUT: ⚾ ⚽
>>> r='\u0061' - it will display ‘a’ as (0061)16 equal to (97)10 , which is the ASCII value of ‘a’

Numeric Literal – numeric values


int - signed integers (whole numbers values –ve & +ve)
➢ Decimal form: 125, 12, -6, -78
➢ Octal Form: number followed by 0o (zero and alphabet ‘o’)
➢ Hexadecimal : number followed by 0x (zero and alphabet ‘x’)
Example:
>>> n=0o65 ; m=0x65 here n = 53 and m= 101 as decimal equivalent

Floating Point number/literals: these are real flowing point values


➢ Fractional Form: 15.2, 17.365, 8.6
➢ Exponent Form: 0.17E5, 3.0E2 , 0.117e5, 3.e2
0.17E5 = 0.17*105 = 17000
3.0E2 = 3.0*102 = 300
Complex Number:
- Complex numbers are written with a "j" as the imaginary part √-1:
- a+bj format here a and b both float (a real part b imaginary part)
Example of Complex:
>>> x = 3+5j
>>> y = 5j
>>> z = -5j
>>> print(type(x))
Output: <class 'complex'>
>>> print(type(y))
Output: <class 'complex'>
>>> print(type(z))
Output: <class 'complex'>

Boolean Literals
A Boolean literal value can be True or False.
Example: >>> d=True; r=False

Special Literal None


It is used to indicate absence of values.
Example : >>>c=None; >>>type(c) output will be None type
Note: you can also use this value in list and tuples
Example: >>> ls=[2,3,5,None,6,7,None] - list
>>>tp=(4, 6,None,6,7) - tuple

Operators:
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators : [ +,-,*,/,//,%,**]
Example: a=7, b=2,
c=a/b; c will be 3.5
d=a//b d will be 3 as integer part of quotient
e=a%b e will be 1 as reminder
• Assignment operators : [ =, +=, -=,*=,/=,//=,%=,**=]
example: >>>a=b; a+=b;

• Comparison operators/ Relational Operator: ==,>, <, >=<=, !=


• Logical operators: and , or
Page |8

Logical operators are used to combine conditional statements:


and - Returns True if both statements are true x < 5 and x < 10
or - Returns True if one of the statements is true x < 5 or x < 4
not -Reverse the result, returns False if the result is true not(x < 5 and x < 10)
• Identity operators: (is, is not ) Identity operators are used to compare the objects, not if
they are equal, but if they are actually the same object, with the same memory location
is: Returns true if both variables are the same type object
is not: Returns true if both variables are not the same type object
Example:
>>> x=int() ; >>> y=int() >>> z=float()
>>> x is y output: True
>>> x is z output: False
>>> x is not z output: True
>>> x is not y output: True
But
>>> x=2 >>> y=3 >>> x is y - False
>>> x=2 >>> y=2 >>> x is y -True

➢ Membership operators: (in, not in) Membership operators are used to test if a sequence is
presented in an object
In: Returns True if a sequence with the specified value is present in the object
not in: Returns True if a sequence with the specified value is not present in the object
Example:
>>> str1=" Raja Ram" >>> str2="Raja" >>> str3="hari"
>>> str1 in str2 - False
>>> str2 in str1 -True
>>> str3 in str1 - False
>>> str3 not in str1 - True
➢ Bitwise operators: <<, >>
<< [ Zero fill left shift ] Shift left by pushing zeros in from the right and let the leftmost bits fall
off
>> [Signed right shift ] Shift right by pushing copies of the leftmost bit in from the left, and let
the rightmost bits fall off
Example:
>>> D=14 >>> D>>2 result in decimal is 3 >>> D>>1 result in decimal is 7
>>> A=16 >>> A>>2 result in decimal is 4
>>> A=3 >>> A>>2 result in decimal is 0
Punctuators: special symbols used to organize statements, expressions and program structure of
python.
Example: ‘ (single quote), ” (Double Quote) , @, #, \, [ ], { }, : etc.

Barebones of a python program:

# This program shows the structure of a program - single line comment

def Welcome(): # function name


# definition of a user
print("WELCOME TO SASWAT SOMYA SAHU ")
defined function WelCome()
print("He is not a regular student ")

# MAIN PROGRAM CODE FOLLOWS NOW - comment

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


R=N%2 # Expression

if(R==0): # conditional expression statements


print(N," is a Even Number")
else:
print(N," is an Odd Number")

Welcome() # Calling the User Defined


function
Page |9

Variable Assignment
Note: in case integers the values from -5 to 0 and 0 to 256 are having fixed memory location with the
loading of the compiler.

>>> n=257; m=257; id(n); id(m) # both id will be different suppose as 35736528 35737088
>>> n=m; id(n); id(m) # both id will be same 35737088 35737088
Or >>> n, m=257; id(n); id(m) # both id will be same 35737088 35737088
Or >>> n, m=257,257; id(n); id(m) # both id will be same 35737088 35737088
We can assign in the following ways:
>>> a=b=c=9 # assigning multiple variable by a single value.
>>>a,b,c=9,2,3 # assigning multiple values to multiple variables

SAMPLE INPUT AND OUTPUT


input() – used to input string type values. i.e. this function will accept values from user and
return the same as a string type value.
Syntax 1: var=input( [prompt to be displayed ] )
Example: reg=input(“Enter your registration number: “)
Syntax 2: var=int(input( [prompt to be displayed ] ))
Syntax 3: var=float(input( [prompt to be displayed ] ))
Example: mark=int(input(“Enter your full mark: “))
Example: avg=float(input(“Enter your average mark: “))

print()- used to send the output to the standard output device normally to monitor.
syntax : print(object[s], [sep=' ' or <separator string>] [end='\n' or <end-string>])
* object[s] may be expression or object separated by comma.
Example: >>>print() - print a blank line only.
>>> print("My ", "School ", "is" , "KVKDML", sep="$")
Output: My $School $is$KVKDML
>>> print("My ", "School ", "is" , "KVKDML", end="$")
Output: My School is KVKDML$
DATA TYPES:
Data type for Numbers:
➢ Integers Numbers
-integers(signed) example: p=int()
-Boolean: False, True are values equivalent to 0 and 1 , example: q=bool()
➢ Floating-point Numbers: 15 digit double precision number , example: r=float()
➢ Complex numbers: example: a+bj here a is real part and bj is imaginary part, example:
a=complex()
String type:
- It may consist of any type of characters as: letters, numbers and special characters.
- Enclosed in single quote or double quote
- Example of valid strings: “123”, ‘123’, “B45TDGG333”, “1.2233OU&%$#UT”
- It can be accessed by index value. Example: >>>s=”SASWAT” >>>s[0] ; s[1]; s[3]
output will be: S A W
- String is immutable.

LIST TYPE
- Sequence data type (collection of list of values).
- Mutable (modifiable) i.e. elements can be changed.
- It can contain mixed values.
- The values in it are to be separated by comma (,) and enclosed in square bracket ([..])

Example: Ls = [10,20,30,40,50,60,70,”KVS”,90]
Index -9 -8 -7 -6 -5 -4 -3 -2 -1
Values 0 1 2 3 4 5 6 7 8

10 20 None 40 50 60 70 KVS 90
P a g e | 10

Example of List:
[ ] – empty list
[1, 2, 3, 4, 5] – list of integers.
[1, 2, 3.5, 2.5, 3.76, 8] – list of numbers (integers and floating)
[‘a’,’b’,’c’] – list of characters
[“One”,”Two”,“Three”] – list of strings
[10, “Raja Ram”, 98, 78500.69] – list of mixed values types

Creating List:
Syntax: ListName = [value1, value2, . . . . , valueN]
>>>sd=[ ] – Blank list / empty list
>>>sd = list( ) – empty list
>>>sd1=[‘abc’,’cst’,’gst’] – string list
>>> sd=list() >>> type(sd) → <class 'list'>

Syntax of list() - list(<one argument_of_sequence_type>)


Example:
>>> d=[12,11,10]
>>> sd=list(d)
>>> sd → [12, 11, 10] or >>>print(sd)
>>> sd=list(12,11,10) # ERROR /INVALID because this will take only argument as sequence.
>>> sd=list([12,11,10]) #VALID
>>> sd=list(10) # # ERROR /INVALID because 10 is not a sequence
>>> sd=list([10]) # # VALID now 10 is enclosed in [ ] a single element in a sequence

String and List (with characters)


>>> str="ram"
>>> str → 'ram' or >>> print(str)
>>> sd=list(str)
>>> sd → ['r', 'a', 'm'] or >>>print(sd)
>>> str → 'ram'
>>> sd=list(10) → TypeError: 'int' object is not iterable
>>> sd=list([10])
>>> sd → [10]
Note:
>>> str="ram"
>>> sd=list(str)
>>> sd → ['r', 'a', 'm']
>>> str → 'ram'
>>> type(sd) → <class 'list'>
>>> type(str) → <class 'str'>
>>> list=[] # here it is a empty list
>>> sd=list(str) → ERROR sd=list(str) TypeError: 'list' object is not callable
As list is immutable so empty list also can not be modified.

Long List: If a list contains many elements, then to enter such long lists, you can split it
across several lines, like below:
sqrs = [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400,
484, 529, 576, 625 ]
Nested List: A list can have an element in it, which itself is a list.
Example: >>> sd=[1,2,[8,9],6,5] >>> sd → [1, 2, [8, 9], 6, 5] >>> sd[0] → 1
>>> sd[2] → [8, 9] >>> sd[2][0] → 8 >>> sd[2][1] → 9
>>> sd[3] →6 >>> p=[6,8,9] >>> sd=[1,2,p,6,5]
>>> sd → [1, 2, [6, 8, 9], 6, 5]
What is the difference & Similarities between string and list?
- List is mutable but String is immutable
- List is enclose with [ ] (square brackets) but String is enclosed with ‘ (single quote), “
(doublequote), 3 double quote or 3 single quote.
- Similarity is both are sequences.
P a g e | 11

LIST OPERATIONS
Accessing a List
>>> LS = [10, "HARI PRSAD", 98, 99, 78, 80, 90] >>> len(LS) → 7 # Length of the list
>>> LS[0] → 10 >>> LS[1] → 'HARI PRSAD' >>> LS[1][0] → 'H' >>> LS[1][9] → 'D'

Access using slice operator (:)


>>> LS[0:2] → [10, 'HARI PRSAD'] >>> LS[1:2] → ['HARI PRSAD']
>>> LS[2:7] → [98, 99, 78, 80, 90] >>> LS[0:7] → [10, 'HARI PRSAD', 98, 99, 78, 80, 90]
Or >>LS → [10, 'HARI PRSAD', 98, 99, 78, 80, 90] >>> LS[-1] → 90
>>> LS[-1:-3:-1] → [98, 'HARI PRSAD']
>>> LS[0:7:2] → [10, 98, 78, 90] (WITH INCREMENT STEP 2 OF INDEX)
>>> LS[0:-2] → [10, 'HARI PRSAD', 98, 99, 78] >>> LS[-1:3:1] → [] >>> LS[-1:3:-1] → [90, 80, 78]
>>> LS[ : :3] → [10, 99, 90] >>> LS[1::2] → ['HARI PRSAD', 99, 80]
>>> LS[ : :-1] → [90, 80, 78, 99, 98, 'HARI PRSAD', 10]

SLICING THE LIST


Syntax-1: SeqVariable = ListName[Start : Stop]
Example: >>> LS[0:2] → [10, 'HARI PRSAD']

Syntax-2: SeqVariable = ListName[Start : Stop:Step]


Example: >>> LS[0:7:2] → [10, 98, 78, 90] (WITH INCREMENT STEP 2 OF INDEX)

Note: List are like string sequence with forward (0 to len-1) and backward (-1, -len) indexing
and also access like that.

Traversing a list: (displaying a list one after another)


LS = [1, 9, 6,7, 80, 90] LS = [1, 9, 6,7, 80, 90]
for k in range(0,6): ln=len(LS)
print(LS[k], end=" , ") for k in range(0,ln):
print("\n Reverse Order Print: " ) print(LS[k], end=" , ")
for k in range(-1,-7,-1): print("\n Reverse Order Print: ")
print(LS[k], end=" , ") for k in range(-1,-(ln+1),-1):
print(LS[k], end=" , ")
Output: Output:
1 , 9 , 6 , 7 , 80 , 90 , 1 , 9 , 6 , 7 , 80 , 90 ,
Reverse Order Print: Reverse Order Print:
90 , 80 , 7 , 6 , 9 , 1 , 90 , 80 , 7 , 6 , 9 , 1 ,

MEMBERSHIP OPERATOR: (in, not in)


in – if the element present in the list then true else false
not in - if the element not present in the list then true else false
>>> 90 in LS → True >>> 100 in LS → False >>> 100 not in LS → True
Concatenation and replication operators + and *
+ this operator adds one list to the end of another list. (joining)
* This operator repeats a list. i.e. it will not multiply with elements.
Multiply list with int only. (replicating or repeating)

JOINING OF LISTS (+)


>>> ls1 → [1, 5, 6] >>> ls2 → ['ram', 'hari'] >>> ls3=ls1+ls2
>>> ls3 → [1, 5, 6, 'ram', 'hari']
>>> ls3=ls1+2 →TypeError: can only concatenate list (not "int") to list
>>> ls3=ls1+[2] # Valid >>> ls3 → [1, 5, 6, 2] >>> ls1*2 → [1, 5, 6, 1, 5, 6]
>>> ls1*3 → [1, 5, 6, 1, 5, 6, 1, 5, 6]
REPLICATING OR REPEATING (*)
>>> ls1*2 → [1, 5, 6, 1, 5, 6]
>>> ls1*3 → [1, 5, 6, 1, 5, 6, 1, 5, 6]
P a g e | 12

COMPARING LIST:
List can be compared by comparison operators (relational operators) : >, <, ==, >=, <=,!=
Note: it compare each corresponding elements one by one where mismatch occurs then there
only decide the comparison result as true or false.
>>> ls1=[1,2,3,5] >>> ls2=[1,2,2,9] >>> ls1>ls2 → True >>> ls1!=ls2 → True
>>> ls1==ls2 → False >>> ls1<ls2 → False >>> ls1>=ls2 → True

Table to comparison checking


Comparison Result Reason
[1,2,8] < [9,1] True Because 1< 9 is true
[1,2,8,9] <= [1,2,9,1] True Because 8<= 9 is true
[1,2,8,9] <= [1,2,8,1] False Because 9 is not <= 1 so False

WORKING WITH LIST

Appending an element to the list: (add)


>>> ls1=[1,3,5] >>> ls1=ls1+[9] or ls1.append(9) (using append function)
>>> ls1 → [1, 3, 5, 9]
Updating element to a list
Syntax: ListName[index]=<new value> >>> ls1=[1,3,5] >>>ls1[1]=7
>>> ls1 → [1, 7, 5] #>>>print(ls1)
>>> ls1[3]=7 → IndexError: list assignment index out of range

IMPORTANT: HOTS
Storage of List in Memory and assignment or coping in python
>>> c=[1,2,9]
>>> d=c # in this case the same list in c will be share by d as an alias name (alternative name)
>>> c[0]=88 >>> c → [88, 2, 9] >>> d → [88, 2, 9] >>> d=[5,7] >>> c → [88, 2, 9]
>>>d → [5,7]

Making true copy in two separate list on above case:


>>> c=[1,2,9] >>>d=list(c) # here separate copy of list will be assigned to d.
>>> c[0]=88 >>> c → [88, 2, 9] >>> d → [1, 2, 9]

List of Function and Methods:


Global Syntax: ListObject.methodName(<argument>)
index() – used to return the index of the item in the list.
Syntax: ListName.index(<itemToFind>)
Example: >>> LS=[10,20,40,60,10,40] >>> LS.index(40) → 2 >>> LS.index(10) → 0
>>> LS.index(10) → 0

WAP to find how many times a value exist in a list by showing its index.
LS=[10,20,40,60,10,40]
c=len(LS)
for k in range(0, c):
if(LS[k]==10):
print(k, end=" , ")

append() – used to add an item / single element to the end of the list. It will not return any
value.
Syntax: ListName.append(<itemToAdd>)
Example:
>>> ls=[1,4,7] >>> ls.append(9) >>> ls → [ 1, 4, 7, 9 ]
>>> ls.append([5,6]) # it will append [5,6] as a separate element in the same list.
>>> ls → [ 1, 4, 7, 9, [5,6] ] # now it has been a nested list

>>> ls.append(5,6) # INVALID it will take only one argument (may be a sequence/literal)
>>> ls.append([5,6]) # it is valid because it is one argument and a list only.
P a g e | 13

extend() – used to add multiple elements by extending the length of the list.
Syntax: ListName.extend(<ListToExtend>)
Example:
>>> ls = [1, 4, 7] >>> ls.extend([8,7]) >>> ls → [1, 4, 7, 8, 7]
>>> ls.extend (5,6) # INVALID it will take only one argument as a list only.
>>> ls.extend([5,6]) # it is valid because it is one argument and i.e. a list only.

Note: Difference between append() and extend

>>> ls = [1, 4, 7, 6] >>> ls = [1, 4, 7, 6]


>>> ls.append([4,7]) >>> ls.extend([8,7])
>>> ls → [ 1, 4, 7, 6, [8, 7] ] # now nested list >>> ls → [1, 4, 7, 6, 8, 7] # single list
>>> len(ls) → 5 >>> len(ls) → 6
>>> del ls[4] >>> del ls[4]
>>> ls → [1, 4, 7, 6] >>> ls → [1, 4, 7, 6,7]

insert() – used to insert an item at a given position (index).


Syntax: ListName.insert(<position/Index>,item)
Example:
>>> ls1=[5,7] >>> ls1.insert(0,"ram") >>> ls1 → ['ram', 5, 7]
>>> ls1.insert(10,2) # if index will more than the length then it will insert at the end only
>>> ls1 → ['ram', 5, 7, 2] >>> ls1.insert(len(ls1),50) >>> ls1 → ['ram', 5, 7, 2,50]

pop() – used to remove and return the value at a particular index position in the list.
Syntax 1: ListName.pop(<index>)
Syntax 2: ListName.pop() – delete and return the last index value i.e. fromTop

Example:
>>> ls1=[10,20,30,40] >>> ls1.pop() → 30 >>> ls1 → [10, 20, 40]
>>> ls1.insert(2,30) >>> ls1 → [10, 20, 30, 40] >>> v=ls1.pop(2)
>>> v → 30 >>> ls1 → [10, 20, 40]

remove() – used to remove the first occurrence of a given item from the list but does not return
anything.
Syntax: ListName.remove(<item/value>)
>>> ls1=[10,20,10,30,10]
>>> ls1.remove(10)
>>> ls1 → [20, 10, 30, 10]
>>> ls1.remove(10)
>>> ls1 → [20, 30, 10]
>>> ls1.remove(0) # ValueError: list.remove(x): x not in list

Deleting Element from a list


To remove item[s] form list according to index values.
Syntax: del ListName[<index>]
Syntax: del LIstName[<start>:<stop>]
Example:
>>> ls1=[1,7,5] >>> del ls1[2] >>> ls1 → [1, 7] >>> ls2 = [1,7,5,4,6,8,9]
>>> del ls2[2:4] # delete values in index 2 to 4-1
>>> print(ls2) → [1, 7, 6, 8, 9]

clear() – used to remove all the items from the list and the list become empty. And does not
return anything.
Syntax: ListName.clear()
Example: >>> ls1=[10,20,10,30] >>> ls1.clear() >>> ls1 → [ ]

count()- used to return the count of the item that passed as argument. If item is not there then
return zero.
Syntax: ListName.count(<item/value>)
P a g e | 14

Example: >>> ls1=[10,20,10,30] >>> ls1=[10,20,10,30] >>> ls1.count(10) → 2


>>> ls1.count(20) → 1 >>> p=ls1.count(100) >>> p → 0

reverse() – used to reverse and replace with reverse values in the same list through which the
function is called. And does not return anything.
Syntax: ListName.revserse()
Example: >>>ls1=[10,"ram", 90,80] >>> ls1.reverse() >>> ls1 → [80, 90, 'ram', 10]

sort() – used to sort and replace the list with sorted values. Does not return anything.
Syntax -1 : ListName.sort() - sort in ascending order
Syntax -2 : ListName.sort(reverse=True) - sort in descending order
>>> ls1=[6,5,6,8,-9] >>> ls1.sort() # or >>> ls1.sort(reverse=False)
>>> ls1 → [-9, 5, 6, 6, 8] >>> ls1.sort(reverse=True) >>> ls1 → [8, 6, 6, 5, -9]

TUPLE data type


- Sequence data type
- Immutable data type
- Can store values of any type
- The values are Depicted in parenthesis (round bracket)
Note: Tuple cannot modified but can be replaced.
Example:
>>>T= (1,2,3) OR >>>T=1,2,3 # without any parenthesis also tuple
>>>T[0]=9 # Error because immutable
>>>T=(9,2,3) # here it is a new tuple with different ID/address

Note: tuple can not be with a single value


>>> TP1=(5,6)
>>> type(TP1) → <class 'tuple'>
>>> TP2=(5)
>>> type(TP2) → <class 'int'>
>>> TP3=("Ram")
>>> type(TP3) → <class 'str'>
Note: A single value followed by a (,) comma can be assigned with to a tuple.
>>> tp=(9) # here it is int >>> type(tp) → <class 'int'> >>> tp=(9 , ) # here it is a tuple
>>> type(tp) → <class 'tuple'> >>> tp=("Ram") ## here it is string >>>tp=(“Ram” , )
>>>tp=() # empty touple

Example: () – Empty tuple # Remember: (6) – it is an int only a single value is considered as the
type as it is inside it. # (1,2,3) - tuple with integers # (‘a’,’b’,’c’) - tuple of characters i.e. strings
(“ram”,”hari”,”Jagannath”) - Tuple of strings (10, 2.5,”hari”, ”Jagannath”) - Tuple of mixed values

Accessing Tuple:
>>> t=(5,7,9,"ram",9.9) >>> type(t) → <class 'tuple'> >>> t[0] → 5 >>> t[3] → 'ram'
>>> t[3][1] → 'a' >>> len(t) →5
>>> t[1]=15 → ERROR: TypeError: 'tuple' object does not support item assignment
>>>t[-1] → 9.9 >>> t[-4] → 7

Creating Tuples
Syntax 1: Variable = (value1, value2, value3…, valueN)
Syntax 2: Variable = Tuple() # constructor method
Syntax 3: Variable = Tuple(<sequence>)

>>>T1=() >>>T2=(10,2.5,“ram”,”hari”,”Jagannath”)
>>>T3=tuple(1,2,(5,8),[6,7]) # Invalid the argument need a () >>>T4=tuple((1,2,(5,8),[6,7]))
>>>T5=tuple() # Empty tuple >>> t3=tuple("Jagannath") >>> t3 → ('J', 'a', 'g', 'a', 'n', 'n', 'a', 't', 'h')
>>> t3=tuple(('jagannath','')) >>> t3 → ('jagannath', '')
P a g e | 15

Creating Tuple using Keyboard input


t1=tuple(input("Enter Elements to the Tuple 1: "))
print(" Tuple 1 Elements are: ", t1)

t2=eval(input("Enter Elements to the Tuple 2: "))


print(" Tuple 2 Elements are: ", t2)

Output
Enter Elements to the Tuple 1: 1,2,"ram
Tuple 1 Elements are: ('1', ',', '2', ',', '"', 'r', 'a', 'm')
Enter Elements to the Tuple 2: 1,2,"ram"
Tuple 2 Elements are: (1, 2, 'ram')

Similarities and Difference between Tuple and List


Similarities: Differences
- both are sequence data type. -List is mutable and tuple is not
-indexing and slicing can be implemented on both mutable.
-length i.e. len() function can be used on both to find length >>> t=(5, 1, 9, 'ram', 9.9) >>>
-membership operator ‘in’ and ‘not in’ can be used to find l=[5, 1, 9, 'ram', 9.9]
elements. >>> t[0]=100 #'tuple not
-concatenation (+) and Replication (*) operator can used in mutable
both >>> l[0]=100 >>> t -> (5, 1,
9, 'ram', 9.9)
>>> l -> [100, 1, 9, 'ram', 9.9]

Slice Operator: syntax: seq[start:stop:step]


Syntax -1: T[start:stop:step] Syntax -2: T[start:stop] # default step is 1
Syntax -3: seq=T[start:stop] # default step is 1 Syntax -4: seq=T[start:stop:step]

>>>t=(5,1,9, 'ram', 9.9) >>> t[-1:-4:-1] → (9.9, 'ram', 9)


>>> t[0:5:2] → (5, 9, 9.9) >>> t[0:5:3] → (5, 'ram')

Traversing a Tuple (display of element of a tuple one after another)


t=eval(input("Enter a tuple: "))
print("\n Tuple is follows :", t)
for k in range(0,len(t)):
print(t[k])

Joining of Tuple: (+) (two tuples can be added)


>>> tp1=("Ram", "Hari") >>> tp2=(5,9,10) >>> tp3=tp1+tp2
>>> tp3 → ('Ram', 'Hari', 5, 9, 10) >>> tp4=tp1+tp2+tp3
>>> tp4 → ('Ram', 'Hari', 5, 9, 10, 'Ram', 'Hari', 5, 9, 10) >>> tp4=tp1+tp2+tp3+tp4 # VALID
>>> tp1+ (6) # INVALID because one is sequence (tuple) and other is int
>>> tp1+ (6,) # VALID because two both are sequences

Repleating or Replicating of Tuple: (*)


>>> tp=(3,5) >>> tp2=tp*3 >>> tp2 → (3, 5, 3, 5, 3, 5)

Comparing Tuples:
Two tuples can be compared using >, <, >=, <=, !=, == relational operator. Two tuples can be equal if
they have same number of elements and matching values (if int and float with matching values are
considered as equal). If the values are not matched i.e. bigger and smaller they will be treated as
unequal.
>>> tp1=(1,2,3) >>> tp2=(1,2,3.0) >>> tp1==tp2 → True >>> tp3=(1,2,3)
>>> tp1==tp3 → True >>> tp4=(1,5,1) >>> tp1==tp4 → False >>> tp1>tp2 → False
>>> tp1 → (1, 2, 3) >>> tp2 → (1, 2, 3.0) >>> tp4 → (1, 5, 1) >>> tp2<tp4 → True
>>>tp6=(1,2,0) >>>tp7=(1,2) >>tp6==tp7 → false >>>tp8=(1,2,None)
>>tp6==tp8 → false
P a g e | 16

Unpacking Tuple:
Creating a tuple from a set of values is called packing and its reverse i.e. crating individual values
from a tuple’s elements called unpacking.
Syntax: <var1>,<var2>,<var3>,….=Tuple_name
Example:
>>>tp=(1,20,35) # you can say it as packing.
>>> a,b,c=tp # unpacking i.e. individual values will be assigned to separate variables.
>>> a → 1 >>> b → 20 >>> c → 35 >>> a,b=tp # unpacking Error as Value Error

max() - This method returns the element from the tuple having maximum value. But it does not
support string values in tuple.
Syntax: max(seq) >>> t3 =(1, 4, 3) >>> max(t3) -> 4
Note: but direct compare strings
>>> max("ram") → 'r' >>> max("ram", "hari") → 'ram' >>> max("ram", "hari", "xmas") → 'xmas'

min() - This method returns the element from the tuple having minimum value. But it does not
support string values in tuple. But allows only string by comparing asci values.
Syntax: min(sequence) example: >>> t3 =(1, 4, 3) >>> min(t3) ->1

index() - This method returns the index value of an existing element from the tuple.
Syntax: <sequence>.index(value) example: >>> t3 =(1, 4, 3) >>> t3.index(4) ->1

len() – This method returns the length the sequence.


Syntax: len(sequence) example: >>> t3 =(1, 4, 3) >>>len(t3) ->3

count() - This method returns the count of a member element /object in a given sequence.
Syntax: <sequence>.count(value) example: >>> t3 =(1, 4, 3, 4, 6, 44) >>> t3.index(4) ->2

tuple() – This method is actually constructor method that can be used to crate tuples form different
type sof values.
Syntax: tuple(sequence) example: >>> t=tuple() # empty tuple
>>>t=tuple(“kvkdml”) # string to tuple ('k', 'v', 'k', 'd', 'm', 'l')

DICTIONARIES
- Mutable data type
- Not a Sequence (unlike a string, list and tuple it is not as sequence as it is a unordered
collection of data)
- Unordered collection of elements in the form of a Key: Value Pair
- Enclosed in { }
- Internally indexed on the basis of keys
- It is just like an English dictionary word, where keys are words and values are equivalent to
meaning of words.
- Dictionaries are also called as associated arrays or mappings or hashes.
- Keys of a dictionary must be immutable: i.e. it should be a number, string, tuple but list
is not allowed, as it is mutable.

Syntax: Dictionary_name ={'key1': 'value1','key2': 'value2',….…'keyN': 'valueN'}


Example: >>> A={1:"one",2:"two",3:"three"} >>> print A → {1: 'one', 2: 'two', 3: 'three'}
>>>d1={3.5:"Hari Prasad", "Word":"Gopal Prasad"}
>>>d1[3.5] → “Hari Prasad” >>>A[2] → two
>>> teacher={[10,20]: "English" , [9,10]: "Biology"} #INVALID TYPE ERROR
Note: Key values must be immutable type
>>> teacher={(10,20): "English" , (9,10): "Biology"} # valid because tuple is immutable
>>> teacher[(9,10)] → 'Biology'

Accessing a Dictionary:
Syntax: <dictionary_name>[<key>]
>>> teachers = {(1,2):"ram", (3,4):"Hari"} >>> teachers[(1,2)] → 'ram'
>>> teachers['ram'] → Invalid
P a g e | 17

>>> mark = { 1:[90,50,78,56,78],2:[97,90,8,96,88] }


>>> mark[1] → [90, 50, 78, 56, 78] >>> mark[2] → [97, 90, 8, 96, 88]
>>> teacher={"R.R.Thakur" : "English" , "B. Sharma" : "Maths", "B.Sasikala": "Biology"}
>>> print("B.Sharma teaches ", teacher["B. Sharma"]) → B.Sharma teaches Maths

Traversing a Dictionary
teacher={"R.R.Thakur" : "English" , "B. Sharma" : "Maths", "B.Sasikala": "Biology"}
for key in teacher:
print(key," teaches ", teacher[key] )
-- OUTPUT--
R.R.Thakur teaches English
B. Sharma teaches Maths
B.Sasikala teaches Biology

Syntax: For <VariableForKey> in <Dictionary>:


[ processing code should be with VaribleForKey i.e. key values one by one from
dictionary]

Accessing keys or Values Simultaneously


<dictionary>.values() – return all the values in one go from the dictionary.
<dictionary>.keys() – return all the Keys in one go from the dictionary.

Example:
>>> teacher={"R.R.Thakur" : "English" , "B. Sharma" : "Maths", "B.Sasikala": "Biology"}
>>> teacher.values() → dict_values(['English', 'Maths', 'Biology'])
>>> k=teacher.values() → values will be store in k as dict_values type but can not be utilized
>>> k=list(teacher.values()) → converting the output to list type
>>> k → ['English', 'Maths', 'Biology']
>>> teacher.keys() → dict_keys(['R.R.Thakur', 'B. Sharma', 'B.Sasikala'])
>>> tp=tuple(teacher.keys()) # to store in a list
>>> tp → ('R.R.Thakur', 'B. Sharma', 'B.Sasikala')
>>>tp[0] →'R.R.Thakur'
>>> s=str(teacher.values()) → converting to string we can’t access or utilize
# Values will be store in s as “dict_values(['English', 'Maths', 'Biology'])”

Characteristics of a dictionary:
- Unordered set of key:values pair.
- Not a sequence (because unordered set of elements)
- Indexed by keys not by numbers
>>> teacher={"R.R.T" : "Eng" , "B.S" : "Maths", "B.S.K": "Bio"}
>>> teacher[0] # INVALID access as KEY ERROR
>>> teacher["B.S"] → 'Maths' # valid as access thorough key
- Key must be unique (duplicate may be allowed but not valuable)
- Mutable (modify using key to values only)

Syntax: <DictionaryName>[key]=<value>
>>> td={10: "Eng" , 20 : "Maths", 30: "Bio"}
>>> td[10] → 'Eng' # same as >>> print(td[10])
>>> td[10] = "CS" # modify 10 key’s value as CS
>>>td → {10: 'CS', 20: 'Maths', 30: 'Bio'}

- Internally stored as mappings:


Internally the key: value pair of a dictionary are associated with one another with some
internal function (i.e. hash-function – it is an internal algorithm to map and link a key with a
stored value) .

Example:
>>> td={50: "Eng" , 10 : "Maths", 20: "Bio"}
P a g e | 18

Keys Values
50 Bio
10 Eng
20 Maths
Adding elements to dictionary:
Syntax: <dictionaryName>[key]=<value>
>>> td={50: "Eng" , 10 : "Maths", 20: "Bio"}
>>> d → {50: 'Eng', 10: 'Maths', 20: 'Bio'}
>>> d[30]="CS" >>> d -> {50: 'Eng', 10: 'Maths', 20: 'Bio', 30: 'CS'}
Updating element of dictionary:
Syntax: <dictionaryName>[key]=<value>
>>> d[50]="IP" >>> d -> {50: 'IP', 10: 'Maths', 20: 'Bio', 30: 'CS'}

Deleting an Element from dictionary:


Syntax: del <dictionary> [ <key> ]
>>> td={50: "Eng" , 10 : "Maths", 20: "Bio"} >>> del td[10]
>>> td → {50: 'Eng', 20: 'Bio'}

Deleting using pop() function


It will delete and return the value of the key element.
Syntax: <DictionaryName>.pop(key)
Example: >>> td={50: "Eng" , 10 : "Maths", 20: "Bio"}
>>> td.pop(10) → “Maths” # output of pop() function >>> td → {50: 'Eng', 20: 'Bio'}

Checking for existence of a key


Syntax-1: <key> in <DictionaryName>
Syntax-2: <key> not in <DictionaryName>
>>> td={50: "Eng" , 10 : "Maths", 20: "Bio"} >>> 10 in td → True >>> 60 in td → False
>>> 60 not in td → True

Pretty printing a dictionary


To print the dictionary in an organized indent (tab/space).
Json.dumps(<dictioanaryName>, indent=<N>)
Step – 1 : >>> td={50: "Eng" , 10 : "Maths", 20: "Bio"} Step – 2: >>> import json
>>> json.dumps(td, indent="5") → '{\n5"50": "Eng",\n5"10": "Maths",\n5"20": "Bio"\n}'
# above without print statement
>>> print(json.dumps(td, indent=5))
Output with indent of 5 (i.e. 5 white space)
{
"50": "Eng",
"10": "Maths",
"20": "Bio"
}

Dictionary function
len() – used to return length of the dictionary i.e. no. of (key:value) pairs.
Syntax: len(<dictionaryName>)
>>> td={50: "Eng" , 10 : "Maths", 20: "Bio"} >>> len(td) → 3

clear() – used to remove all the items from the dictionary and make it empty.
Syntax: <dictionaryName>.clear()
>>> td={50: "Eng" , 10 : "Maths", 20: "Bio"} >>> td.clear() >>> td → {} # now it is empty

get() – used to get /return the item with the given key. It is similar to dictinaryName[key]. Syntax:
dictionaryName.get(<key>)
>>> td={50: "Eng" , 10 : "Maths", 20: "Bio"} >>> td.get(10) → 'Maths' >>> td[10] →'Maths'

values() -used to return all the values in one go from the dictionary.
Syntax: <dictionary>.values()
>>> teacher={"R.R.Thakur" : "English" , "B. Sharma" : "Maths", "B.Sasikala": "Biology"}
P a g e | 19

>>> teacher.values() → dict_values(['English', 'Maths', 'Biology'])


>>>ls=list(teacher.values()) → it will assign to a list
>>> for k in teacher.values():
Print(k)
Output: 'English'
'Maths'
'Biology'

Keys()– return all the Keys in one go from the dictionary


Syntax: <dictionary>.keys()
Example:
>>> teacher.keys() → dict_keys(['R.R.Thakur', 'B. Sharma', 'B.Sasikala'])
>>> tp=tuple(teacher.keys()) # to store in a list >>> tp → ('R.R.Thakur', 'B. Sharma', 'B.Sasikala')
>>>tp[0] →'R.R.Thakur' >>>ls=list(teacher.keys()) → it will assign the keys to a list

update()- used to update a dictionary with other dictionary values i.e. add all different (keys with values)
element from other dictionary and if duplicate key:values are there then override. If there same key in
other with different value then value will be updated.
syntax: <dictionaryName>.update(otherDictionary)

>>> emp1={10:"Saswat",20:"Tushar",30:"Sanjeet"}
>>> emp2={20:"Ayush",30:"Sanjeet",40:"Tushar",50:"Digbijay"}
>>> emp1.update(emp2)
>>> emp1 → {10: 'Saswat', 20: 'Ayush', 30: 'Sanjeet', 40: 'Tushar', 50: 'Digbijay'}
>>> emp2 →{20: 'Ayush', 30: 'Sanjeet', 40: 'Tushar', 50: 'Digbijay'}

Comments
Single Line comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
Example:
# This is a comment.

Multiple line comments: also called as DOCSTRINGS


Python also has extended documentation capability, called docstrings. Docstrings can be one line, or
multiline. Python uses triple quotes (single quote or double quote) at the beginning and end of the
docstring:
Example:
Docstrings are also comments:
"""This is a
multiline docstring."""

Example:
# add two number
a=10 # a value is 10
b=20; """ b value is 10""" - here semicolon is needed to separate
c=a+b; ''' adding number '''

What is the difference between mutable and immutable explain with example:
A mutable object can be changed after it is created, and an immutable object can't. Objects of built-in
types like (int, float, bool, str, tuple, unicode) are immutable. Objects of built-in types like (list, set, dict)
are mutable. Custom classes are generally mutable
Example:
>>> ls=[10,20,"ram"]; tp=(10, 20, "ram")
>>> id(ls); id(tp) output address: 37974784 38187096
>>> ls[0]=99; print(ls); output: [99, 20, 'ram']
>>> id(ls) 37974784
>>> tp[0]=99 # invalid tuple is not mutable (you can not modify the same.)
P a g e | 20

HOTS
>>> tp=(99, 20, 'ram'); print(tp); output will be as: (99, 20, 'ram')
>>> id(tp); output address: 38185360 # here ID changed that means in above case you are
not
# modifying the tuple rather assigning a new value to the tuple, because ID/address has been
changed.

>>> chr(65) – 'A' >>> ord('A') – 65


>>> t=int(“55”) – valid converted to integer 55
>>> t=int(“5.5”) – invalid parameter must be numeric
>>>p=int(“hari”) – invalid parameter must be digits
>>>s=str(5.5) – valid converted to string “5.5”

OPERATOR
- For numbers, the + character works as a mathematical operator:
Example: >>> x = 5 >>>y = 10 >>>print(x + y) → Output: 15

- If you try to combine a string and a number, Python will give you an error:
Example: >>>x = 5 >>>y = "John" >>> print(x + y)
Output : Error
Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

- If you try to combine a string with itself twice/thrice then :


Example: >>> y = "kvs" >>>print(4* y) → Output : kvskvskvskvs

What is L value and R value in python?


Ans:
L value:
- Expression that can come on the LHS of an assignment.
- It can come on LHS or RHS of an assignment statement.
Example: a=10 or a=b=10; # a and b are L values
R value:
- Expression that can come RHS of an assignment.
- It can come on RHS of an assignment statement.
Example: b=10 or roll=1 but 10=b or 1=roll not valid
Multiple Assignment:
• a=b=c=10
• x, y, z = 1,3,9

HOTS:
** converting asci value to characters and vice versa
>>> chr(65) -> 'A' **used to return characters against ASCII values.
>>> ord('A') -> 65 **used to return ASCII values against characters.

** Sequence data Types in python: str, unicode (string) , list, tuple, buffer, range
** Buffer structures (or simply “buffers”) are useful as a way to expose the binary data from
another object to the Python programmer. They can also be used as a zero-copy slicing
mechanism
Example 1: >>> s = 'Hello world' >>> t = buffer(s, 6, 5)
>>> t -> <read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t -> world
In above code the buffer in this case is a sub-string, starting at position 6 with length 5, and it
doesn't take extra storage space - it references a slice of the string. This isn't very useful for
short strings like this above, but it can be necessary when using large amounts of data. This
example uses a mutable bytearray as follows:
P a g e | 21

>>> s = bytearray(1000000) # a million zeroed bytes


>>> t = buffer(s, 1) # slice cuts off the first byte
>>> s[1] = 5 # set the second element in s
>>> t[0] ->'\x05' # which is now also the first element in t

** range – The range() is a built-in function of Python which returns a range object, which is
nothing but a sequence of integers. i.e., Python range() generates the integer numbers between
the given start integer to the stop integer, which is generally used to iterate over with for loop.

HOTS:
** python do not have any data type like char
** Unlike C++ in python data types are not keywords example (int, float, str, tuple, list, bool )
** If you are taking variables in the name of data types in python then you can not call the
constructor function of that data type to create a new empty variable.
** It will always better do not take variable with name of data types in python.
Example:
>>> p=int() >>> s=str() >>> int=10 >>> q=int() #INVALID AND ERROR
Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> q=int() TypeError:
'int' object is not callable
>>> str1=str() >>> str="ram" >>> str2=str() #INVALID AND ERROR
Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> str2=str()
TypeError: 'str' object is not callable

SORTING
INSERTION SORTING: insert element at proper place by searching and comparing in backward
direction of the list / array.
Ascending order

0 1 2 3 4 5 6
10 20 15 25 11 1 9

0 1 2 3 4 5 6
10 20 15 25 11 1 9

0 1 2 3 4 5 6
10 20 15 25 11 1 9

0 1 2 3 4 5 6
10 15 20 25 11 1 9

0 1 2 3 4 5 6
10 15 20 25 11 1 9

0 1 2 3 4 5 6
10 15 20 25 11 1 9

0 1 2 3 4 5 6
10 11 15 20 25 1 9

0 1 2 3 4 5 6
1 10 11 15 20 25 9

0 1 2 3 4 5 6
1 10 11 15 20 25 9

0 1 2 3 4 5 6
1 9 10 11 15 20 25
P a g e | 22
P a g e | 23

standard input, output, and error streams


*stream means sequence of bytes
- Standard input device is keyboard. (stdin)
- Standard output device is Monitor.(stdout)
- Standard Error showing device is monitor. (stderr)
Example:
>>>import sys
>>> p=sys.stdin.read(10) # to read 10 bytes from keyboard
>>>sys.stdout.write(“line of text”) # display output in monitor
>>>sys.stderr.write(“Error message”) # message as Error as output in monitor

Example:
import sys
for st in sys.stdin:
# print(st)
sys.stdout.write(st)
# press Ctrl+D to exit to the prompt
Example 2:
import sys
fh=open(r"d:\myprog\poem.txt")
line1=fh.readline()
line2=fh.readline()
sys.stdout.write(line1)
sys.stdout.write(line2)
sys.stderr.write("No Error Occured\n")
fh.close()
# press Ctrl+D to exit to the prompt
Example 3:
import math
import sys
p=math.sqrt(16)
sys.stdout.write(str(p))
P a g e | 24

INTERFACE PYTHON WITH MYSQL


Note:
• It will be better to connect your PC to internet before any installation in
python.
• Always run CMD mode in “run as Administrator” so that installation can be
easy
• C:\ Program Files\Python37-32\Scripts> python -m pip install --up grade
pip - upgrade pip installer to install other packages of python.
• mysql>select current_user() - used to show the host and user name

INSTALLATION OF MYSQL CONNECTOR


Step-1: Connect the system to internet:
Step-2: run CMD as administrator
Step-3: Now go to your python folder
C:\> CD C:\Program Files\Python37-32 
Or
C:\> CD C:\Program Files\Python37-32\ Scripts 
Now prompt will be : C:\ Program Files\Python37-32\Scripts> This prompt
may be required when your path has not been set properly. Because pip
command source file there only.

Step-4: Install mysql connector in python:


C:\ Program Files\Python37-32\Scripts> pip install mysql-connector

NOTE: *Go to python shell prompt and write the following command to check
connection object and
>>> import mysql.connector  →if no error comes then mysql connector
installed properly
Or
>>> import mysql.connector as mysqlPy  →mysql connector may be used
with alias name

CREATE DATABASE CONNECTIVITY WITH MYSQL FOR APPLICATION


DEVELOPMENT

Step-1: Import MySQL connector package.


>>> import mysql.connector  →if no error comes then mysql connector
installed properly
Or
>>> import mysql.connector as mysqlPy  →mysql connector may be used
with alias name

Step-2: Open Connection to MySQL database.


Syntax: <connection-Obj>=mysql.connector.connect(host=<”hostname”>,
user=<”username”>,
P a g e | 25

passwd=<”password”>
[,database=<database>])
Example -1 : To login to mysql only
>>> mydb=mysql.connector.connect(host="localhost",
user="root",passwd="admin")
OR by suing alias name of mysql connector
>>>mydb=mysqlPy.connect(host="localhost",
user="root",passwd="admin")
Example -2 : To login to mysql and open Database EMPLOYEE>
>>>mydb=mysql.connector.connect(host="localhost", user="root",
passwd="admin",

database=”EMPLOYEE”)
• connect(….) : this function of mysql.connector us used take four parameter
host, user, passwd and database to establish connection to MySQL or any
MySQL database.
• A database connection object (in above i.e. mydb) controls the
connection to the database. It represents a unique session with a
database connected from within a script/program.
• Is_connected() : This function returns True if the connection is
successful.
Syntax: connectionObj.is_connected()
Example: if mydb.is_connected()==True:
print("Connection to MySQLdatabase is successful")

The following codes are used to connect python with MySQL


Localhost user (not to a particular database) and check for successful
connection:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",
user="root",passwd="admin")
if mydb.is_connected()==True:
print("Connection to MySQLdatabase is successful")
OR
import mysql.connector as sqlPy #sqlPy is the alias name of
mysql.connector
mycon=mysqlPy.connect(host="localhost", user="root",passwd="admin")
if mycon.is_connected()==True:
print("Connection to MySQLdatabase is successful")

Step-3: Create Cursor Instance


• A database cursor is a special control structure that facilitates the
row by row processing of records in the result set. i.e. the set of
records retrieve as per query.
Syntax: <cursorObject> =<connectionObject>.cursor()
Example: curObj=mydb.cursor()
• Different function suing cursor:

Step-3.1: Execute SQL Queries /Commands


P a g e | 26

• execute() – function is used to execute sql queries / commands


Syntax: <cussorObject>.execute(<sql query/command string>)
Example: curObj.execute("SELECT * FROM DEPT")
curObj.execute("CREATE DATABASE IF NOT EXISTS
KDML ")
curObj.execute("INSERT INTO DEPT VALUES (20,
'RESEARCH', 'DALLAS')")

Step-3.2: Extract data from result set after execution of the Queries
using execute()
• fetchall() – It will return all the records retrieved as per query in a tuple
form (i.e. now <data> will be tuple).
Syntax: <data_var>=<cursorObj>.fetchall()
Example: rec=curObj.fetchall()
for k in rec:
print(k)
• fetchone() – It will return one record from resultset (cursor object) as a
tuple or a list. First time it will return the first record, next time it will fetch
the next record and so on. This method returns one record as a tuple: if
there are no more records then it returns ‘None’.
Syntax: <data_var>=<cursorObj>.fetchone()
Example: rec=curObj.fetchone()
print(rec)
• rowcount –The rowcount is a property of cursor object that returns the
number of rows retrieved from the cursor so far.
Syntax: <data_var>=<cursorObj>.rowcount
Example: data=curObj.fetchall()
N=curObj.rowcount #curObj is cursor object (NOT
connection object)
print(“Total number of rows retrieved : “, N) # display total
no. of records

Step-4: Clean up the environment


Commit(): this function is sued to save the changes to the Database
physically, which are
made through INSRT or UPDATE or any DML command through any
front end (python code)
Syntax: <connectionObject>.commit()
Example: mycon.commit() # mycon is connection object (NOT the
cursor object)

Step-5: Clean up the environment


close(): This is the final step to close the connection with MySQL
Syntax: <connection object>.close()
Example: mycon.close()
P a g e | 27

NEED FOR THE PROJECT

EMPLOYEE MANAGEMENT SYSTEM

This project is developed by using various software

methodologies, involving the Interface Python with and SQL

database connectivity to store and retrieve data through

PYTHON and MYSQL DBMS software to automate the Stock

Entry of Computer Peripheral. This is an application for the

computer controlled “EMPLOYEE MANAGEMENT SYSTEM”

making the task easier to maintain stock for an organization.

Our project aims at modeling of the computer software for

the navigation of computer controlled environment to fulfill the

stock entry transactions including database creation and

manipulation modules.

Hence, it can further enhance to incorporate the Stock Entry

jobs easier using computer technology.


P a g e | 28

REQUIREMENTS

HARDWARE

PROCESSOR
• Pentium 486/PI/PII/PIII/PIV/Core2Due or Higher
Processor

MEMORY
• Main Memory : 2 GB or More
• Secondary Memory : 250 GB or More

OTHER PERIPHERALS:
• printer (for Documentation using
hardcopy)
NETWORKING
• LAN (for module developments)
• INTERNET (for online informations)

SOFTWARE

OPERATING SYSTEM
• GUI : Windows 8.1 OS or Higher (or any GUI OS)

APPLICATION
• Word Processor : MS Word (or any other for
documentation)
• Editor : Python IDE or any other
Editor for python coding
LANGUAGE
• Coding Language : Python 3.6.0 (or higher ver.)

DBMS/RDBMS
• SQL Software : MYSQL 5.5.11 (or higher ver.)
P a g e | 29

DATABASE & TABLES USED IN THE


PROJECT
Name of the Database: employee
Tables in the Database & Their purpose

Table Name: dept


Purpose of the Table: This tables is used to store the department details.

Structure of the Table:

Sample Data in the Table:

Table name: emp

P urpose of t he Table: This tables is used to store the employee


detail.

Structure of the table:


P a g e | 30

Sample Data in the Table:

Name of the Database: PASS

Table: user (for password entry)

Purpose of the Table: This tables is used to store the user detail for login screen.

Code to create:
P a g e | 31

DROP DATABASE IF EXISTS PASS;


CREATE DATABASE IF NOT EXISTS PASS;
USE PASS;
create table user (uid char(30) primary key, uname char(30),upwd char(30));
insert into user values('admin@gmail.com', 'N SETHI','admin123');
insert into user values('ayush007@gmail.com', 'ayush','menyoo98');
insert into user values('cslab@yahoo.com', 'csstudents','kvk@cslab');

Structure of the table:

Sample Data in the Table:


P a g e | 32

PYTHON LIBRARY MODULES


USED IN THE PROJECT

import mysql.connector
To change the current database later, execute a USE SQL
statement or set the database property of the MySQLConnection
instance. By default, Connector/Python tries to connect to a
MySQL server running on the local host using TCP/IP. The host
argument defaults to IP address 127.0. 0.1 and port to 3306.

import datetime
Date and datetime are an object in Python, so when you
manipulate them, you are actually manipulating objects and not
string or timestamps. Whenever you manipulate dates or time,
you need to import datetime function.
P a g e | 33

FUNCTIONS USED IN
THE PROGRAM

def database_setup():
- U sed to cr eate d atab ases w i th i ts t abl es usi ng D D L comma nd.
- The d atabas e i s “e mpl oye e ” an d the tabl es na me i s “de pt”, “em p”.

def connectivity_check():
- U sed to check conn ecti vi ty betw e en mys ql and python .

def show_database_contents():
- U sed to l i st ta bl es i n e mpl oye e data base.

def edit_database():
- U sed to i nse rt, del ete, u pdat e reco rds i n empl o yee data base .

def insert():
- U sed to i nse rt, del ete a nd up date reco rds i n e mpl oyee datab ase.

def delete():
- U sed to del ete r ecords i n em pl oyee datab ase .

def update():
- U sed to up date reco rds i n e mpl oye e dat abase .

def acquire_data():
- U sed to show reco rds fr om e mp an d de pt tabl e .

def empno():
- U sed to show detai l s o f an empl oye e by e mpno .

def ename():
- U sed to show detai l s o f an empl oye e by e name .

def job():
- U sed to show detai l s o f al l em pl oyee s by j ob .

def deptno():
- U sed to show detai l s o f al l em pl oyee s by dep tn o .

def job_wise():
- U sed to show detai l s o f al l em pl oyees j o bw i se.

def deptno_wise():
- U sed to show detai l s o f al l em pl oyees deptn ow i se .
P a g e | 34

SOURCE CODE OF THE PROJECT


# B E S T V IEW IN C ON FIGU R E ID E : FON T FA C E : cour io n n ew [bol d] S IZE : 12 IN D E N T
W ID T H : 4
# E MP LOY E E IN FOR MA T ION S Y S TE M

im por t os
im por t da tetim e
now = da tetim e. date tim e.n ow ()

im por t m ysql. con nec tor


def data bas e_se tup ():
m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d =" adm in")

m ycur sor =m yc on.c ur sor ()


m ycur sor .ex ecu te("D R OP D A T A B A S E IF E X IS T S em ployee")
m ycur sor .ex ecu te("C R E A T E D A T A B AS E IF N OT E X IS TS em ployee")

# m ycur sor .ex ecu te("U S E em plo yee")


m ycon. clo se()

m ydb=m ys ql.co nn ect or .con nec t(h ost ="loc al host" ,user ="r o ot", passw d="a dm in", d
ataba se=" em ploy ee")

m ycur sor =m yd b.c ur sor ()


pr int ("C r eatin g D E P T table... . \n\ n\n\ n")
sql = "C R E A T E T A B LE DE PT (D E P TN O int N OT N U LL, D N A ME var char (1 4), LOC
var char (13 ), P R IMA R Y K E Y (D E P T N O));"
m ycur sor .ex ecu te(s ql)
pr int ("D E P T T A B LE C RE A TE D !!! \n\n" )

pr int ("C r eatin g E MP ta ble... . \n\ n\n")


sql = "C R E A T E T A B LE E MP (E MP N O int N OT N U LL P R IMA R Y K E Y , E N A ME char (10),
JOB char (9 ), MGR int, D O J d ate, S A L IN T (7), C OMM IN T (7), D E P T N O int ,
FOR E IGN K E Y (D E P T N O) R E FE RE N C E S DEP T (D E PT N O));"
m ycur sor .ex ecu te(s ql)
pr int ("E MP T A B LE C R E A TE D !!!! \n\ n\n")
pr int ("E MP LOY E E D A T A B A SE S U C CE S S FU LLY C R E A T E D !!! \n\n\ n")
pr int ("W oul d y ou li ke t o in ser t t he d efa ult value s in to t he dat abas e? \ n\n" )
pr int ("Y -Y E S OR N -N O")

n=i np ut( )
if n in[' y' ,' Y ' ]:
m ycur s or .exec ute ("IN S E R T IN T O D EP T V A LU E S (10, ' A C C OU N T IN G' , ' N E W
Y OR K ' );")
m ycur s or .exec ute ("IN S E R T IN T O D EP T V A LU E S (20, ' R E S E A RC H ' , ' DA LLA S ' );")
m ycur s or .exec ute ("IN S E R T IN T O D EP T V A LU E S (30, ' S A LE S ' , 'C H IC A GO' );")
m ycur s or .exec ute ("IN S E R T IN T O D EP T V A LU E S (40, ' OP E R A T IONS ' , ' B OS T ON' );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7369, ' S MIT H ' , ' C LE R K' , 7902,
' 1990-12 -17' , 80 0, N U LL , 20 );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7499, ' A LLE N ' , ' S A LE S MA N ' , 7698,
' 1981-02 -20' , 16 00, 3 00, 3 0);")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7521, ' W A R D ' , ' S A LES MA N ' , 7698,
' 1981-02 -22' ,125 0, 50 0, 30 );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7566, ' JON E S ' , ' MA N A GE R' , 7839,
' 1981-04 -02' , 29 75, N U L L, 20 );")
P a g e | 35

m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7654, ' MA R T IN ' , ' S A LE S MA N' , 7698,
' 1981-09 -28' , 12 50, 1 400, 30);" )
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7698, ' B LA K E ' , ' MA N A GE R ' , 7839,
' 1981-05 -01' , 28 50, N U L L, 3 0);")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7782, ' C LA R K ' , ' MA N A GE R ' , 7839,
' 1981-06 -09' , 24 50, N U L L, 10 );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7788, ' S C OT T' , ' A N A LY ST ' , 7566,
' 1982-12 -09' , 30 00, N U L L, 20 );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7839, ' K IN G' , ' P R E S IDE N T' , N U LL,
' 1981-11 -17' , 50 00, N U L L, 10 );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7844, ' T U R N E R ' , ' S A LE S MA N' ,
7698, ' 198 1 -0 9-08' , 1 500, 0, 30 );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7876, ' A D A MS ' , ' C LE R K ' , 7788,
' 1983-01 -12' , 11 00, N U L L, 20 );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7900, ' JA ME S ' , ' C LE R K ' , 7698,
' 1981-12 -03' , 95 0, N U LL , 30 );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7902, ' FOR D ' , ' A N A LY S T' , 7566,
' 1981-12 -03' , 30 00, N U L L, 20 );")
m ycur s or .exec ute ("IN S E R T IN T O E MP V A LU E S (7934, ' MIL LE R ' , ' C LE R K ' , 7782,
' 1982-01 -23' , 13 00, N U L L, 10 );")
m yd b.com m it( )
pr in t("V A LU E S S U C C E S S FU LLY E N TE RE D ")

def c on nect ivit y_ch eck( ):


m ycon =m ysql .co nne ctor .c on nect (h ost ="l ocalh ost" ,
user ="r oo t",pa ssw d="adm in" ,da taba se=" em ploye e")

if m yc on.i s_co nn ecte d() ==T r ue:


pr i nt("C o nn ecti on to M yS QLd ata base i s suc cess ful")
else :
pr i nt("C o nn ecti on E r r or ....!!! E xit of t h e pr ogr am ...! !!")

def s how _da tab ase_c on ten ts( ):

m ydb=m ys ql.co nn ect or .con nec t(h ost ="loc al host" ,user ="r o ot", passw d="a dm in", d
ataba se=" em ploy ee")
m ycur sor =m yd b.c ur sor ()
pr int ("___ ____ ____ ____ ____ ____ ____ ___ ______ ____ ____ ____ ____ _E MP LOY E E
D A T A B SE ________ ____ ____ ____ _____ ____ _ ______ ____ ____ ____ ___ \ n\n\ n")
pr int (" * * * * ** * ** *** * ** ** * ** ** ** ** * ** ** ** * ** ** ** ")
pr int (" D E P T T A B LE ")
pr int (" * * * * ** * ** *** * ** ** * ** ** ** ** * ** ** ** * ** ** ** ")

sql ="S E LE C T * FR OM D E P T ;"


m ycur sor .ex ecu te( sql)
p=m yc ur sor .fe tch all()
pr int (" \t\ t\t\t --- --- --- --- --- --- --- ---- --- --- --- --- - ---- --- --- ---- " )
pr int (" \t\ t\t\t DEPTNO D N A ME LOC A T ION ")
pr int (" \t\ t\t\t --- --- --- --- --- --- --- ---- --- --- --- --- - ---- --- --- ---- " )
for i i n p :
pr i nt(" \ t\t\t \t\t", i[0 ]," \t",i [1], ((12 -len (i[ 1]))* " ")," \ t",i[2 ])
pr int (" \t\ t\t\t --- --- --- --- --- --- --- ---- --- --- --- --- - ---- --- --- ---- " )
pr int (" * * * ** * ** ** ** * ** ** ** ** * ** ** * ** ** ** ** * ** ** ** * ** ** ** * ** ** ** * ** ** ** ** * ** ")
pr int (" E MP T A B LE ")
pr int (" * * * * ** ** ** * ** ** ** * ** * ** ** * ** ** ** ** * ** ** ** * ** ** ** * ** ** ** * ** ** ** ** * ** ")

m ycur sor .ex ecu te("S E LE C T * FR OM E MP ; ")


p=m yc ur sor .fe tch all()
P a g e | 36

pr int (" \t\ t-- --- ---- --- --- --- --- --- --- --- ---- --- --- -- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- -- " )
pr int (" \t\ t E MP N O E N A ME JOB MGR D OJ S A LA R Y C O MM
D E P T N O")
pr int (" \t\ t-- --- ---- --- --- --- --- --- --- --- ---- --- --- -- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- -- " )
for i i n p :
pr i nt(" \ t\t",i [0]," \ t",i[1 ],(( 8 -le n(i [1]) )* " "),"",i[2] ,((1 0 -le n(i [2]) )* "
"),"",i[3] ," \t",i[ 4]," \ t",i[5 ]," \t",i [6]," \ t ",i[ 7])
pr int (" \t\ t-- --- ---- --- --- --- --- --- --- --- ---- --- --- -- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- -- " )
def e dit_ dat aba se( ):
pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")
pr int (" \t\t \t\t\ t | 1. IN S E R T R E C OR D |")
pr int (" \t\t \t\t\ t | 2. D E LE T E R E C OR D |")
pr int (" \t\t \t\t\ t | 3. U P D A T E R E C OR D |" )
pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")
n=i nt( inp ut(" \t\t\ t\t\ t\t E n ter yo ur cho ice :" ))
pr int (" \t\t \t\t\ t\t |* * * ** ** * ** ** ** * ** ** ** * ** ** ** * ** * ** ** | \n")
if n == 1:
in ser t()
if n == 2:
d elet e()
if n == 3:
u pda te( )
def i nser t( ):
m ydb=m y sql.c on nec tor .co nne ct( hos t="l o calho st", user ="r oo t",p assw d="a dm in",
data base ="E MP LOY E E ")

m ycur sor =m yd b.c ur sor ()

pr int (" \n E n ter th e de tails of the em plo ye e w hose r ecor d s t o be inser t ed: \ n")
en o=in t(i np ut("E n ter em plo yee N o:"))
nam =i npu t("E n ter em ploy ee nam e:")
jb=i np ut("E n ter em pl oyee j ob :")
pr int ("E nter D at e o f Joi nin g as d d:m m :yy y: ");
d=i nt( inp ut(" dd : "))
m =int (in put ("m m : "))
y=i nt(i np ut(" yyyy :"))
dj= dat etim e.d ate (y,m ,d) # dat eti m e.date( 1981 , 4, 2 )
# dj = d ate tim e.da tetim e( y,m ,d)
# dj = dj .str ftim e (' %Y -%m - %d' )
# pr in t(d j)
sl=f loa t(in pu t("E nt er S alar y:"))
dn o=i nt(i np ut("E n ter de pt no N o :"))
m ycur sor .ex ecu te("IN S E R T IN T O E MP (empno, enam e, job , d oj, sa l, com m , de pt no)
V A LU E S ({ } , '{ }' , ' {} ' , ' {} ' , {} ,{ } , { } )".for m at(en o, nam , j b, dj , sl, ' N U LL' , dno ))
m ydb.c om m it() # T o sa ve a bov e D ML tr a nsact ion s t o th e da tab ases ot her w ise w ill
not save per m ane ntly

m ycur sor .ex ecu te("S E LE C T * FR OM E MP ")


for k i n m ycur s or :
pr in t(k )
m ydb.c los e()
def delet e() :
im por t m ysq l.co nn ect or
m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d=" adm in",
data base ="em pl oyee" )
if m yco n.is _co nne cte d() ==T r ue:
pr in t("C o nne cti on t o M yS QLda tab ase i s suc cess ful")

m ycur sor =m yc on.c ur sor ()


P a g e | 37

en o=in t (i np ut("E n ter the em pn o w hich r ec or d yo u w ant t o d elete : ") )


qr ="D E LE T E FR OM E MP W H E R E em pno={ } ".for m at(e no)
pr int (qr )
m ycur sor .ex ecu te( qr )
m ycon. com m it() # T o s ave abo ve D M L t ansac tio ns t o t he d ata base s o ther w ise w ill
not save per m ane ntly
pr int (" \nA FT E R D E LE T ION C ON T E NT OF E MP T A B LE FOLLOW S : ")
m ycur sor .ex ecu te("S E LE C T * FR OM E MP ")
for k i n m ycur s or :
pr in t(k )
m ycon. clo se()

def upd ate ():


im por t m ysq l.co nn ect or
m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d=" adm in",
data base ="em pl oyee" )

m ycur sor =m yc on.c ur sor ()

en o=in t(i np ut("E n ter the em pn o w hich r ec or d yo u w ant t o u pda te: " ))
qr ="S E LE C T * FR OM E MP W H E R E em pno={ } ".for m at(eno)
pr int (qr )
m ycur sor .ex ecu te( qr )
r ec=m ycur s or .fetc hall ()
pr int (" \n Ol d R ec or d is foll ow s: ")
for k i n r ec:
pr in t(k )

pr int (" \nE N T E R D E T A ILS T O U P D AT E R E COR D : \n")


pr int ("E nter em pl oyee N o:", en o)
nam =i npu t("E n ter em ploy ee nam e:")
jb=i np ut("E n ter em pl oyee j ob :")
sl=f loa t(in pu t("E nt er em ploy ee S alar y:" ))
dn o=i nt(i np ut("E n ter de pt no N o :"))
qr ="U P D A T E E MP SE T enam e=' { }' , job=' { } ', S al={ } , dept no ={ } w her e
em pno={ } ".for m at( nam , jb , sl, dn o,en o)
pr int (qr )
m ycur sor .ex ecu te( qr )
m ycon. com m it()
pr int (" \nN E W R E C OR D A FT E R U P D AT E OF T A B LE : ")
m ycur sor .ex ecu te("S E LE C T * FR OM E MP ")
for k i n m ycur s or :
pr in t(k )
m ycon. clo se()

def a cqu ir e_da ta( ):


m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d=" adm in",
data base ="em pl oyee" )

m ycur sor =m yc on.c ur sor ()


pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")
pr int (" \t\t \t\t\ t | 1. S H OW R E C OR D FR OM E MP N O |")
pr int (" \t\t \t\t\ t | 2. S H OW R E C OR D FR OM N A ME |")
pr int (" \t\t \t\t\ t | 3. S H OW R E C OR D FR OM JOB |")
pr int (" \t\t \t\t\ t | 4. S H OW R E C OR D FR OM D E P T N O |")
pr int (" \t\t \t\t\ t | 5. S H OW R E C OR D JO B W IS E |")
pr int (" \t\t \t\t\ t | 6. S H OW R E C OR D D E P T N O W ISE |")
P a g e | 38

pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")


n=i nt( inp ut(" \t\t\ t\t\ t\t E n ter yo ur cho ice :" ))
pr int (" \t\t \t\t\ t|* * * * ** ** * ** ** ** * ** ** ** * ** ** ** * *** * ** | \n")
if n == 1:
em p no( )
if n == 2:
# os.sy stem (' cls' )
e nam e()
if n == 3:
jo b( )
if n == 4:
d ept no ()
if n == 5:
jo b_w ise()
if n == 6:
d ept no_w ise( )

def em p no ():
m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d=" adm in",
data base ="em pl oyee" )

m ycur sor =m yc on.c ur sor ()


pr int ("E nter t he em pl oye e n o. w hose r ec o r d you w ant to see :")
em pn o=in t(i np ut() )
m ycur sor .ex ecu te("S E LE C T * FR OM E MP W H E R E E MP N O={} ".for m at(em pno) )
p=m yc ur sor .fe tcha ll()
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
pr int (" \t\t E MP N O E N A ME JOB MGR D OJ S A LA R Y C O MM
D E P T N O")
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
for i i n p :
pr in t(" \t \t",i[ 0]," \ t",i[1 ],(( 8 -le n(i[ 1]) )* " ") ,"",i[2], ((10 -le n(i[ 2]))* "
"),"",i[3] ," \t",i[ 4]," \ t",i[5 ]," \t",i [6]," \ t ",i[ 7])
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )

def e nam e() :

m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d=" adm in",
data base ="em pl oyee" )

m ycur sor =m yc on.c ur sor ()


pr int ("E nter t he em pl oye e nam e w ho se r e cor d yo u w ant to s ee :" )
enam e =in put ()
m ycur sor .ex ecu te("S E LE C T * FR OM E MP W H E R E E NA ME =' {} ' ".for m at(enam e))
p=m yc ur sor .fe tcha ll()
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
pr int (" \t\t E MP N O E N A ME JOB MGR D OJ S A LA R Y C O MM
D E P T N O")
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
for i i n p :
pr in t(" \t \t",i[ 0]," \ t",i[1 ],(( 8 -le n(i[ 1]) )* " ") ,"",i[2], ((10 -le n(i[ 2]))* "
"),"",i[3] ," \t",i[ 4]," \ t",i[5 ]," \t",i [6]," \ t ",i[ 7])
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )

def j ob( ):

m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d=" adm in",
data base ="em pl oyee" )
P a g e | 39

m ycur sor = m yc on.c ur sor ()


pr int ("E nter t he j ob w hos e r ecor d you w ant t o see :")
job =in pu t()
m ycur sor .ex ecu te("S E LE C T * FR OM E MP w her e job=' { } ' ".for m at(job) )
p=m yc ur sor .fe tcha ll()
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
pr int (" \t\t E MP N O E N A ME JOB MGR D OJ S A LA R Y C O MM
D E P T N O")
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
for i i n p :
pr in t(" \t \t",i[ 0]," \ t",i[1 ],(( 8 -le n(i[ 1]) )* " ") ,"",i[2], ((10 -le n(i[ 2]))* "
"),"",i[3] ," \t",i[ 4]," \ t",i[5 ]," \t",i [6]," \ t ",i[ 7])
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )

def dep tno ():


m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d=" adm in",
data base ="em pl oyee" )

m ycur sor =m yc on.c ur sor ()


pr int ("E nter t he depar tm e nt n o. w hos e r ecor d yo u w ant to s ee :" )
de ptn o=i nt(i np ut( ))
m ycur sor .ex ecu te("S E LE C T * FR OM E MP w her e dept no={ } ".for m at( dep tn o))
p=m yc ur sor .fe tcha ll()
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
pr int (" \t\t E MP N O E N A ME JOB MGR D OJ S A LA R Y C O MM
D E P T N O")
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
for i i n p :
pr in t(" \t \t",i[ 0]," \ t",i[1 ],(( 8 -le n(i[ 1]) )* " ") ,"",i[2], ((10 -le n(i[ 2]))* "
"),"",i[3] ," \t",i[ 4]," \ t",i[5 ]," \t",i [6]," \ t ",i[ 7])
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )

def j ob_w ise( ):


m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d=" adm in",
data base ="em pl oyee" )

m ycur sor =m yc on.c ur sor ()


pr int ("E MP LOY E E S A R R A N GE D JOB W ISE A R E A S FOLLOW S : \n")

m ycur sor .ex ecu te("S E LE C T * FR OM E MP or der by j ob desc" )


p=m yc ur sor .fe tcha ll()
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
pr int (" \t\t E MP N O E N A ME JOB MGR D OJ S A LA R Y C O MM
D E P T N O")
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
for i i n p :
pr in t(" \t \t",i[ 0]," \ t",i[1 ],(( 8 -le n(i[ 1]) )* " ") ,"",i[2], ((10 -le n(i[ 2]))* "
"),"",i[3] ," \t",i[ 4]," \ t",i[5 ]," \t",i [6]," \ t ",i[ 7])
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )

def dep tno _w ise():


m ycon =m ysql. co nnec tor .c onn ect (ho st="l ocalh ost" , us er ="r oot", passw d=" adm in",
data base ="em pl oyee" )

m ycur sor =m yc on.c ur sor ()


pr int ("E MP LOY E E S A R R A N GE D JOB W ISE A R E A S FOLLOW S : \n")
P a g e | 40

m ycur sor .ex ecu te("S E LE C T * FR OM E MP or der by dep tno asc" )


p=m yc ur sor .fe tcha ll()
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
pr int (" \t\t E MP N O E N A ME JOB MGR D OJ S A LA R Y C O MM
D E P T N O")
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )
for i i n p :
pr in t(" \t \t",i[ 0]," \ t",i[1 ],(( 8 -le n(i[ 1]) )* " ") ,"",i[2], ((10 -le n(i[ 2]))* "
"),"",i[3] ," \t",i[ 4]," \ t",i[5 ]," \t",i [6]," \ t ",i[ 7])
pr int (" \t\t --- --- --- --- --- --- --- ---- --- --- --- --- --- --- ---- --- --- ---- --- --- --- --- --- --- --- ---- --- - " )

# __ MA IN ___
# LOGIN P A S S W OR D S C R E E N

ctr =0
flag= 0
w hile ctr <3:
im por t m ysq l.co nn ect or
pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")
pr int (" \t\t \t\t\ t | LOG IN S C R E E N OF S YS T E M |")
pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")
user _ nam e=i npu t(" \t \t\t\ t\t\ t E nter U s er N am e: ")
ps d=in pu t(" \t\ t\t\ t\t\ t E nter P as sw or d: ")
pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")

m ydb=m ys ql.co nn ect or .con nec t(h ost ="loc al host" ,user ="r o ot", passw d="a dm in", d
ataba se="P A S S ")
m ycur sor =m yd b.c ur sor ()
sql ="S E LE C T uid,un am e,upw d fr om user "
m ycur sor .ex ecu te(s ql)
ctr =c tr +1
for i i n m ycur s or :
# pr int(" \t\t",i [0]," \t",i[ 1], " \ t",i[2 ])
if (i[1 ]== user _ nam e)a nd(i [2] == psd ):
pr int (" \t\t\ t\t\ t | S ucc essf ully log in ...! !! |")
pr int (" \t\t\ t\t\ t |* * * * ** * ** ** ** ** * ** ** ** * *** * ** ** * ** ** | \n\n\n\ n\n")
flag =1
br eak;
if fl ag= =0 a nd ctr <3:
pr in t(" \t \t\t\ t\t | IN V A LID U ID OR P A S S W OR D ...!!! |")
pr in t(" \t \t\t\ t\t | T R Y A GA IN (MA X 3 T IME S ) ...!!! |")
pr in t(" \t \t\t\ t\t |* * * ** ** * ** ** ** * ** ** ** * ** ** *** * ** ** * * | \n")
elif flag ==0 an d ctr > =3:
pr in t(" \ n\t\t \t\tS OR R Y ..!! S Y S T E M E R R OR C ON T A C T Y OU R V E ND E R ..!! ")
ex it()
else :
br ea k;

# MA IN ME N U
pr int(" ...... ......... ......... .W elco m e S ir T o Main
P r ogr am ................. ....... \ n\n\ n\n" )
pr int(" ...... ......... .D evel ope d B Y Mitr abha nu P r ad han, C lass X II
S C ............... \ n\n\ n\n" )
w hile T r ue:
pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")
pr int (" \t\t \t\t\ t | E MP LOY E E MA N A GE ME N T S YS T E M |")
pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")
pr int (" \t\t \t\t\ t | 1. D A T A B A S E S ET U P |" )
pr int (" \t\t \t\t\ t | 2. C ON N E C T IV IT Y C H EC K |")
P a g e | 41

pr int (" \t\t \t\t\ t | 3. S H OW D A T A B A S E CON T E NT S |")


pr int (" \t\t \t\t\ t | 4. E D IT D A T A B A S E |")
pr int (" \t\t \t\t\ t | 5. A C QU IR E D A T A |")
pr int (" \t\t \t\t\ t | 6. E X IT | ")
pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * |")
n=i nt( inp ut(" \t\t\ t\t\ t\t E n ter yo ur cho ice :" ))
pr int (" \t\t \t\t\ t |* * * * ** * ** ** ** * ** ** ** * ** ** ** * ** ** * ** * | \n")
if n == 1:
d ata base _set up ()
if n == 2:
# os.sy stem (' cls' )
c onn ecti vity _che ck( )
if n == 3:
s how _dat aba se_c ont ent s()
if n == 4:
e dit_ dat abas e()
if n ==5 :
ac quir e_ dat a()
if n == 6:
br ea k
P a g e | 42

TESTING OF THE
PROGRAM

The program runs very well and it

produces the desired output as expected by

me. This Program is an easy and excellent

way for the Employee Management System

to Manage details of Employees and

Departments.

It perfectly stores the information of all

the Employees and Departments with

accurately and effectively.


P a g e | 43

OUTPUT OF THE PROJECT

OUTPUT SCREEN: ONE

PURPOSE: SECURITY OF THE SYSTEM.


P a g e | 44

OUTPUT SCREEN: TWO

PURPOSE: USER ID AND PASSWORD ENTRY SCREEN SHOWING ERRORS


INCASE INVALID LOGIN ID AND PASSWORD.
P a g e | 45

OUTPUT SCREEN: THREE

PURPOSE: MAIN MENU SYSTEM.


P a g e | 46

OUTPUT SCREEN: FOUR

PURPOSE: MAIN MENU SELECTING OPTION FOR DATABASE SETUP.


P a g e | 47

OUTPUT SCREEN: FIVE

PURPOSE: SHOWING THE CREATION OF THE DATABASE.


P a g e | 48

OUTPUT SCREEN: SIX

PURPOSE: TO CHECK THE CONNECTIVITY BETWEEN MYSQL AND


PYTHON.
P a g e | 49

OUTPUT SCREEN: SEVEN

PURPOSE: SHOWING CONTENTS OF DATABASE.


P a g e | 50

OUTPUT SCREEN: EIGHT

PURPOSE: ADDING NEW RECORDS IN EMP TABLE AND LIST THEM.


P a g e | 51

OUTPUT SCREEN: NINE

PURPOSE: DELETING RECORDS FROM EMP TABLE AND LIST THEM.


P a g e | 52

OUTPUT SCREEN: TEN

PURPOSE: UPDATING RECORDS OF PRODUCT TABLE AND LIST THEM.


P a g e | 53

OUTPUT SCREEN: ELEVEN

PURPOSE: USED TO SHOW DETAILS OF AN EMPLOYEE BY


EMPNO.
P a g e | 54

OUTPUT SCREEN: TWELVE

PURPOSE: USED TO SHOW DETAILS OF AN EMPLOYEE BY


NAME.
P a g e | 55

OUTPUT SCREEN: THIRTEEN

PURPOSE: USED TO SHOW DETAILS OF ALL EMPLOYEES BY


JOB.
P a g e | 56

OUTPUT SCREEN: FOURTEEN

PURPOSE: USED TO SHOW DETAILS OF ALL EMPLOYEES BY DEPTNO.


P a g e | 57

OUTPUT SCREEN: FIFTEEN

PURPOSE: USED TO SHOW DETAILS OF ALL EMPLOYEES JOBWISE.


P a g e | 58

OUTPUT SCREEN: SIXTEEN

PURPOSE: USED TO SHOW DETAILS OF ALL EMPLOYEES DEPTNOWISE.


P a g e | 59

OUTPUT SCREEN: SEVENTEEN

PURPOSE: EXISTING THE PROGRAM.


P a g e | 60

CONCLUSIONS

All the process of this “EMPLOYEE MANAGEMENT SYSTEM” is

working successfully. The code, test plan & other documents are used to

solve the total process of the system. Any user can test this project easily

but there may be some error that can be negligible and that will not affect

the system or the general user. Any type of difficulty will be find that should

be error free by the system administrator. The design of the system is very

attractive but time taking or the system is very user friendly.

❖ Maintenance: The maintenance is very easy not so risky.

❖ Reliability: The system’s reliability is perfect.

❖ Operation: This process involved in the system is error free.

❖ Security: The security is average but it can be increased by


maintaining.

❖ Safety: There is Security provision for maintaining the records, so,


it is a safety system.

❖ Cost: The cost of developing & validating the system reliability is


very less.

❖ Time consume: The system is very less time consuming for


updating, entering the data & searching the data.
P a g e | 61

MAINTENANCE

INSTALLATION PROCEDURE

The user has to first switch ON the computer


then wait for the desktop screen. Then open the CD
drive & copy the folder of this software to the mass
storage device of the PC.

DOCUMENTATION:
The program provides proper documentation
with clarity of coding.

MAINTENANCE

The Software provides a very user-friendly


environment/coding for its maintenance as per the
requirement in the place of installation.
P a g e | 62

At: Mulagudari,Po: Gudari(B.O),Via: Khajuripada(S.O), Dist: Kandhamal -762012

DEPARTMENT OF COMPUTER SCIENCE

CERTIFICATE
This is to certify that Mitrabahanu Pradhan, student of class

XII (Computer Sc.) of Kendriya Vidyalaya Kandhamal has

developed the project “EMPLOYEE MANAGEMENT

SYSTEM” under the guidance of Mr. Nabakishore Sethi , PGT,

Computer Science of Kendriya Vidyalaya Kandhamal.

As a partial fulfillment of the academic curriculum, they have worked

on this project successfully.

External Examiner Internal Examiner

Date: Date:
P a g e | 63

BIBLIOGRAPHY

1. Computer Science with Python by Sumita Arora

2. Introduction to Computer Science using Python by


Charles Dierbach

3. Problem Solving and Python Programming by Kulkarni

4. Python Crash Course’ by Eric Matthews

5. Head-First Python’ by Paul Barry

6. www.w3schools.com/ for python tutorial

7. www.programiz.com for python programming

8. www.geeksforgeeks.org/ for python programming

9. www.python-course.eu for python programming

10. www.tutorialspoint.com/ for python programming

You might also like