Computer Science (Sidharth)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

KENDRIYA VIDYALAYA RAILWAY

GANDHIDHAM

Project Work In
PYTHON TUTORIALS (Code No - 083 )
2019 – 20

SUBMITTED BY:

Name: SIDHARTH SURESH KUMAR


Roll No:
1
Class: XII SCIENCE

CERTIFICATE

This is to certify that the PYTHON TUTORIAL Project work has been successfully
completed by Mr.SIDHARTH SURESH KUMAR .Roll No. ___________ of class XII
SCIENCE during the academic session 2019 – 20.

Examiner No:
Date:

Teacher In-Charge External Examiner

Principal

2
ACKNOWLEDGEMENT

It is profound privilege to express my deep sense of gratitude towards our school


Kendriya Vidyalaya Railway Gandhidham.

I would also like to thank our respected Principal Mr. Chandan Singh Pilkhwal for their
encouragement and appreciation.

I wish to extend my gratitude in all sincerity to our teacher Mr. VINAY KUMAR
CHAUHAN who gave me an opportunity to work under his guidance. He has been a
constant source of inspiration and without his valuable guidance the project would not
have been successful. I would also like to thank our other teachers and staff members
who provided me help and support regarding this project.

At last, I am also thankful to all my classmates who helped me with whole heartedness
during the development of the project.

3
CONTENTS

___________________________

1. USER DEFINED MODULE FUNCTION

2. TEXT FILE

3. WORKING DESCRIPTION

4. SOURCE CODE

5. INPUT/OUTPUTINTERFACE

6. BIBLIOGRAPHY

4
MODULE FUNCTIONS

# FUNCTION
def l_s(ar,item): #l_s is used to find the index of item in the list

i=0

while i < len(ar) and ar[i]!=item :

i+=1

if i< len(ar):

return i

else:

return False # if i>len(ar)

def b_s(ar,item):

beg=0

last=len(ar)-1 #last item from list will be inserted in last

while(beg<=last):

mid= (beg+last)/2

if (item == ar[mid]):

return mid

5
elif (item >ar[mid]):

beg=mid+1

else:

last= mid-1

else:

return False #when item not found

def Findpos(ar,item): #Findpos is used finding element position in list

size=len(ar)

if item<ar[0]:

return 0

else:

pos=-1

for i in range (size-1):

if (ar[i]<=item and item < ar[i+1]):

pos=i+1

break

if (pos==-1 and i<=size-1):

pos = size

return pos

def shift(ar,pos): #for shifting element position

ar.append(None) # add an empty element at an end

size = len(ar)

6
i=size-1

while i>=pos:

ar[i]=ar[i-1]

i=i-1

def s_sort(liste): #s_sort is used to sort list

for curpos in range(len(liste)):

minpos=curpos #starting with current position

for scanpos in range(curpos+1,len(liste)):

if liste[scanpos]<liste[minpos]:

minpos=scanpos

#Swap the two values

temp=liste[minpos]

liste[minpos]=liste[curpos]

liste[curpos]=temp

def swapelements(list): #the elements will get swapped

i=0

while (i<len(list)-1):

if (list[i]>list[i+1]):

temp=list[i]

list[i]=list[i+1]

list[i+1]=temp

i=i+1

7
#print( " List after pass",(i), ":",list)

def b_sort(list): #original list will get swapped

for num in range(len(list)-1):

pass

swapelements(list)

def i_sort(ar): #it will sort original list when max. size is >50

for i in range(1,len(ar)):

v=ar[i]

j=i

while ar[j-1]> v and j>=1:

ar[j]=ar[j-1]

j-=1

#Insert the value at its correct postion

ar[j]=v

def traverse(ar): #this function is used for traversing ar

size =len(ar) #len() is used for calculating length of ar

for i in range(size):

print (ar[i],)

def isempty(stk):

if stk==[]:

return True

else:

8
return False

def push(stk,item): #to push item in stk

stk.append(item)

top=len(stk)-1

def pop(stk): #pop function is used for removing topmost element in stk

if isempty(stk):

return "Underflow"

else:

item=stk.pop()

if len(stk)==0:

top=None

else:

top=len(stk)-1

return item

def peek(stk):

if isempty(stk):

return ("Underflow")

else:

top=len(stk)-1

