Computer
Computer
FUNCTIONS IN PYTHON
1.1 Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.
Built in functions
Functions defined in
Types of functions modules
1. Library Functions: These functions are already built in the python library.
3. User Defined Functions: The functions those are defined by the user are called user
defined functions.
Example:
import random
n=random.randint(3,7)
Page 3
Where:
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
One or more valid python statements that make up the function body. Statements must
have same indentation level.
An optional return statement to return a value from the function.
Example:
def display(name):
Page 4
1.4 Calling the function:
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
… .. …
… .. …
OUTPUT:
(7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
print(s1, s2, s3)
OUTPUT:
7 7 11
b. Function not returning any value (void function) : The function that performs some
operationsbut does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
Page 6
OUTPUT:
Hello
None
Scope of a variable is the portion of a program where the variable is recognized. Parameters
and variables defined inside a function is not visible from outside. Hence, they have a local
scope.
1. Local Scope
2. Global Scope
1. Local Scope: Variable used inside the function. It can not be accessed outside the function.
In this scope, The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a
variable is the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
Page 7
Here, we can see that the value of x is 20 initially. Even though the function my_func()changed
the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the one
outside. Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables
using the keyword global.
1+ 1!
+ 2!
+ 3!
+⋯+ !
Solution:
def fact(x):
j=1
res=1
while j<=x:
res=res*j
j=j+1
return res
n=int(input("enter the number : "))
i=1
sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)
2. Write a program to compute GCD and LCM of two numbers
def gcd(x,y):
while(y):
x, y = y, x % y
return x
FILE HANDLING
3.1 INTRODUCTION:
File:- A file is a collection of related data stored in a particular area on the disk.
Stream: - It refers to a sequence of bytes.
File handling is an important part of any web application.
3.2 Data Files:
Data files can be stored in two ways:
1. Text Files: Text files are structured as a sequence of lines, where each line includes a
sequence of characters.
2. Binary Files : A binary file is any type of file that is not a text file.
S.
No. Text Files Binary Files
Example:
To open a file for reading it is enough to specify the name of the file:
f = open("book.txt")
The code above is the same as:
f = open("book.txt", "rt")
Where "r" for read mode, and "t" for text are the default values, you do not need to specify
them.
Text Binary
file File Description
mode Mode
‘r’ ‘rb’ Read - Default value. Opens a file for reading, error if the file does not
exist.
‘w’ ‘wb’ Write - Opens a file for writing, creates the file if it does not exist
‘a’ ‘ab’ Append - Opens a file for appending, creates the file if it does not exist
‘r+’ ‘rb+’ Read and Write-File must exist, otherwise error is raised.
‘x’ ‘xb’ Create - Creates the specified file, returns an error if the file exists
Page 14
In addition you can specify if the file should be handled as binary or text mode
“t” – Text-Default value. Text mode
“b” – Binary- Binary Mode (e.g. images)
Print/Access data
Page 15
Let a text file “Book.txt” has the following text:
“Python is interactive language. It is case sensitive language.
It makes the difference between uppercase and lowercase letters.
It is official language of google.”
OUTPUT: OUTPUT:
Python is interactive language. It is case sensitive Python is
language.
It makes the difference between uppercase and
lowercase letters.
It is official language of google.
fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read()
L=str.split()
count=0
for i in L:
if i=='is':
count=count+1
print(count)
fin.close( )
To write the data to an existing file, you have to use the following mode:
Page 18
Example: Open the file "Book.txt" and append content to the file:
fout= open("Book.txt", "a")
fout.write("Welcome to the world of programmers")
Example: Open the file "Book.txt" and overwrite the content:
fout = open("Book.txt", "w")
fout.write("It is creative and innovative")
Program: Write a program to take the details of book from the user and write the record
in text file.
fout=open("D:\\python programs\\Book.txt",'w')
n=int(input("How many records you want to write in a file ?:"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :3
Enter details of record : 1
Enter the title of book : java
Enter price of the book: 250
Enter details of record : 2
Enter the title of book : c++
Enter price of the book: 300
Enter details of record : 3
Enter the title of book : python
Enter price of the book: 450
c. Append the data to a file:
This operation is used to add the data in the end of the file. It doesn’t overwrite the existing
data in a file. To write the data in the end of the file, you have to use the following mode:
Page 19
"a" - Append - will append to the end of the file.
Program: Write a program to take the details of book from the user and write the record
in the end of the text file.
fout=open("D:\\python programs\\Book.txt",'a')
n=int(input("How many records you want to write in a file ?
:")) for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :2
Enter details of record : 1
Enter the title of book : DBMS
Enter price of the book: 350
Enter details of record : 2
Enter the title of book : Computer
Networking
Enter price of the book: 360
d. Delete a file: To delete a file, you have to import the os module, and use remove( )
function.
import os
os.remove("Book.txt")
Page 20
import os
if os.path.exists("Book.txt"):
os.remove("Book.txt")
else:
print("The file does not exist")
Output:
Page 21
Output:
Once upon a time
Output: 14
seek(offset) : Change the cursor position by bytes as specified by the offset.
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )
Output: 5
3.8 File I/O Attributes
Attribute Description
name Returns the name of the file (Including path)
mode Returns mode of the file. (r or w etc.)
encoding Returns the encoding format of the file
closed Returns True if the file closed else returns False
Page 22
Example:
f = open("D:\\story.txt", "r")
print("Name of the File: ", f.name)
print("File-Mode : ", f.mode)
print("File encoding format : ", f.encoding)
print("Is File closed? ", f.closed)
f.close()
print("Is File closed? ", f.closed)
OUTPUT:
Name of the File: D:\story.txt
File-Mode : r
File encoding format : cp1252
Is File closed? False
Is File closed? True
DATA STRUCTURE-I (LINEAR LIST)
7.1 INTRODUCTION:
Definition: The logical or mathematical model of a particular organization of data is called
data structure. It is a way of storing, accessing, manipulating data.
DATA STRUCTURE
LINKED
ARRAY STACK QUEUE TREE GRAPH
LIST
1. Linear data structure: It is simple data structure. The elements in this data structure creates
a sequence. Example: Array, linked list, stack, queue.
2. Non-Linear data structure: The data is not in sequential form. These are multilevel data
structures. Example: Tree, graph.
Page 45
7.3 OPERATION ON DATA STRUCTURE:
There are various types of operations can be performed with data structure:
1. Traversing: Accessing each record exactly once.
2. Insertion: Adding a new element to the structure.
3. Deletion: Removing element from the structure.
4. Searching: Search the element in a structure.
5. Sorting: Arrange the elements in ascending and descending order.
6. Merging: Joining two data structures of same type. (not covered in syllabus)
Output:
10
20
30
40
50
b. Inserting Element in a list: There are two ways to insert an element in a list:
(i) If the array is not sorted
(ii) If the array is sorted
Page 46
(i) If the array is not sorted: In this case, enter the element at any position using insert(
) function or add the element in the last of the array using append( ) function.
Example:
L=[15,8,25,45,13,19]
L.insert(3, 88) # insert element at the index 3
print(L)
Output:
[15, 8, 25, 88, 45, 13, 19]
(ii) If the array is sorted: In this case, import bisect module and use the functions bisect( )
and insort( ).
bisect( ) : identifies the correct index for the element and returns the
index. insort( ): Inserts the element in the list in its correct order.
Example:
import bisect
L=[10,20,30,40,50]
print("Array before insertion the element:", L)
item=int(input("Enter the element to insert in array: "))
pos=bisect.bisect(L,item) #will return the correct index for item
bisect.insort(L,item) #will insert the element
print("Element inserted at index: ", pos)
print("Array after insertion the element : ", L)
OUTPUT:
Array before insertion the value: [10, 20, 30, 40, 50]
Enter the element to insert in array: 35
Element inserted at index : 3
Array after insertion the element : [10, 20, 30, 35, 40, 50]
Note: bisect( ) works only with that lists which are arranged in ascending order.
Page 47
c. Deletion of an element from a List: To delete an element from a list we can use remove( )
or pop( ) method.
Example:
L=[10,15,35,12,38,74,12]
print("List Before deletion of element: ", L)
val=int(input("Enter the element that you want to delete: "))
L.remove(val)
print("After deletion the element", val,"the list is: ", L)
OUTPUT:
List Before deletion of element: [10, 15, 35, 12, 38, 74, 12]
Enter the element that you want to delete: 12
After deletion the element 12 the list is: [10, 15, 35, 38, 74, 12]
d. Searching in a List:
There are two types of searching techniques we can use to search an element in a list. These
are:
(i) Linear Search
(ii) Binary Search
Page 48
break
else:
print("Element not Found")
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
Page 49
if found>=0:
print(element, "Found at the position : ",found+1)
else:
print("Element not present in the list")
OUTPUT:
Enter the elements in sorted order: [12,23,31,48,51,61,74,85]
Enter the element that you want to search : 61
61 Found at the position : 6
e. Sorting: To arrange the elements in ascending or descending order. There are many
sorting techniques. Here we shall discuss two sorting techniques:
(i) Bubble sort
(ii) Insertion sort
(i) BUBBLE SORT: Bubble sort is a simple sorting algorithm. It is based on comparisons,
in which each element is compared to its adjacent element and the elements are swapped if
they are not in proper order.
Page 50
PROGRAM:
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
OUTPUT:
The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]
Page 51
(ii) INSERTION SORT: Sorts the elements by shifting them one by one and inserting the
element at right position.
PROGRAM:
n=len(L)
for j in range(1,n):
temp=L[j]
prev=j-1
prev=prev-1
Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]
The sorted list is : [2, 11, 19, 34, 45, 56, 78, 90]
7.4.2. Multi-Dimensional array (Nested Lists): A list can also hold another list as its element.
It is known as multi-dimensional or nested list.
A list in another list considered as an element.
Example:
>>>NL=[10, 20, [30,40], [50,60,70], 80]
>>> len(NL)
5
>>>secondlist=[1,2,3,[4,5,[6,7,8],9],10,11]
>>> len(secondlist)
6
Example-2:
>>> L=["Python", "is", "a", ["modern", "programming"], "language", "that", "we", "use"]
>>> L[0][0]
'P'
>>> L[3][0][2]
'd'
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range
Page 54
CHAPTER-8
DATA STRUCTURE-II (STACK AND QUEUE)
8.1 STACK IN PYTHON:
8.1.1 INTRODUCTION:
def size(self): # Size of the stack i.e. total no. of elements in stack
return len(self.items)
s = Stack( )
print("MENU BASED STACK")
cd=True
while cd:
print(" 1. Push ")
print(" 2. Pop ")
print(" 3. Display ")
print(" 4. Size of Stack ")
print(" 5. Value at Top ")
if choice==1:
val=input("Enter the element: ")
s.push(val)
elif choice==2:
if s.items==[ ]:
print("Stack is empty")
else:
print("Deleted element is :", s.pop( ))
elif choice==3:
print(s.items)
elif choice==4:
print("Size of the stack is :", s.size( ))
elif choice==5:
print("Value of top element is :", s.peek( ))
else:
print("You enetered wrong choice ")
Page 56
print("Do you want to continue? Y/N")
option=input( )
if option=='y' or option=='Y':
var=True
else:
var=False
Exponentiation ↑ 1
Page 57
Element Operation Stack Result
5 Push 5
6 Push 5, 6
2 Push 5, 6, 2
+ Pop 5, 8 6+2=8
* Pop 40 5*8=40
12 Push 40, 12
4 Push 40, 12, 4
/ Pop 40, 3 12/4=3
- Pop 37 40-3=37
Page 58
8.1.5 Infix to Postfix Conversion:
Example-1 : Convert the following infix expression into its equivalent postfix expression.
Y= ( A + B * ( C-D ) / E )
Symbol Stack Expression Description
( ( Push the symbol in stack
A ( A Move the element in expression
+ (+ A Operator, so push into stack
B (+ AB Move the element in expression
* (+* AB Operator, push into stack, * has higher precedence than
+, so can come after +
( (+*( AB Push the open parentheses symbol into stack
C (+*( ABC Move the element in expression
- (+*(- ABC Operator, push into stack
D (+*(- ABCD Move the element in expression
) (+* ABCD - Closing parentheses, so pop the elements of the stack up
to opening parentheses
/ (+/ ABCD - * Operator, / and * operators have the same precedence,
so associativity from left to write will take place and *
will pop from stack and / will push into stack
E (+/ ABCD - *E Move the element in expression
) ABCD - * E / + Closing parentheses, so pop the elements of the stack up
to opening parentheses
Example-2 : Convert the following infix expression into its equivalent postfix expression.
Y= ( A / B - ( C*D ↑ E ) + F )
Symbol Stack Expression Description
( ( Push the symbol in stack
A ( A Move the element into expression
/ (/ A Operator, so push into stack
B (/ AB Move the element into expression
- (- AB/ Operator, - has lower precedence than /. so, / will pop
from stack and – will push into stack.
( (-( AB/ Push the symbol into stack
C (-( AB/C Move the element into expression
* (-(* AB/C Operator, push into stack
D (-(* AB/CD Move the element into expression
↑ ( - ( *↑ AB/CD Operator, ↑ has higher precedence than *, so can come
after *.
E ( - ( *↑ AB/CDE Move the element into expression
Page 59
) (- AB/CDE↑ * Closing parentheses, so pop the elements of the stack up
to opening parentheses
+ (+ AB/CDE↑ * - Operator, - and + both have same precedence, to
associativity from left to right take place. – will pop
from stack then + will push into stack.
F (+ AB/CDE↑ * - F Move the element into expression
Page 65