0% found this document useful (0 votes)
103 views

XII CS Unit1 TxT File DataStr Exception Notes

Godd

Uploaded by

velukarthick3010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

XII CS Unit1 TxT File DataStr Exception Notes

Godd

Uploaded by

velukarthick3010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Text Files / Data Structure / Exception Handling

Marks Text Files


(Question)
Section A 1 1
Section B 2 -
Section C 3 1
Section D 4 -
Section E 5 -
Total Marks 04

Text Files (Sample Programs)

Write a Python function that displays all Write a Python function that finds and
the words containing @cmail from a text displays all the words longer than 5
file "Emails.txt". characters from a text file "Words.txt".

def show(): def display_long_words():


f=open("Email.txt",'r') f=open("Words.txt", 'r')
data=f.read() data=file.read()
words=data.split() words=data.split()
for word in words: for word in words:
if '@cmail' in word: if len(word)>5:
print(word,end=' ') print(word,end=' ')
f.close() f.close()
Write a function in python to read lines Write a function COUNT() in Python to
from file “POEM.txt” and display all those read contents from file
words, which has two characters in it. “REPEATED.TXT”, to count and display
def TwoCharWord(): the occurrence of the word “Catholic”
f = open('poem.txt') or “mother”.
count = 0 def COUNT():
for line in f: f= open('REPEATED.txt')
words = line.split() count = 0
for w in words: for line in f:
if len(w)==2: words = line.split()
print(w,end=' ') for w in words:
if w.lower() == 'catholic' or w.lower() == 'mother':
count+=1
print('Count is', count)
Write a Python function that can read a Write a Python function that extracts and
text file and print only numbers stored in displays all the words present in a text file
the file on the screen (consider the text “Vocab.txt” that begins with a vowel.
file name as "info.txt"). def display_words():
def sample(): vowels = 'AEIOUaeiou'
f=open( “info.txt”,”r”) f=open('Vocab.txt', 'r')
d=file.read() words = file.read().split()
for x in d: for word in words:
if x.isdigit(): if word[0] in vowels:
print(x) print(word)
Write a function in python to count the Write a function Biggest( ) in python to
number of lines in a text file ‘readme.txt’, read a text file ‘readme.txt’ and then
that contain the word ‘happy’ anywhere in return the word that has the maximum
them. length.
def count(): def count():
f = open(‘readme.txt’, ‘r’) f = open(‘readme.txt’, ‘r’)
lines = f.readlines() big = “”
c=0 content = f.read()
for line in lines: words = content.split(‘ ’)
if ‘happy’ in line: for w in words:
c+=1 if len(w)>len(big):
print(“Total number of such lines: ”, c) big = w
f.close() f.close()
return big
Write a function in python to read the Write a function in python to count the
text file ‘CITY.TXT’ and count the number number of lines in a text file
of times “my” occurs in the file. ‘COUNTRY.TXT’ which is starting with an
def COUNTMY(): alphabet ‘p’ or ‘k’.
file=open('CITY.TXT','r') def COUNTLINES():
count=0 file=open('COUNTRY.TXT','r')
x = file.readlines() lines = file.readlines()
word=x.split() count=0
for w in word: for w in lines:
if (w==”my”): if w[0]=="p" or w[0]=="k":
count=count+1 count=count+1
print(“Total lines “,count) print(“Total lines “,count)
file.close() file.close()
Write a method/function Display_three() Write a function in python to count the
in python to read lines from a text file number of lines in a text file ‘FILE.TXT’
STORY.TXT, and display those words, which is starting with an alphabet ‘A’ or ‘a’.
which are less than or equal to 3 defcountlines():
characters. file=open("FILE.TXT")
def Display_three(): lines=file.readlines()
f=open(“STORY.TXT”,’r’) count=0
lines=f.readlines() for word in lines:
for line in lines: if word[0]=="A" or word[0]=="a":
for word in line.split(): count=count+1
if len(word)<=3: print("total lines",count)
print(word) file.close()
Write a function linecount() in python Write a Python function that displays all
which read a file ‘data.txt’ and count the words starting from the letter ‘C’ in
number of lines starts with character ‘P’. the text file "chars.txt".
def linecount(): Def cletter():
count = 0 f=open( “chars.txt”,”r”)
f=open('data.txt', 'r') d=file.read()
for line in file: WL=d.split()
if line.startswith('P'): for w in WL:
count += 1 if w[0]==’c’ or w[0]==’C’:
print(‘Number of lines’, count) print(w)
f.close()
Data Structure

