An Introduction to Interactive Programming in Python (Part 3)
An Introduction to Interactive Programming in Python (Part 3)

Errors and Exception

The most common perspective in Python is that it handles all errors with exceptions.An exception is a signal that an error or other unusual condition has occurred.There are several built-in exceptions, which indicates certain conditions like IndentationError: unexpected indent, ZeroDivisionError: division by zero. You can also define your exceptions.

Programs are susceptible. It would be nice if the code always returns a valid result, but sometimes a correct result cannot be calculated.

For Example, it is not possible to divide a number by zero or to access the third element in a negative item list.

Until now error messages haven’t been more than mentioned, but if you have tried out the examples, you have probably seen some. There are (at least) two distinct kinds of errors:

1. Syntax errors
2. Exceptions

Syntax Errors

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python.Syntax errors are almost always fatal, i.e. there is almost never a way to successfully execute a piece of code containing syntax errors.

Example :

The error is caused by the token preceding the arrow.In this example the error is detected at print() function as the parentheses is not closed.

Since a colon ‘ : ’ is missing after the condition of while loop it encountered a syntax error.

Exceptions

Exceptions occur when exceptional situations happen in your program. For Example, what if you are going to read a file that doesn’t exist or what if you accidentally deleted it when the program is running. Such situations are handled using exceptions.

Similarly, what if your program had some wrong statements?
This is handled by Python which conveys you that there is an error.

Example:

Consider a simple print function call. What if we misspelled the word print as Print? Note the capitalisation here. In this case, Python raises a syntax error.

Observer that a NameError is raised and also the location where the error was detected is printed.

Now let’s see few types errors in Python

ZeroDivisionError : When a number is divided by zero.

IndexError : When the index is out of range.

TypeError : Raised when an operation or function is applied to an object of inappropriate type

KeyError : It occurs when a dictionary is incorrectly used.

Exceptional Handling

Like many other programming languages, Python has exception handling. We can handle the exceptions using the try except for statement. We basically put our general statements within the try-block and keep all our error handlers in the except block.

Example :

handling_exception.py

python3 handling_exception.py

Catching Specific Exceptions in Python

A try clause can have any number of except clause to handle them differently, but only one will be executed in case an exception occurs.

We can use a tuple of values to specify multiple exceptions in an except clause. Here is an example pseudo code.

Raising Exceptions

In Python programming, exceptions are raised when corresponding errors occur at run time, but we can forcefully raise it using the keyword raise.

Example: Raising a KeyboardInterrupt

Raising MemoryError

Let’s raise a value error and except the error.

raising_error.py

python3 raising_error.py

try…finally

The try statement in Python can have an optional finally clause. This clause is executed no matter what, and is generally used to release external resources.

file_handling.py

Here it tries to open the file text.txt in the current directory or else it raises a FileNotFoundError error.

Modules

Python comes with hundred of modules that do all sort of things. There are also third party modules that are available for download from the internet.

Python includes a set of modules called the standard library, for example, math, cmath which contains mathematical functions for real and complex numbers, but there are much more.

A module is imported using the import statement.

Let’s now import few modules and run functions in them.

Here we imported math module and used sin and cos functions which returns the values.

In this example, we had imported time module and called asctime function from that module, which returns the current time as a String.

There is another way to import to use import statement.

Here, we have imported just the asctime function from the time module.

Packages

Consider a sound package, the way organise your Python code creates awesome packages.

Third Party Packages

Python has got the greatest community for creating Python packages. There are more than 1,00,000 packages available at https://pypi.python.org/pypi .

Python package is a collection of all modules connected properly into one form and distributed PyPi, The Python Package Index maintains the list of Python packages available. Now when you are done with pip setup Go to command prompt or terminal and say

After running this command the package will be installed in your python library.You can import the package and them in your program.

Congratulations you have just completed your basic Python Programming !

Kudos to everyone who read the story and supported it.

Suggest

☞  Python Programming For Network Engineers

☞  Python For Beginners – Learn Programming from scratch

☞ The Python Video Workbook: Solve 100 Exercises

☞ Python 3: A Beginners Quick Start Guide to Python

☞ Learn the essentials of Python and ArcGIS’s arcpy

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here