II - I - CSE - Python Programming - Unit-2 - Exceptions - Mate - 240426 - 180429

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

Department of Computer Science and Engineering (Artificial Intelligence & Machine

Learning)
Python Programming – II Year B.Tech II Semester
Course Instructor: Prof.B.Sreenivasu, 9502251564, 9550411738
------------------------------------------------------------------------------------------------------------------------------
==========================================================================================================
Exceptions: Exceptions in Python, Detecting and Handling Exceptions, Context Management, *Exceptions
as Strings, Raising Exceptions, Assertions, Standard Exceptions, *Creating Exceptions.
==========================================================================================================
Exceptions:
● What is Exception?
● Why exception handling?
● Syntax error v/s Runtime error
● Detecting and Handling Exceptions
● Handling exception – with help of using try block and except blocks or try with multi except blocks
● Handling multiple exceptions with single except block
● Handling exception with help of using ==>
❖ try-except
❖ Try-except-finally
❖ Try with finally

● Raising Exceptions, Assertions, raise keyword


● User defined exceptions
Need for Custom exceptions
Introduction:
 As a human beings, we commit several errors. A software developer (programmer) is also a human
being and hence prone to commit errors either in the designing of the software or in writing the
code. The errors in the software are called ‘bugs’ and the process of removing them is called
‘debugging’.
 Let’s learn about different types of errors that can occur in a program.
Types of Errors:
In software application development programmer / developer come across different types of errors.
1. Syntax Errors
2. Logical Errors
3. Runtime Errors
Syntax Error:
Syntax errors occurs when we violate the rules of programming language (Python).
For example, consider the lines of code given below.
>>> y = 0
>>> if y == 0 print(y)
SyntaxError: invalid syntax

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 1 of 22
All compile time errors are called syntax errors. If there is a syntax error within program. program is not
executed.
Note:
• When the proper syntax of the language is not followed then a syntax error is thrown.
• Syntax errors must be rectified by programmer in order to execute program.

Logic error:
▪ Logical errors occur due to our mistakes in programming logic.
▪ A program with logical errors compiles successfully and executes but does not generate the desired
results.
▪ Logical errors are no caught by compiler. It has be identified and corrected by the programmer /
developer.

Example:
==========================================================================================================

#python program to demonstrate logical error.

n1=float(input("Enter first floating point number: "))


n2=float(input("Enter second floating point number: "))
avg=n1+n2/2
print(f'average of two numbers{n1} and {n2} is {avg}')

OUTPUT:
Enter first floating point number: 4.5
Enter second floating point number: 2.9
average of two numbers4.5 and 2.9 is 5.95

Enter first floating point number: 4.5


Enter second floating point number: 5.5
average of two numbers4.5 and 5.5 is 7.25

==========================================================================================================

Note: The results mentioned above is incorrect. Because according to the operator
precedence, division is evaluated first before addition.

Difference between Syntax Error and Exceptions:


Syntax Error: As the name suggests this error is caused by the wrong syntax in the python code / python
program. It leads to the termination of the program.

Exceptions: An exception is a type of error that occurs when a syntactically correct python code raises an
error during execution time / run time. If run time errors are not handled program gets terminated.

Runtime Errors:
Even if a python code (python program) is syntactically correct, it may still raise error when
executed.
Runtime errors occurs because of wrong input / invalid input given by end user. When runtime error occurs,
program execution is terminated.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 2 of 22
Key note: An error which is occurred during execution of program is called runtime error.
An exception is a run time error which can be handled by the programmers.

Exception handling:
▪ Exception handling or Error handling means handling runtime errors.
▪ Exception is a runtime error.
▪ When a python program raises an exception, it must handle the exception otherwise program will
be immediately terminated.
▪ We can handle exceptions (runtime errors) by making python program more robust.
Python provides the following keywords to handle exceptions/errors:

1. try
2. except
3. finally
4. raise
We can handle exceptions in python program by using try block and except block.
Advantage of error handling or exception handling:
1.Avoiding abnormal termination program
2.Converting predefined error messages or codes into user defined error message
Key note:

❖ Every error is one class or type in python. Creating object of error class/type and giving to PVM is
called raising an error or generating error.
❖ An error generated in function during execution / run time if wrong input is given by end user.
Exceptions are of two types:
1. Predefined exceptions / error types (Built-in exceptions)
2. User defined exceptions/error types

Built-in exceptions that are usually raised in Python:


Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
AssertionError Raised when an assert statement fails
AttributeError Raised when attribute reference or assignment fails
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 3 of 22
Exception Base class for all exceptions
EOFError Raised when the input() method hits an "end of file" condition (EOF)
FloatingPointError Raised when a floating point calculation fails
GeneratorExit Raised when a generator is closed (with the close() method)
ImportError Raised when an imported module does not exist
IndentationError Raised when indentation is not correct
IndexError Raised when an index of a sequence does not exist
KeyError Raised when a key does not exist in a dictionary
KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete
LookupError Raised when errors raised cant be found
MemoryError Raised when a program runs out of memory
NameError Raised when a variable does not exist
NotImplementedError Raised when an abstract method requires an inherited class to override the
method
OSError Raised when a system related operation causes an error
OverflowError Raised when the result of a numeric calculation is too large
ReferenceError Raised when a weak reference object does not exist
RuntimeError Raised when an error occurs that do not belong to any specific exceptions
StopIteration Raised when the next() method of an iterator has no further values
SyntaxError Raised when a syntax error occurs
TabError Raised when indentation consists of tabs or spaces
SystemError Raised when a system error occurs
SystemExit Raised when the sys.exit() function is called
TypeError Raised when two different types are combined
UnboundLocalError Raised when a local variable is referenced before assignment
UnicodeError Raised when a unicode problem occurs
UnicodeEncodeError Raised when a unicode encoding problem occurs
UnicodeDecodeError Raised when a unicode decoding problem occurs
UnicodeTranslateError Raised when a unicode translation problem occurs
ValueError Raised when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero

Imp. Note:
Exception is a root class or base class for all exception types.

Detecting and Handling Exceptions:


• Exceptions can be detected by incorporating syntactically correct python code as a part of try
statement.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 4 of 22
• Any python code suite / code block / statements will be monitored for exceptions which is
incorporated in try suite.
try block:
try block contains the statements (python code) which has to be monitored for exception handling (OR)
the statements which generate errors during runtime are included within try block.

Syntax:
try:
try_suite / statement(s) #watch for exception here

except block:
except block is an error handling block. If there is an error inside try block, that error is handled by except
block.
try block followed by one or more except blocks.

Syntax:
try:
statement-1
statement-2
except <error-type> as <variable-name>:
statement-3 #exception handling code
except <error-type> as <variable-name>:
statement-4

Note: except block contains logic to convert predefined error message into user defined message.

#python program to print object ‘x’


print(x)

OUTPUT:
Traceback (most recent call last):
File "C:\Users\Sreenivasu\Desktop\cse_exception.py", line 3, in <module>
print(x)
NameError: name 'x' is not defined

#python program to understand exceptions in python


try:
print(x)
except:
print("Dear user look into program")

OUTPUT:
Dear user look into program

Example:
Predefined exception type with description:
exception ZeroDivisionError
Raised when the second argument / parameter of a division or modulo operation is zero.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 5 of 22
# Write a python program to handle the divide zero exception
while True:
num1=int(input("Enter First Number "))
num2=int(input("Enter Second Number "))
try:
div=num1/num2
print(" Result of division is", div)
print(f'Result of division of {num1} and {num2} is {div:.2f}') #formatting output using f'string
break
except ZeroDivisionError:
print(" You Cannot Divide a Number with zero")
print("Dear Sreenivasu Enter valid inputs...")

OUTPUT:

Enter First Number 64


Enter Second Number 8
Result of division is 8.0
Result of division of 64 and 8 is 8.00

OUTPUT:

Enter First Number 81


Enter Second Number 0
You Cannot Divide a Number with zero
Dear User Enter valid inputs...
Enter First Number 81
Enter Second Number 9
Result of division is 9.0
Result of division of 81 and 9 is 9.00

raise keyword:
A function generates error using raise keyword.
Generating error is creating error object and giving to PVM (python virtual machine).
Syntax:
raise <error-type-name>()