Marks Data Structure


(Question)
Section A 1 -
Section B 2 -
Section C 3 1
Section D 4 -
Section E 5 -
Total Marks 03

Sample Program
# Initialize an empty list to represent the stack
stack = []

# Push elements onto the stack


stack.append(10) # Push 10 onto the stack
stack.append(20) # Push 20 onto the stack
stack.append(30) # Push 30 onto the stack

# Display the current stack


print("Stack:", stack)

# Pop elements from the stack


print("Popped item:", stack.pop()) # Removes and returns 30
print("Popped item:", stack.pop()) # Removes and returns 20

# Display the stack after popping


print("Stack after popping:", stack)

# Check if the stack is empty


if len(stack) == 0:
print("The stack is empty.")
else:
print("The stack is not empty.")

# Size of the stack


print("Size of stack:", len(stack))
Sample Programs (Stack -03 Mark)

A) You have a stack named BooksStack that contains records of books. Each book record
is represented as a list containing book_title, author_name, and publication_year.
Write the following user-defined functions in Python to perform the specified operations
on the stack BooksStack:

push_book(BooksStack, new_book): This def push_book(BooksStack, new_book):


function takes the stack BooksStack and BooksStack.append(new_book)
a new book record new_book as arguments
and pushes the new book record onto the
stack.

pop_book(BooksStack): This function def pop_book(BooksStack):


pops the topmost book record from the if not BooksStack:
stack and returns it. If the stack is print("Underflow")
already empty, the function should display else:
"Underflow". return(BookStack.pop())
peep(BookStack): This function displays def peep(BooksStack):
the topmost element of the stack without if not BooksStack:
deleting it. If the stack is empty, the print("None")
function should display 'None'. else:
print(BookStack[-1])

There is a stack named Uniform that contains records of uniforms Each record is
represented as a list containing uid, uame, ucolour, usize, uprice.
Write the following user-defined functions in python to perform the specified operations
on the stack Uniform :

Push_Uniform(new_uniform): adds the def Push_Uniform(new_uniform):


new uniform record onto the stack
Uniform.append(new_uniform)
Pop_Uniform(): pops the topmost record def Pop_Uniform():
from the stack and returns it. If the if not Uniform:
stack is already empty, the function print("Underflow")
should display “underflow”. else:
return(Uniform.pop())

Peep(): This function diplay the topmost def peep(Uniform):


element of the stack without deleting it.if if not Uniform:
the stack is empty,the function should print("None")
display ‘None’. else:
print(Uniform[-1])
Sample Programs (Stack -03 Mark)

A list, items contain the following record as list elements [itemno, itemname, stock]. Each
of these records are nested to form a nested list.

Write the following user defined functions to perform the following on a stack reorder.

i. Push(items)- it takes the nested list as its ii. Popitems() -It pops the objects
argument and pushes a list object containing one by one from the stack reorder
itemno and itemname where stock is less than 10 and also displays a message ‘Stack
empty’ at the end.

items=[[101,'abc',8],[102,'gg',12],[103,'tt',5],[104,'yy',15]] def Popitems():


