Types of Errors in Python
Syntax errors:
Syntax errors occur when the code violates the rules of the Python
language syntax. These errors are detected by the Python interpreter
when it is parsing the code. (Missing colon, Unmatched
parentheses, Missing quotes, Using a keyword as a variable name,
Missing indentation)
Runtime errors:
Runtime errors occur when the code is syntactically correct but causes
an error when it is executed. These errors can be caused by a variety of
reasons, such as invalid input data, division by zero, or accessing an
undefined variable.
Logical errors:
Logical errors occur when the code is syntactically correct and runs
without causing any errors, but the output is not what you expected.
These errors can be caused by incorrect algorithmic design,
mathematical errors, or a misunderstanding of the problem
requirements.
Examples
if x>0
print(“x is positive”) x=”20”
y=10
********************** z=x/y #TypeError
list1=[10,20,30]
print(list1[4]) ***********************
#IndexError
str1=”Hello, Sam”
*********************** str1.reverse() #AttributeError
a=5
b=10 ************************
average = a+b /2 x=0
print(average) while x<20:
print(x)
*******************
a=20
print(b) # Name Error
Build-in exceptions in python
1) SyntaxError: Raised when there is a syntax error in the Python code
2) Type Error: Raised when an operation or function is applied to an object of
inappropriate type.
3) ValueError: Raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value.
4) IndexError: Raised when trying to access an index that does not exist in a
sequence.
5) KeyError: Raised when trying to access a key that does not exist in a dictionary.
6) NameError: Raised when a variable name is not defined.
7) AttributeError: Raised when trying to access an attribute that does not exist.
8) I/OError: Raised when an input/output operation fails.
9) ZeroDivisionError: Raised when trying to divide a number by zero.
10) MemoryError: Creating a large list or array that exceeds the available memory
11) ImportError: Raised when an import statement fails to find and load the
requested module.
Program to check for ValueError Exception
while True:
try:
number = int(input("Enter a number:"))
print(f"The number you have entered is {number}")
break
except ValueError:
print("Oops! That was no valid number. Try again...")
Output:
Enter a number: wer
Oops! That was no valid number. Try again...
Enter a number:4.0
Oops! That was no valid number. Try again...
Enter a number:
Program to check for ZeroDivisionError
x=int(input("Enter value of x:")) Output:
y=int(input("Enter value of y:")) Enter value of x:4
try: Enter value of y:2
result=x/y Result is 2.0
except ZeroDivisionError: Executing finally clause
print("Division by zero")
else: Enter value of x:2
print(f"Result is {result}") Enter value of y:0
finally: Division by zero
print("Executing finally Executing finally clause
clause")
Encapsulation
In Python, encapsulation refers to the bundling of data
(attributes) and methods (functions) that operate on
the data into a single unit
Encapsulation features :
Organized variable and its methods.
Avoids unnecessary modification of variable.
Can use across the modular programming.
Encapsulation in python
Wrapping of variables and functions under a single unit
data hiding, private
Ex: Class Encap:
Class Encap: __a=10
a=10 def display(self):
def display(self):
print(self.a) print(self.__a)
e=Encap() e=Encap()
e.display() e.display()
print(e.a) print(e.a)
# Invalid cannot access private var
Here, a is a public variable, which can be accessed anywhere in the program
Inorder, to provide data hiding we have to provide private access specifier.
Python doesn’t support private access specifier
Python provides _ _
__a =10 is represented as private variable
__display(self): is represented as private method
Class Encap:
__a=10
def __display(self ):
print(self.__a)
def show(self):
self.__display()
e=Encap()
e.display() # Invalid cannot access private var
print(e.a) # Invalid cannot access private var
e.show()
Class Encap:
__a=10
def setA(self,a):
self.a=a
def getA(self):
return(self.a)
e=Encap()
e.setA(30)
print(e.getA())