return stk[top]

def display(stk): # display is used for displaying stk

if isempty(stk):

9
return "Stack empty"

else:

top=len(stk)-1

print ( stk[top],"<-top")

for a in range(top-1,-1,-1):

print (stk[a])

def cls(n):#cls is used for clear screen

print (" "*n )

def qu_isempty(qu): #qu_isempty is used for empty queue

if qu==[]:

return True

else:

return False

def qu_enqueue(qu,item): #for appending element enqueue is used

qu.append(item)

if len(qu)==1:

front=rear=0

else:

rear=len(qu)-1

def qu_peek(qu): #peek shows top element in stk

if qu_isempty(qu):

return "Underflow"

10
else:

front=0

return qu[front]

def qu_dequeue(qu): # it will delete top element in stk

if qu_isempty(qu):

return "Underflow"

else:

item=qu.pop()

if len(qu)==0:

front=rear=None

return item

def qu_display(au):

if qu_isempty(qu):

print (" QueUE Empty")

elif len(qu)==1:

print ([qu],"<== front,rear")

else:

front=0

rear=len(qu)-1

print (qu[front],"<- front")

for a in range(1,rear):

print (qu[a])

11
print (qu[rear],"<-rear")

def s():

print ("------------------------------------")

TEXT FILES USED

1. ERROR.txt
_______________________ExceptionHandling________________
Error handling in Python is done through the use of exceptions that are
caught in try blocks and handled in except blocks. Syntax:::
try:
# statement that may raise error
except:
# handle exception here
finally:
# statement that will always run

####Try and Except ::-

12
If an error is encountered, a try block code execution is stopped and
transferred
down to the except block. In addition to using an except block after the
try block, you can also use the finally block. The code in the finally block
will be executed regardless of whether an exception
occurs.

##Raising an Exception
You can raise an exception in your own program by using the raise exception
[, value] statement. Raising an exception breaks current code execution and
returns the exception
back until it is handled.

Example: A try block look like below


try:
print ("Hello World")
except:
print ("This is an error message!")

___________________Some Exceptions______________________

EXCEPTION NAME DESCRIPTION

OverflowError() Raised when a calculation exceeds maximum limit for a


numeric type.

0ZeroDivisonError() Raised when division or modulo by zero takes place


for all numeric types.

EOFError() Raised when there is no input from either the raw_input()


or input()function and the end of file is reached.
ImportError() Raised when an import statement fails.

13
IndexError() Raised when an index is not found in a sequence.

NameError() Raised when an identifier is not found in the local or global


namespace.

IOError() Raised when an input/ output operation fails, such as the


print statement or the open() function when trying to
open a file that does not exist.
TypeError() Raised when an operation or function is attempted that is
invalid for the specified data type.

ValueError() Raised when the built-in function for a data type has the
valid type of arguments, but the arguments have invalid
values specified.

______________________Generators______________________

A generator is simply a function which returns an object on which you can


call next, such that for every call it returns some value, until it raises a
StopIteration exception, signaling that all values have been generated.
Such an object is called an iterator.
Normal functions return a single value using return, just like in Java. In
Python, however, there is an alternative, called yield. Using yield anywhere
in a function makes it a generator

EXAMPLE:
>>> def myGen(n):
... yield n
... yield n + 1
...
>>> g = myGen(6)
>>> next(g)
6
>>> next(g)
14
7

2. R_W.txt
__________________Opening and Closing____________________

The first thing to do when you are working with files in Python isto open
thefile. When you open the files, you can specify with parameters how you
want to open them.

The "r" is for reading, the "w" for writing and the "a" for appending.

This opens the filename for reading. By default, the file is opened with the
"r" parameter.

fh = open("filename_here", "r")

This opens the fhe file for writing.

It will create the file if it doesn't exist, and if it does, it will overwrite it.

fh =open("filename_here", "w")

This opens the fhe file in appending mode.

That means, it will be open for writing and everything will be written to the

end of the file.

fh =open("filename_here", "a")

#This closes the file and is used when the program doesn't need it more.

15
fh.close()

__________________Reading and Writting ______________________

###Reading from file

Functions available for reading the files: read, readline and readlines.

-----Read---

The read function reads all characters (unless you specify other)

eg.

fh = open("filename", "r")