reorder=[] while len(reorder):
def Push(items): print(reorder.pop())
for i in items: else:
if i[2]<10: print("Stack
reorder.append([i[0],i[1]]) empty")
Push(items) Popitems()
reorder [[101, 'abc'], [103, 'tt']]

You have a stack named Inventory that contains records of medicines. Each record is
represented as a list containing code, name, type and price.

Write the following user-defined functions in Python to perform the specified operations
on the stack Inventory:

New_In (Inventory, newdata): This Inventory=[]


function takes the stack Inventory and def New_In(Inventory,newdata):
newdata as arguments and pushes the Inventory.append(newdata)
newdata to Inventory stack.

Del_In(Inventory): This function removes def Del_In(Inventory):


the top most record from the stack and if len(Inventory)==0:
returns it. If the stack is already empty, print(“Nothing to POP”)
the function should display "Underflow". else:
Inventory.pop()
Show_In(Inventory): This function def Show_In(Inventory):
displays the topmost element of the stack for p in range(len(Inventory)-1,-1,-1):
without deleting it. If the stack is empty, print(Inventory[p])
the function should display 'None'.
code=input(“Code”)
name=input(“Name”)
price=input(“Price)
L=[code,name,price]
New_In(Inverntory, L)
Del_In(Inventory)
Show_In(Inventory)
Sample Programs (Stack -03 Mark)

You have a stack named MovieStack that contains records of movies. Each movie record
is represented as a list containing movie_title, director_name, and release_year.

Write the following user-defined functions in Python to perform the specified operations
on the stack MovieStack:

(I) push_movie(MovieStack, new_movie): This def push_movie(movie_stack, new_movie):


function takes the stack MovieStack and a new movie_stack.append(new_movie)
movie record new_movie as arguments and pushes
the new movie record onto the stack.
(II)pop_movie(MovieStack): This function pops def pop_movie(movie_stack):
the topmost movie record from the stack and if not movie_stack:
returns it. If the stack is empty, the function return "Stack is empty"
should display "Stack is empty". return movie_stack.pop()
(III) peek_movie(MovieStack): This function def peek_movie(movie_stack):
displays the topmost movie record from the stack if not movie_stack:
without deleting it. If the stack is empty, the return "None"
function should display "None". return movie_stack[-1]

Write the definition of a user-defined def push_odd(M, odd_numbers):


function push_odd(M) which accepts a list for number in M: # 1mark
of integers in a parameter M and pushes all if number % 2 != 0:
those integers which are odd from the list odd_numbers.append(number)
M into a Stack named OddNumbers.
Write the function pop_odd() to pop the def pop_odd(odd_numbers):
topmost number from the stack and return if not odd_numbers: # 1mark
it. If the stack is empty, the function return "Stack is empty"
should display "Stack is empty". return odd_numbers.pop()
Write the function disp_odd() to display all def disp_odd(odd_numbers):
elements of the stack without deleting if not odd_numbers: # 1mark
them. If the stack is empty, the function return "None"
should display "None". return odd_numbers
For example:
If the integers input into the list
NUMBERS are: [7, 12, 9, 4, 15]
Then the stack OddNumbers should store:
[7, 9, 15]
Sample Programs (Stack -03 Mark)

Write the definition of a user defined function push_words(N) which accept list of words
as parameter and pushes words starting with A into the stack named InspireA

def push_words(N):
# Initialize an empty stack
InspireA = []
# Loop through each word in the list N
for word in N:
# Check if the word starts with the letter 'A'
if word.startswith('A') or word.startswith('a'):
# Push the word to the stack
InspireA.append(word)
# Return the stack (optional, to view the result)
return InspireA

Write the function pop_words(N) to pop topmost word from the stack and return it. if
the stack is empty, the function should display “Empty”.

def pop_words(N):
# Check if the stack is empty
if not N:
# If the stack is empty, return "Empty"
return "Empty"
else:
# Pop the topmost word from the stack and return it
return N.pop()

Write a Python program to input an integer and display all its prime factors in descending
order, using a stack. For example, if the input number is 2100, the output should be: 7 5
5 3 2 2 (because prime factorization of 2100 is 7x5x5x3x2x2)

n=int(input("Enter an integer: "))


s=[] #stack
f=2
while n>1:
if n%f==0:
s.append(f)
n//=f
else: f+=1
while s:
print(s.pop(),end=' ')
Exception Handling

Marks Exception Handling


(Question)
Section A 1 1
Section B 2 -
Section C 3 -
Section D 4 1
Section E 5 -
Total Marks 05

An exception is a Python object that represents an error. When an error occurs during
the execution of a program, an exception is said to have been raised. Such an exception
needs to be handled by the programmer so that the program does not terminate
abnormally.

Types of Errors

1. Compile Time Errors: compile time errors are classified into two categories:

(i) Syntax Errors: A syntax error occurs when any of the Python programming
rules are violated or the program is not written correctly as per the format
required.
For Example,
x =+3 #Statement 1 not the correct operator,
if a = (a+b) #Statement 2 is incorrect.

(ii) Semantic Errors: Semantic Errors occur when the statement has no meaning
in the program.
For Example,
a=5 #Statement 1
b=7 #Statement 2
a+b=res #Statement 3 has a semantic error because an expression never
comes to the left side of the assignment operator.

2. Logical errors:
Quite often the programmer has written the code correctly without any syntax error or
semantic error. But didn’t get the exact result that is desired. This happens because of
the programmer’s mistake where the appropriate logic is not used.

For example in place of addition, subtraction is done.

3. Runtime errors:
Sometimes the program is correct syntactically and semantically, but when the
programmer runs the program, errors occur. Such kinds of errors are called runtime
errors. Runtime errors are very harder to detect in the programs. These errors may stop
the program execution abnormally or crash in between or runs infinite loops.
4. Exceptions:
An exception is a program event that occurs during program execution and disrupts the
flow of a program. When a Python program cannot cope with a situation, it raises an
exception. An exception is a Python object that represents an error.
Some common Python exceptions are as follows:

Exception Explanation
ValueError It is raised when a built-in method or operation mismatched or
inappropriate values are provided as input.

IOError It is raised when the file specified in a program statement cannot


be opened.

KeyboardInterrupt It is raised when the user accidentally presses delete or esc key or
cancels the execution.

ImportError It is raised when the specified module is not installed or not


working.

EOFError It is raised when the end of file condition is reached without


reading any data by input().

ZeroDivisionError It is raised when any number is having denominator zero.

IndexError It is raised when the index or subscript in a sequence is out of


range.

NameError It is raised when a variable is accessed before declaration.

IndentationError It is raised due to incorrect indentation in the program code.

TypeError It is raised when an operator is supplied with a value of incorrect


data type.

OverFlowError It is raised when the result of a calculation exceeds the maximum


limit for numeric data type.

try and except block


The try block contains the actual codes that need to be executed.
Every try block is followed by except block.
The exception handling code is written inside the except block.
In the execution of the program, if an exception is raised the try block execution is
stopped and the control is shifted to except block.

The syntax of try and except is as follows:


try:
program statement in which exception may occur
except [exception_name]:
exception handler code
Exceptions Examples
NameError Exception try:
print(x)
except NameError:
print("Varibale is not defined...")
ValueError Exception try:
a = int(input("Enter your age: "))
except ValueError:
#Print message for ValueError
print("Invalid input:Enter numbers only")
ImportError try:
import Datetime
print("Module")
except ImportError:
print("Invalid module Can't import")
ZeroDivisionError try:
c=5/0
except ZeroDivisionError:
print("You cannot divide")
IndexError l=[11,45,67,89]
try:
print(l[5])
except IndexError:
print("Index not found")
TypeError try:
a=5
print(a+'b')
except TypeError:
print("Invalid Datatypes")

Finally Clause
The statements inside the finally block are always executed regardless of whether an
exception has occurred in the try block or not.

The finally clause always executes at the end. The finally clause ends the exception-
handling process. Just have a look at the following:

print ("Handling multiple exceptions")


try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1+n2
except ValueError:
print("Enter integers only...")
else:
print("No exception raised...")
print("The result is:",res)
finally:
print("You have done it!!! Bye Bye")
Sample Programs (Exception Handling – 04 Mark)

I. When is ZeroDivisionError exception raised in Python?


Ans: ZeroDivisionError is raised when a statement tries to divide a number by zero.

II. Give an example code to handle ZeroDivisionError? The code should display the
message "Division by Zero is not allowed" in case of ZeroDivisionError exception, and the
message " " in case of any other exception.

Ans:
try:
a=int(input("Enter an integer: "))
print("Reciprocal of the number =",1/a)
except ZeroDivisionError:
print("Division by Zero is not allowed")
except:
print("Some Error Ocurred")

I. When is NameError exception raised in Python?


Ans: NameError is raised when an undefined identifier is used in the program.

II. Give an example code to handle NameError? The code should display the message
"Some name is not defined" in case of NameError exception, and the message "Some
error occurred" in case of any other exception.

Ans:
try:
a=eval(input("Enter an integer: "))
print("Reciprocal of the number =",1/a)
except NameError:
print("Some name is not defined")
except:
print("Some Error Ocurred")

You might also like