#example-1: python program to demonstrate use of raise keyword


def division(n1,n2): #creating / developing a user defined function
if n1==0 or n2==0:
raise ValueError()
else:
return n1/n2

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 6 of 22
n1=int(input("Enter first num "))
n2=int(input("Enter second num "))
res=division(n1,n2) #calling function
print("result of division", res)

OUTPUT:

Enter first num 45


Enter second num 9
result of division 5.0

OUTPUT:

Enter first num 34


Enter second num 0
Traceback (most recent call last):
File "C:\Users\Sreenivasu\Desktop\exception.py", line 19, in <module>
res=division(n1,n2)
File "C:\Users\Sreenivasu\Desktop\exception.py", line 14, in division
raise ValueError()
ValueError

#example-2 python program to demonstrate use of raise keyword


def multiply(n1,n2):
if n1==0 or n2==0:
raise ValueError()
else:
return n1*n2

while True:
try:
num1=int(input("Enter First Number "))
num2=int(input("Enter Second Number "))
num3=multiply(num1,num2)
print(num1,num2,num3)
break
except ValueError:
print("Numbers cannot multiply with zero")
print("Pls enter numbers again")

OUTPUT:
Enter First Number 4
Enter Second Number 6
4 6 24

OUTPUT:

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 7 of 22
Enter First Number 1
Enter Second Number 0
Numbers cannot multiply with zero
Pls enter numbers again
Enter First Number 0
Enter Second Number 4
Numbers cannot multiply with zero
Pls enter numbers again
Enter First Number 6
Enter Second Number 9
6 9 54

#python program having an except block handling multiple exceptions simultaneously


try:
num=int(input("enter any number"))
print(num**2)
except (KeyboardInterrupt,ValueError):
print("please check before you enter...... program terminating")

OUTPUT:
enter any number56
3136
enter any number
you should have entered a number.....program terminating

raise keyword:
Note: you can deliberately raise an exception using raise keyword
syntax for the raise statement is
raise <exception>

#python program to deliberately raise an exception


try:
num=int(input("Enter any number"))
print(num)
raise ValueError
except:
print("Exception occurred....program terminating")

OUTPUT:
Enter any number56
56
Exception occurred....program terminating

#python program to deliberately raise an exception


try:
num=int(input("Enter any number"))
print(num)
except:
print("Exception occurred....program terminating")
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 8 of 22
OUTPUT:
Enter any number45
45
OUTPUT:
Enter any number4.5
Exception occurred....program terminating

#program to handle exceptions from an invoked function


def divide(a,b): #invoked function
try:
return a/b

except ZeroDivisionError:
print("you can not divide a number by zero....program terminating")

a=int(input("Enter a : "))
b=int(input("Enter b : "))
res=divide(a,b) #calling function
print(res)

OUTPUT:
Enter a : 45
Enter b : 9
5.0

OUTPUT:
Enter a : 45
Enter b : 0
you can not divide a number by zero....program terminating
None

#program to handle exceptions in calling function


def divide(a,b):
return a/b

try:
a=int(input("Enter a : "))
b=int(input("Enter b : "))
res=divide(a,b)
print(res)
except ZeroDivisionError:
print("you can not divide a number by zero....program terminating")

OUTPUT:
Enter a : 84
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 9 of 22
Enter b : 16
5.25
OUTPUT:
Enter a : 68
Enter b : 0
you can not divide a number by zero....program terminating

finally block:
➢ finally is a keyword.
➢ finally block is not exception handler.
➢ finally block is used to de-allocate the resources allocated within try block.
➢ finally block contains statements which are executed after execution of try block and except
block.
➢ The 'finally' block contains code that will always be executed, regardless of whether an exception
occurs or not within the “try” block.
➢ The finally block is always executed, so it is generally used for doing the concluding tasks like
closing file resources or closing database connection.

#Example python program to demonstrate use of try, except and finally blocks
try:
print("inside try block")
a=int(input("Enter value of a "))
b=int(input("Enter value of b "))
c=a/b
print(f'division of {a} and {b} is {c:.2f}')
except:
print("inside except block")
print("Dear User,Exception occurred..>ValueError..>Enter valid input")
finally:
print("inside finally block")
print("it's ok")

