Saturday 19 May 2018

Errors and Exceptions in Python

In Python there are two kinds of Errors :

Syntax Error and Exceptions

Syntax Errors are also known as parsing errors and are the one which occur due to wrong syntax , means  the mistake we did in use of Python language. They are analogous to grammatical mistakes in English language. The parser immediately points to the error without further executing the code.

For e.g


>>> for i in range(3):
print i
    int i = 9.0

SyntaxError : invalid syntax


Exceptions

An "exception" is defined as "something that does not conform to the norm "". Even if a statement is syntactically correct it might give error in execution . Error detected during execution are called exceptions.

Exceptions occur with different types and type is printed as message with error.

The most common types are:

Index Error : It is the type of exception that raises when a program tries to access an element that is not within the bounds of an indexable type.
The string followed by index error provide information about what caused the exception to occur.
For example :

>>> a = [1,2,3,4]
>>> print a[5]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print a[5]
IndexError: list index out of range

Name Error : It is a type of exception that raises when a name is not defined in the program
For example :

>>> print b
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print b
NameError: name b is not defined
                             


Value Error  : It is a type of exception that raises when a value mismatch occurs in the program
For example:
>>> x = int(raw_input("Enter a number: ")) enter a number: d
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
x = int(raw_input("Enter a number"))
ValueError: invalid literal for int() with base 10: 'd'

Type Error  : It is a type of exception that raises when a type mismatch occurs in the program.
For example
>>> 2 + '7' Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
2 + '7'
TypeError: unsupported operand type(s) for +: 'int' and 'str'



No comments:

Post a Comment

Loan Prediction Analysis

In this post I will share my visuals ,learning and understanding of a dataset and using various algorithms of Machine Learning to analyse i...