Computer Science (Sidharth)
Computer Science (Sidharth)
Computer Science (Sidharth)
GANDHIDHAM
Project Work In
PYTHON TUTORIALS (Code No - 083 )
2019 – 20
SUBMITTED BY:
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:
Principal
2
ACKNOWLEDGEMENT
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
___________________________
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
i+=1
if i< len(ar):
return i
else:
def b_s(ar,item):
beg=0
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:
size=len(ar)
if item<ar[0]:
return 0
else:
pos=-1
pos=i+1
break
pos = size
return pos
size = len(ar)
6
i=size-1
while i>=pos:
ar[i]=ar[i-1]
i=i-1
if liste[scanpos]<liste[minpos]:
minpos=scanpos
temp=liste[minpos]
liste[minpos]=liste[curpos]
liste[curpos]=temp
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)
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
ar[j]=ar[j-1]
j-=1
ar[j]=v
for i in range(size):
print (ar[i],)
def isempty(stk):
if stk==[]:
return True
else:
8
return False
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]
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])
if qu==[]:
return True
else:
return False
qu.append(item)
if len(qu)==1:
front=rear=0
else:
rear=len(qu)-1
if qu_isempty(qu):
return "Underflow"
10
else:
front=0
return qu[front]
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):
elif len(qu)==1:
else:
front=0
rear=len(qu)-1
for a in range(1,rear):
print (qu[a])
11
print (qu[rear],"<-rear")
def s():
print ("------------------------------------")
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
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.
___________________Some Exceptions______________________
13
IndexError() Raised when an index is not found in a sequence.
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______________________
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")
It will create the file if it doesn't exist, and if it does, it will overwrite it.
fh =open("filename_here", "w")
That means, it will be open for writing and everything will be written to the
fh =open("filename_here", "a")
#This closes the file and is used when the program doesn't need it more.
15
fh.close()
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---
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
eg.
fh = open("filename", "r")
content = fh.readlines()
print( content.rstrip())
print (content[:-1])
---Write---
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.
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
return
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:
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 support
support.print_func("Zaira")
>>>Hello : Zaira
4. S_FUN.txt
________________String Manipulation Methods_____________
1. string.capitalize():
Return a copy of s, but with lower case letters converted to upper case
19
3.string.lstrip(s[, chars]):
4.string.rstrip(s[, chars]):
5.string.lower(s):
Return a copy of s, but with upper case letters converted to lower case.
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.
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.
2. STACKS:
Stacks data structure refer to list stored and accessed in a special way,
3. QUEUES:
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:
WORKING DESCRIPTION
4. Loops 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 ##########
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
53