OUTPUT:

inside try block


Enter value of a 56
Enter value of b 7
division of 56 and 7 is 8.00
inside finally block
it's ok

OUTPUT:

inside try block


Enter value of a 100
Enter value of b 0
inside except block
Dear User,Exception occurred..>ValueError..>Enter valid input
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 10 of 22
inside finally block
it's ok

try block with multiple except block:


 if try block raises more than one exception those exceptions are handled using multiple except
blocks.
Syntax:
try:
statement-1
statement-2
except <exception-type>:
statement-3
except <exception-type>:
statement-4

Example python program:


try:
n1=int(input("Enter First Number "))
n2=int(input("Enter Second Number "))
n3=n1/n2
print(f'Result is {n3}')
except ValueError as a:
print("input only numbers")
except ZeroDivisionError as b:
print("cannot divide number with zero")

Output:
Enter First Number 5
Enter Second Number 0
cannot divide number with zero

Enter First Number abc


input only numbers

Output:
Enter First Number
Traceback (most recent call last):
File "C:/Users/Sreenivasu/Desktop/Exception programs/11_11_2023_try.py", line 2, in <module>
n1=int(input("Enter First Number "))
KeyboardInterrupt

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 11 of 22
Note: In above python program we have except blocks to handle ValueError and ZeroDivisionError but
there is no except block to handle KeyboardInterrupt error which is raised when the user inputs interrupt
keys (Ctrl + C or Delete)

How to handle multiple errors using one except block?


• except block without error type is able to handle any error raised by try block.
• except block without error type is called generic except block.

Example:
try:
n1=int(input("Enter First Number "))
n2=int(input("Enter Second Number "))
div_res=n1/n2
print(f'Result is {div_res}')
except:
print("cannot divide number with zero or input only numbers ")

Output:
Enter First Number 45
Enter Second Number 9
Result is 5.0

Enter First Number 0


Enter Second Number 9
Result is 0.0

Enter First Number sdc


cannot divide number with zero or input only numbers

Enter First Number 45


Enter Second Number 0
cannot divide number with zero or input only numbers

Enter First Number 45


Enter Second Number
cannot divide number with zero or input only numbers

Note: KeyboardInterrupt error which is raised when the user inputs interrupt keys (Ctrl + C)

# Write a Python program for IndexError


cse_list = [501,502,503,504]

try:

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 12 of 22
value =cse_list[4]
print(value)
except IndexError as e:
print(" An index error occurred : ", e)

OUTPUT:

An index error occurred : list index out of range

#python program for FileNotFoundError


import os
try:
os.rename("D:\marks.txt","D:\snigdha.txt")
print("file renaming is done")
except FileNotFoundError:
print("exception occurred...>specified file is not found")

OUTPUT:
exception occurred...>specified file is not found

else block:
➢ the try and except block can optionally have an else block
➢ the statements in the else block is executed only if the try block does not raise an exception.

For example, the python code given below illustrates both the cases

#python program to demonstrate else block


try:
f1=open("D:\snigdha.txt",'r')
str=f1.readline()
print(str)
except IOError:
print("Error occurred during input....program terminating")
else:
print("Program terminating successfully")

OUTPUT:
543 tej 89 45

Program terminating successfully

#python program to demonstrate else block


try:
f1=open("D:\snigdha.txt",'a')
str=f1.readline()
print(str)

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 13 of 22
except IOError:
print("Error occurred during input....program terminating")
else:
print("Program terminating successfully")

OUTPUT:
Error occurred during input....program terminating

=================================================================================================================
Note: built-in exceptions in Python:
(Python 3.11.4 documentation
Welcome! This is the official documentation for Python 3.11.4.)

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 14 of 22
Built-in Exceptions in python as per official documentation for Python 3.11.4:

In Python, all exceptions must be instances of a class that derives from BaseException. In a try statement
with an except clause that mentions a particular class, that clause also handles any exception classes
derived from that class