content = fh.read()

---Readline---

The readline function reads a single line from the file

eg.

fh = open("filename", "r")

content = fh.readline()

----Readlines----

The readlines function returns a list containing all the lines of data in the

16
file.The readlines function reads all rows and retains the newlines
character that is

at the end of every row.

eg.

fh = open("filename", "r")

content = fh.readlines()

print( content.rstrip())

print (content[:-1])

### Writting from files

The functions for writing are write and writelines

---Write---

To write a fixed sequence of characters to a file

eg.

fh = open("hello.txt","w")

write("Hello World")

----Writeline----

With the writeline function you can write a list of strings to a file

eg.

fh = open("hello.txt", "w")

lines_of_text = ["a line of text", "another line of text", "a third line"]
17
fh.writelines(lines_of_text)

3. M_FUN.txt
_________________Function defined in module___________________

A module allows you to logically organize your Python code. Grouping related
code into a module makes the code easier to understand and use. A module
is a Python object with arbitrarily named attributes that you can bind and
reference.

Simply, a module is a file consisting of Python code. A module can define


functions, classes and variables. A module can also include runnable code.

Example:

The Python code for a module named aname normally resides in a file named
aname.py. Here's an example of a simple module, support.py

def print_func( par ):

print ("Hello : ", par)

return

The import Statement

You can use any Python source file as a module by executing an import
statement in some other Python source file. The import has the following
syntax:

import module1[, module2[,... moduleN]

18
When the interpreter encounters an import statement, it imports the
module if the module is present in the search path. A search path is a list
of directories that the interpreter searches before importing a module.
For example, to import the module hello.py, you need to put the following
command at the top of the script -

# Import module support

>>>import support

# Now you can call defined function that module as follows

support.print_func("Zaira")

When the above code is executed, it produces the following result -

>>>Hello : Zaira

A module is loaded only once, regardless of the number of times it is


imported. This prevents the module execution from happening over and
over again if multiple imports occur.

4. S_FUN.txt
________________String Manipulation Methods_____________

1. string.capitalize():

Returns a copy ofstring with first characcter capitalised.

2. upper string. ():

Return a copy of s, but with lower case letters converted to upper case
19
3.string.lstrip(s[, chars]):

Return a copy of the string with leading characters removed. If chars is


omitted or None, whitespace characters are removed. If given and not
None, chars must be a string; the characters in the string will be stripped
from the beginning of the string this method is called on.

4.string.rstrip(s[, chars]):

Return a copy of the string with trailing characters removed. If chars is


omitted or None, whitespace characters are removed. If given and not
None, chars must be a string; the characters in the string will be stripped
from the end of the string this method is call.

5.string.lower(s):

Return a copy of s, but with upper case letters converted to lower case.

6.string.find(s, sub[, start[, end]]):

Return the lowest index in s where the substring sub is found such that sub
is wholly contained in s[start:end]. Return -1 on failure. Defaults for start
and end and interpretation of negative values is the same as for slices.

7.string.islower(): This method checks if the string is in lowercase and


returns true if all the characters are in lowercase.

8.string.isupper(): This method checks if all the characters in the string


are in uppercase. If any character is in lower case, it would return false
otherwise true.

5. D_T.txt
____________________DATA STRUCTURES____________________

20
Python offers 5 different types of data structure.

1. ARRAY:
Array refers to a named list of finite number n of similar data elements.
Each of the data elements can be referenced respectively by a set of
consecutive numbers, usually 0,1,2,3,4 . . . n .

e.g.

A array ar containing 10 elements will be referenced as

ar[0],ar[1] ,ar[2] . . . ar[9]

2. STACKS:

Stacks data structure refer to list stored and accessed in a special way,

where LIFO(Last In First Out) technique is followed. In stack insertion and


deletion take place at only one end called the top.

3. QUEUES:

Queues data structure are FIFO(First In First Out ) lists , where

take place at "rear" end of queue deletions take place at the "front" end

of the queue.

4. LINKED LIST:

Linked lists are special list of some data elements linked to one another.
The logical ordering is represented by having each element pointing to
next element. Each element is called a 'node' which has the parts.

The INFO part which stores the information and the reference pointer
part i.e stores reference of next element.

21
5.Trees:

Trees are multilevel data structures having a hierarchical relationship


amongstits element called 'node'. Topmost node is called node of the tree
and bottom most node of tree is called leaves of tree. Each node have some
reference pointerspointing to node below it.

WORKING DESCRIPTION

This following program is designed to teach a new beginners to code simple


program with python.

This program consists of 9 options

1. Working with Stings

2. Simple Input and Output Statements

3. Python Functions and Modules

4. Loops in Python

5. Data Types and Usage

6. Linear list Manipulation

7. Stacks and Queues

8. Data File Handling

9. Exception handling and Generators in python

22
SOURCE CODE

"""This mini project is created to teach new beginners how to program and
learn about python program """
try:
from LLM import *
except ImportError:
print( "Module Not imported")

# MAIN
con=True
while con:
print ("#############")
print (" ")
print (" PYTHON TUTORIAL ")
print( " " )
print( "################")
print (" ")
print (“ Welcome to python tutorial!!!!!!!!")
print ( " ")
print (" 1. GET STARTED with PYTHON")
print (" 2. ABOUT PYTHON AND PROJECT")
print (" 3. EXIT")
try:
i1=input("enter your choice(1-3):")
except IOError:
print (" No Input!")
print (" ")
print ("PROGRAM WILL RESTART")
cls(2)
23
if i1==1:
con2=True
while con2:
cls(2)
print (" Lets start with python")
print ("Choose anyone of the module to start")
cls(2)
print( " 1. Working with Srings")
print (" 2. Simple Input and Output Statements")
print (“ 3. Python Functions and Modules")
print (" 4. Loops in Python")
print (" 5. Data Types and Usage")
print (" 6. Linear list Manipulation")
print (" 7. Stacks and Queues")
print (" 8. Data File Handiling")
print (" 9. Exception handiling and Generators in python")
print ("10. Get back to main menu")
try:
i2=input("Enter your choice(1-10): ")
except IOError:
print (" No input given")
if i2==1: # String OPerations
con3=True
while con3:
cls(2)
s()
print ("Strings :-A data type are any number of valid
characters into a set of quotion marks.")
print ("Operations that can be performed with string are::")
print ("1.Traversing of string")
print ("2.String opeartors on string")
print ("3.String Functions")
print ("4.Slicing a string")
print ("5.Get Back to previous menu")
24
try:
i3=input("Enter your choice(1-5):")
except IOError:
print ("No input given")
if i3==1:
print ("Traversing can be performed in a following way")
a="Python"
print (">>>a='Python'")
print (">>>for i in a:")
print (“ print i,'-'")
print ("_______________")
for i in a :
print (i,"-",)
print()
print (" *** ")
raw_input("Press Enter to Continue")
elif i3==2:
print ("String operators are"
print ("1.String Concatenation operator (+):")
print (" eg.")
print (“ 'ram' + 'shayam'")
print (" will result into")
print (" 'ramshayam' ")
print ("2. String replication operator (*):")
print (" e.g.")
print (" 'DSS'*3")
print (" will result into ")
print (" 'DSSDSSDSS'")
print ("3. Membership operator:")
print ("in : Returns True if sub string exist in given string,
otherwise False")
print ("not in: Returns True if sub string not exist in given
string, otherwise False")

25
print (" e.g.")
print (" >>> 'a' in 'ram'")
print ("True")
print (" >>> 'a' not in 'ram'")
print ("4.Comparison operator(<,>,>=,<=,==,!=):")
print (" e.g.")
print (" 'a'=='a' will give True")
print (" 'a'=="b" will give False")
raw_input("Press Enter to Continue")
elif i3==3:
q=open("S_FUN.txt")
w=q.read()
print (w)
del q,w
raw_input("Press Enter to Continue")
elif i3==4:
cls(2)
print ("Slicing a string can be performed as follow,")
print ("")
print (">>a=ramayan")
a='ramayan'
print (">>>print a[0:3]")
print (" "),a[0:3]
raw_input("Press Enter to Continue")
elif i3==5:
con3=False
else:
print( "Invalid input !!!!!!!!!!!")
elif i2==2: #Simple I/O Statement
print ( "Simple input and output statement can be given using")
print ("1. For input :")
print (" 1.input() and")
print (" 2.raw_input()")
print (" Following are sample programs to illustrate")
26
print (" eg.")
print (" >>> a=raw_input('Enter your number:' )")
print (" Enter your number: 25")
cls(2)
print ("2.For output Python use 'print' key word")
print ("")
print (">>>For i in 'Python':")
print (" print i ") # print is output keyword
print (" Output will be as")
print (" P \n y\n t\n h\n o\n n\n")
raw_input("Press Enter to continue...")
elif i2==3: # Functions and modules
con4=True
while con4:
print( "Python offers 3 type of Functions")
print ("1.In-built functions")
print ("2.Function defined in Modules")
print ("3.User defined functions")
print ("4.Get back to previous menu")
try:
i4=input(" Enter your choice(1-4):")
except IOError:
print ("No input provided")
if i4==1:
print ("Python offers some built-in functions which are
always available to use")
print (" eg. len(),type(),int()")
cls(2)
print( ">>> a=Python")
print( ">>>len(a)")
print (" 6")
raw_input("Press Enter to continue...")
elif i4==2:
q=open("M_FUN.txt")
27
w=q.read()
print (w)
q.close()
del q,w
raw_input("Press Enter to continue...")
elif i4==3:
print ("These are the functions defined by programmer.
And can be defined using 'def' keyword. ")
print ("How to create a function is illustrated in following
example")
print ()
print( "def sum(x,y):")
print (" r= x+y")
print (" return r")
print ("a=input('Enter number1:')")
print ("b=input('Enter number 2:)")
print ("c=sum(a,b)")
print ("print c")
raw_input("Press Enter to continue...")
elif i4==4:
con4=False
else:
print ("Invalid in put")
elif i2==4:
con5=True
while con5:
print ("Python offers 2 type of loop statement")
print ("1. The for loop")
print ("2. The while loop")
print ("3. Get back to previous menu")
try:
i4=input("Enter your choice(1-3):")
except IOError:
print( "No input provided ")
28
if i4==1:
print ("The general form of 'for loop' is as given below:")
print (" for <variable> in <sequence> :")
print (" statements_to_repeat")
cls(2)
print ("eg.")
print (" for element in [10,15,20,25]:")
print (" print (element +2),")
print ("Or for loop can be also used wiht range()function")
print ("eg.")
print (" for val in range(3,10):")
print (" print val")
elif i4==2:
print( "The general form of while loop is given below")
print (" while <logical Expression>:")
print( " loop-body")
elif i4==3:
con5=False
else:
print( "Invalid Input")
elif i2==5:
try:
e=file("D_T.txt")
w=e.read()
print (w)
except EOFError:
print ("Error in file opening")
del e,w
raw_input("Press Enter to continue...")
elif i2==6:
con6=True
while con6:
print( " Basic operations on Linear list")
print ("1.Searching”)
29
print ("2.Insertion")
print ("3.Deletion")
print ("4.Traversal")
print ("5.Sorting")
print ("6.Return to previous menu")
try:
i6=input("Enter your choice(1-6):")
except:
print " InputError!!!!"
if i6==1:
con7=True
while con7:
print ("Python offers 2 type of common searching
technique")
print ("1.Linear search")
print ("2.Binary search")
print( "3.Return to previous menu")
try:
i7=input("Enter your choice(1-3)")
except IOError:
print ("Input error")
if i7==1:
print ("____________Linear list________”)
print("In linear search each element of array with the
given Item to be searched for, one by one")
print ("Following program illustrate searching by linear
search")
n=input("Enter desired linearlist(max.50)..")
print( "\nEnter elements for linear list\n")
ar=[0]*n # initialize list of size n with zeros
for i in range(n):
ar[i]=input("Element" +str(i+1) +":")
item=input("\Enter element to be searched for...")
index = l_s(ar,item)
30
if index :
print( "\nElement found at
index:",index,",position:",(index+1))
else:
print ("\nSorry!! Givn element not found\n")
raw_input("Press Enter to continue...")
elif i7==2:
print( "___________Binary search____________”)
print( " Binary search can work for any sorted array
while linear search can work for both sorted as
well as unsorted array")
n=input("Enter desired linear-list size(max. 50)..")
ar=[0]*n
for i in range(n):
ar[i]=input("Element"+str(i+1)+":")
s_sort(ar)
print ("\List after sorting",ar)
item=input("\nEnter Element to be searched for...")
index=b_s(ar,item)
if index :
print( "\nElement found at
index:",index,",position:",(index+1))
else:
print( "\nSorry!! Givn element not found\n")
raw_input("Press Enter to continue...")
elif i7==3:
con7=False
else:
print( " Invalid input")
del i7,con7
elif i6==2:
print( "____________Insertion in a list _________")
n=input("Enter desired linear-list size(max. 50)..")
ar=[0]*n
31
for i in range(n):
ar[i]=input("Element"+str(i+1)+":")
s_sort(ar)
print ("List in sorted order is",ar)
item=input("Enetr new element to be inserted:")
position=Findpos(ar,item)
shift(ar,position)
ar[position]=item
print ("The list after inserting",item,"is")
print (ar)
raw_input("Press Enter to continue...")
elif i6==3:
print( "____________Deletion in a list ___________”)
n=input("Enter desired linear-list size(max. 50)..")
ar=[0]*n
for i in range(n):
ar[i]=input("Element"+str(i+1)+":")
s_sort(ar)
print "List in sorted order is",ar
item=input("Enter new element to be deleted:")
position=b_s(ar,item)
if position:
del ar[position]
print( "The list after deletion",item,"is")
print( ar)
else:
print ("SORRY! No such element in the list")
raw_input("Press Enter to continue...")
elif i6==4:
print ("__________ Traversal of list ______________”)
n=input("Enter desired linear-list size(max. 50)..")
ar=[0]*n
print( "Enter element for the linear list")
for i in range(n):
32
ar[i]=input("Element"+str(i+1)+":")
print( "Traversing the list:")
traverse(ar)
raw_input("Press Enter to continue...")
elif i6==5:
print ("Python offers 3 type of common sorting technique")
print ("1.Selection sort")
print ("2.Bubble sort")
print ("3.Insertion sort")
try:
i7=input("Enter your choice(1-3):")
except IOError:
print ("Input error")
if i7==1:
print ("____________Selection sort ____________")
print ()
print( " The basic idea of selection sort is to repeatedly
select the smallest key in remaining us sorted
array")
print (" The following program illustrate the sorting by
selection sort")
n=input("Enter desired linear-list size(max. 50)..")
ar=[0]*n
print ("Enter element for the linear list")
for i in range(n):
ar[i]=input("Element"+str(i+1)+":")
print ("Original list is:",ar)
s_sort(ar)
print ("List after sorting:",ar)
raw_input("Press Enter to Continue")
elif i7==2:
print ("__________Bubble sort ______________”)
print

33
print( "The basic idea of bubble sort is to compare two
adjoining values and exchange them if they are not
in proper order.")
print (" The following program illustrate the sorting by
Bubble sort")
n=input("Enter desired linear-list size(max. 50)..")
ar=[0]*n
print ("Enter element for the linear list")
for i in range(n):
ar[i]=input("Element"+str(i+1)+":")
print ("Original list is:",ar)
b_sort(ar)
print ("List after sorting:",ar)
raw_input("Press Enter to Continue")
elif i7==3:
print ("_____________Insertion sort______________”)
print()
print( "Suppose an array A with n elements
a[1],A[2],...,A[N} is in memory. The insertion sort
algorithm scans A from A[1]to A[N],insertion each
element A[K]into is proper position in the previously
sorted sub array A[1],A[2]...,A[K-1].")
print( " The following program illustrate the sorting by
Insertion sort")
n=input("Enter desired linear-list size(max. 50)..")
ar=[0]*n
print ("Enter element for the linear list")

for i in range(n):
ar[i]=input("Element"+str(i+1)+":")
print ("Original list is:",ar)
i_sort(ar)
print ("List after sorting:",ar)

34
else :
print( "Invalid input!!!!")
del i7
elif i6==6:
con6=False
else:
print ("Invalid Input")

elif i2==7:
con8=True
while con8:
print( "1.Stacks")
print ("2.Queues")
print ("3.Return to previous menu")
try:
i7=input("Enter your choice(1-3)")
except IOError:
print( "Input error")
if i7==1:
print ("Python program to illustrate Stack operation")
#######STACK IMPLEMENTAION #######
"""
Stack: implemented as a list
top: Integer having topmost element in a stack
"""
stack=[]
top=None
co=1
while co==1:
print( “STACK OPERATIONS")
print ("1.Push")
print ("2.Pop")
print ("3.Peek")
print( "4.Display stack")
35
print ("5.Exit")
try:
ch=input("Enter your choice(1-5):")
except IOError:
print ("Input error")
if ch==1:
try:
item=input("Enter item:")
except IOError:
print ("Input error")
push(stack,item)
elif ch==2:
item=pop(stack)
if item=="Underflow":
print ("Underflow! Stack is empty!")
else:
print ("Popped item is",item)

elif ch==3:
item=peek(stack)
if item=="Underflow":
print( "Underflow! Stack is empty!")
else:
print ("Topmost item is",item)
elif ch==4:
display(stack)
elif ch==5:
co=0
else:
print ("Invalid INPUT")
else:
print (“Invalid choice!")
elif i7==2:
print ("Python program to illustrate queue operation")
36
##### QUEUE IMPLEMENTAION ##########

queue: implemented as a list


front: Integer having position if first (front most)element in queue
rear: integer having position of last element in queue
"""
queue=[]
front=None
b=True
while b:
print("QUEUE OPERATIONS")
print ("1.Enqueue")
print ("2.Dequeue")
print ("3.Peek")
print ("4.Display queue")
print( "5.Exit")
try:
ch=input("Enter your choice(1-5):")
except IOError:
print ("Input error")
if ch==1:
try:
item=input("Enter item:")
except IOError:
print( "Input error")
qu_enqueue(queue,item)
raw_input("Press Enter to continue....")
elif ch==2:
item=qu_dequeue(queue)
if item=="Underflow":
print( "Underflow! Queue is empty!")
else:
print( "Deueue-ed item is",item)
raw_input("Press Enter to Continue.....")
37
elif ch==3:
item=qu_peek(queue)
if item=="Underflow":
print( "Underflow! Queue is empty!")
else:
print( "Frontmost item is",item)
raw_input("Press Enter to continue...")
elif ch==4:
display(queue)
raw_input("Press Enter to continue...")
elif ch==5:
b=False
else:
print("Invalid choice!")
raw_input("Press Enter to continue...")

elif i7==3:
con8=False
else:
print( "Invalid Input")

elif i2==8:
con9=True
while con9:
print ("__________ DATA FILE HANDILING__________”)
print( "1. Opening and closing a file")
print ("2. Reading and Writing onto files")
print ("3. Return to previous menu")

try:
i7=input("Enter your choice(1-3):")
except IOError:
print( "Input error")
if i7==1:
38
a=open("R_W.txt")
b=a.read(837)
print b
a.close()
del a,b
raw_input("Press Enter to continue...")
elif i7==2:
a=open("R_W.txt")
b=a.read(837)
c=a.read(1900)
print(c)
a.close()
del a,b,c
print( " ")
raw_input("Press Enter to continue...")
elif i7==3:
con9=False
else:
print ("Invalid input")
del i7,con9
elif i2==9:
con10=True
while con10:
print ("1.Exception Handling")
print ("2.Generators")
print("3.Return to previous menu")
try:
i7=input("Enter your choice(1-3)")
except IOError:
print( "Input error")
if i7==1:
a=open("ERROR.TXT")
b=a.read(2235)
print(b)
39
a.close()
del a,b
elif i7==2:
a=open("ERROR.TXT")
b=a.read(2235)
c=a.read(9999)
print (c)
a.close()
del a,b,c
elif i7==3:
con10=False
else:
print ("Invalid Input")
elif i2==10:
con2=False
else:
print(" Invalid input!")
elif i1==2:
cls(2)
a=open("ABOUT.txt")
b=a.read()
a.close()
print (b)
del a,b
cls(2)
print ("**********************************************")
elif i1==3:
con=False
print( "Thank u for using program")
else:
print(" ")
print (" INVALID INPUT !!!!")
print ( " ")
print( "PROGRAM WILL RESTART")
40
for i in range (10000):
a=i
del a

41
INPUT / OUTPUT INTERFACE

42
43
44
45
46
47
48
49
50
51
52
BIBLIOGRAPHY

1. Sumita Arora (Python)


2. www.python.com
3. www.stackoverflow.com

53

You might also like