0% found this document useful (0 votes)
19 views5 pages

Test Questions

Uploaded by

nedumaran202
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views5 pages

Test Questions

Uploaded by

nedumaran202
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Exception handling

Exceptions
• An exception is an error that happens during execution of a program. When that Error occurs
Errors in python

•IO Error-If the file cannot be opened.


•Import Error -If python cannot find the module
•Value Error -Raised when a built-in operation or function receives an argument
thathas the right type but an inappropriate value
• Keyboard Interrupt -Raised when the user hits the interrupt
• EOF Error -Raised when one of the built-in functions (input() or raw_input()) hits
an end-of-file condition (EOF) without reading any data
Exception Handling Mechanism
1. try –except
2. try –multiple except
3. try –except-else
4. raise exception
5. try –except-finally
1. Try –Except Statements
• The try and except statements are used to handle runtime errors
Syntax:
try :
statements
except :
statements
The try statement works as follows:-
✓ First, the try clause (the statement(s) between the try and except keywords) is executed.
✓ If no exception occurs, the except clause is skipped and execution of the try statement
is finished.
✓ If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if
its type matches the exception named after the except keyword,the except clause is executed,
and then execution continues after the try statement.
Example:
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / Y
print(“result=”.result)
except ZeroDivisionError:
print(“Division by Zero”)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero

2. Try – Multiple except Statements


o Exception type must be different for except statements
Syntax:
try:
statementsexcept
errors1:
statementsexcept
errors2:
statementsexcept
errors3:
statements
Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of y”))
try:
sum = X + Y
divide = X / Y
print (“ Sum of %d and %d = %d”, %(X,Y,sum))
print (“ Division of %d and %d = %d”, %(X,Y,divide))
except NameError:
print(“ The input must be number”)
except ZeroDivisionError:
print(“Division by Zero”)

Output:1 Output 2: Output 3:


Enter the value of X = 10 Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 0 Enter the value of Y = a
Sum of 10 and 5 = 15 Sum of 10 and 0 = 10 The input must be number
Division of 10 and 5 = 2 Division by Zero

1. Try –Except-Else
o The else part will be executed only if the try block does not raise the exception.

o Python will try to process all the statements inside try block. If value error occur, the flow of
control will immediately pass to the except block and remaining statements in try block will
be skipped.
Syntax:
try:
statements
except:
statements
else:
statements
Example:
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try
result = X / Y
except ZeroDivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero

4. Raise statement
The raise statement allows the programmer to force a specified exception to occur.
Example:
>>> raise NameError('HiThere')
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>NameError: HiThere
If you need to determine whether an exception was raised but don’t intend to handleit, a simpler
form of the raise statement allows you to re-raise the exception:

Example
try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
Output:
An exception flew by! Traceback(most recent
call last):
File "<stdin>", line 2, in <module>NameError: HiThere

5. Try –Except-Finally
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break,
continue or return statement.
Syntax:
try:
statements
except:
statements
finally:
statements
Example:
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / Y
except Zero DivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
finally:
print (“executing finally clause”)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero
executing finally clause executing finally clause

Strings and its operation:


A string is a sequence of characters within (either single quotes ( ‘ ) or double quotes ( “ ). Python treats
anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so
single character is a string of length 1.
An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative). A index starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is created. Python will get the input at
run time by default as a string.
Python does not support character data type. A string of size 1 can be treated as characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
Indexing in string:
Indexing means referring to an element of particular string.

Positive indexing helps in accessing the string from the beginning

Negative subscript helps in accessing the string from the end.


Subscript 0 or –ve n(where n is length of the string) displays the first element. Displays the first element.
Example: A[0] or A[-5] will display “H”
Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”

String Slicing:
It is the process of extracting a sub string from a main string is called Slicing.
It is a way to get specific parts of a string by using start, end, and step values. It’s especially useful for text
manipulation and data parsing.
Syntax of String Slicing in Python
substring = s[start : end : step]

Parameters:
• s: The original string.
• start (optional): Starting index (inclusive). Defaults to 0 if omitted.
• end (optional): Stopping index (exclusive). Defaults to the end of the string if omitted.
• step (optional): Interval between indices. A positive value slices from left to right, while a negative value
slices from right to left. If omitted, it defaults to 1 (no skipping of characters).

Retrieve All Characters


To retrieve the entire string, use slicing without specifying any parameters.

Example: Output:
s = "Hello Python" Hello Python
print(s[:]) Hello Python
print(s[::])
Get All Characters Before or After a Specific Position
To get all the items from a specific position to the end of the string, we can specify the start index and leave
the end blank.
And to get all the items before a specific index, we can specify the end index while leaving start blank.

Example:
s = "Hello Python" Output:
print(s[6:]) Python
print(s[:5]) Hello

Reverse a String Using Slicing


To reverse a string, use a negative step value of -1, which moves from the end of the string to the beginning.
Example:
s = "Hello Python"
print(s[::-1])

Output:
nohtyP olleH

String Concatenation:
String concatenation in Python allows us to combine two or more strings into one.
The most simple way to concatenate strings in Python is by using the + operator.

Example:
s1 = "Hello"
s2 = "python"
res = s1 + " " + s2
print(res)

Output:
Hello python

Repeat a String using * Operator


The simplest way to repeat a string in Python is with
the * operator. Use the operator on a string to repeat
the string a provided number of times.
The syntax for the operation is:
result = string * number

Example:
s = "GK " * 5
print(s)

(or)

s = "GK "
print(s*5)

Output:
GK GK GK GK GK

Memebership:

The Python membership operators test for the


membership of an object in a sequence, such as strings,
lists, or tuples. Python offers two membership
operators such in and not in to check or validate the
membership of a value.

Example:
s = "Ganesh CS RockerZ"
print("CS" in s)
print("CS" not in s)

Output:
True
False

You might also like