Exceptions hierarchy:
The class hierarchy for built-in exceptions is:
BaseException
├── BaseExceptionGroup
├── GeneratorExit
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ExceptionGroup [BaseExceptionGroup]
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── BlockingIOError
│ ├── ChildProcessError
│ ├── ConnectionError
│ │ ├── BrokenPipeError
│ │ ├── ConnectionAbortedError
│ │ ├── ConnectionRefusedError
│ │ └── ConnectionResetError
│ ├── FileExistsError
│ ├── FileNotFoundError
│ ├── InterruptedError
│ ├── IsADirectoryError
│ ├── NotADirectoryError
│ ├── PermissionError
│ ├── ProcessLookupError

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 15 of 22
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
│ ├── NotImplementedError
│ └── RecursionError
├── StopAsyncIteration
├── StopIteration
├── SyntaxError
│ └── IndentationError
│ └── TabError
├── SystemError
├── TypeError
├── ValueError
│ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
│ └── UnicodeTranslateError
└── Warning
├── BytesWarning
├── DeprecationWarning
├── EncodingWarning
├── FutureWarning
├── ImportWarning
├── PendingDeprecationWarning
├── ResourceWarning
├── RuntimeWarning
├── SyntaxWarning
├── UnicodeWarning
└── UserWarning

=================================================================================================================

sys.exc_info()

This function returns the old-style representation of the handled exception. If an exception e is currently
handled (so exception() would return e), exc_info() returns the tuple (type(e), e, e.__traceback__). That
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 16 of 22
is, a tuple containing the type of the exception (a subclass of BaseException), the exception itself, and
a traceback object which typically encapsulates the call stack at the point where the exception last
occurred.

#example python program

import sys
try:
n1=int(input("Enter First Number "))
n2=int(input("Enter Second Number "))
n3=n1/n2
print(f'Result is {n3}')
except:
t=sys.exc_info()
print(t[1])
OUTPUT:

Enter First Number 64


Enter Second Number 0
division by zero

Enter First Number 45


Enter Second Number 9
Result is 5.0

Enter First Number 3


Enter Second Number 2
Result is 1.5

Enter First Number 24


Enter Second Number abc
invalid literal for int() with base 10: 'abc'

Creating Exceptions:
▪ Each time an error is detected in a program, the python interpreter raises (throws) an exception.
▪ Programmers can also raise exceptions in a program using the raise and assert statements.
User defined exceptions:
▪ Every exception is a derived class from exception class(exception is base class).
▪ All the exception either built-in or user defined all are derived class from exception class.

Defining Custom Exceptions:


In Python, we can define custom exceptions / user defined by creating a new class that is derived from
the built-in class.
Key points:
Custom Error Types or User Defined Error Types
1. Every error type is one class.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 17 of 22
2. This class is inherited from Exception class.
Basic steps for creating error class
1. Create class by inheriting Exception class
2. Provide a constructor, which calls the constructor of super class.

Syntax for defining custom exceptions:

class CustomError(Exception):
...
pass

try:
...
except CustomError:
...

Note: CustomError is a user defined error / exception which inherits from the Exception class which is a
base class for all built-in and user defined exceptions.

The assert statement:


 The assert statement is useful to ensure that a given condition is True. If it not True, it raises
AssertionError.
 The assert keyword is used when debugging code.
 The assert keyword lets you to test if a condition in your code returns True, if not, the program
will raise an AssertionError.

Syntax:
assert <condition>, <error message>

Key note: if the condition is False, then the exception by the name AssertionError is raised along with the
message written in the assert statement. If the message is not given in the assert statement and the condition
is False, then also AssertionError is raised without message.

Example programming exercises:

# Example python program to demonstrate use of 'assert' keyword


str="PYTHON"
assert str=="Python", "str should be PYTHON" # if condition is False,then AssertionError is raised

OUTPUT:
Traceback (most recent call last):
File "C:/Users/Sreenivasu/Desktop/assert.py", line 5, in <module>
assert str=="Python", "str should be PYTHON"
AssertionError: str should be PYTHON

#python program using the assert statement and catching AssertionError


try:
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 18 of 22
x=int(input("Enter a number between 5 and 10: "))
assert x>=5 and x<=10
print("the number entered: ",x)
except AssertionError:
print("The condition is not fulfilled")

OUTPUT:

Enter a number between 5 and 10: 98


The condition is not fulfilled

Enter a number between 5 and 10: 6


the number entered: 6

#python program using the assert statement with a message and catching AssertionError
try:
x=int(input("Enter a number between 5 and 10: "))
assert x>=5 and x<=10, "Your input is not correct"
print("the number entered: ",x)
except AssertionError as obj:
print(obj)

OUTPUT:
Enter a number between 5 and 10: 34
Your input is not correct

Enter a number between 5 and 10: 9


the number entered: 9

Note: When the condition in assert statement is False, the message is passed to AssertionError object ‘obj’
that can be displayed in the except block as shown in above program.

#python program to create user defined exception called “InvalidData” which is derived class from
#Exception class => exception class is base class for all built-in and user defined exceptions

class InvalidData(Exception):
pass
marks=int(input("Enter marks for students: "))
try:
if marks<0 or marks>100:
raise InvalidData
except InvalidData:
print("Student marks should be in between 0 and 100")

OUTPUT:
Enter marks for students: 105
Student marks should be in between 0 and 100
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 19 of 22
Important Note: In above program we have created exception called “InvalidData” which is derived class
from Exception class => exception class is base class for all built-in and user defined exceptions

#python program to define custom exception / user defined exception

class InvalidAgeException(Exception):
"Raised when input value is less than 18"
pass

age_vote=18

try:
age=int(input("Enter age: "))
if age<age_vote:
raise InvalidAgeException
else:
print("eligible to vote")
except InvalidAgeException:
print("Exception occurred: Invalid age")

OUTPUT:

Enter age: 45
eligible to vote

Enter age: 13
Exception occurred: Invalid age

Enter age: 12
Exception occurred: Invalid age

#python program for creating custom exception ‘loginError’


users={'sreenivasu':'cse123','bs':'a321','sreenivasu_ad':'ad543','cse_ab':'cr123'}

class LoginError(Exception):
def __init__(self):
super().__init__()

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 20 of 22
def login(user,pwd):
if user in users and users[user]==pwd:
return True
else:
raise LoginError()

try:
uname=input("UserName ")
password=input("Password ")
if login(uname,password):
print(f'{uname} welcome')
except LoginError:
print("invalid username or password")

OUTPUT:
UserName cse_ab
Password cr123
cse_ab welcome

*****
Sample Review Questions:
1. Differentiate between error and exception.
2. What will happen if an exception occurs but is not handled by the program?
3. Explain the syntax of try-except block
4. Explain how to handle an exceptions in python.
5. What is the difference between try-except and try-finally?
6. Elaborate on raise statement used to raise exceptions.
7. Write a python program to illustrate “FileNotFoundError” exception.
8. Write a python program for creating custom exception ‘loginError’

Reference Books:

1. Core Python Programming, Wesley J.Chun, Second Edition, Pearson.


2. Python Programming Using Problem Solving Approach, Reema Thareja, Second
Edition, OXFORD University Press.
3. Introduction to Python, Kenneth A. Lambert, Cengage.

==========================================================================================================

Dear Students,

During your preparation for the examinations / interview questions, you can refer / use below mentioned
websites for material / for coding exercises / coding practice.
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 21 of 22
for Python Developer Interview Questions: for Interview questions

1. https://www.interviewbit.com/python-interview-questions
2. https://quescol.com/interview-preparation

==========================================================================================================
Coding platforms of international repute: for coding practice
1. https://www.hackerrank.com
2. https://www.codechef.com
3. https://leetcode.com

==========================================================================================================

Web links for self-learning / coding exercise:

1. https://www.tutorialspoint.com/python
2. https://www.javatpoint.com/python-tutorial
3. https://www.programiz.com/python-programming
4. https://www.geeksforgeeks.org/python-programming-language/
5. https://www.w3schools.com/python
6. https://onlinecourses.nptel.ac.in/noc22_cs26/preview

==========================================================================================================

Thanks.

Prof.BS

9502251564 – for voice call and ‘whatsapp’

9550411738

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 22 of 22

You might also like