Learn Python Programming Language in 15 Minutes Part-3

By Kimberly Cook |Email | Dec 24, 2018 | 56379 Views

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 :
>>> print("Hello
File "<stdin>", line 1
SyntaxError: EOL while scanning string literal

The error is caused by the token preceding the arrow. In this example, the error is detected at the print() function as the parentheses are not closed.
>>> while True print("Hello World !")
File "<stdin>", line 1
while True print("Hello World !")
SyntaxError: invalid syntax

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

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.

Consider a simple print function call. What if we misspelled the word print as Print? Note the capitalization here. In this case, Python raises a syntax error.
>>> Print("Hello there !")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Print' is not defined

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.
>>> 2/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

IndexError : When the index is out of range.
>>> list = [1,2,3]
>>> list[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

TypeError : Raised when an operation or function is applied to an object of inappropriate type
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int
KeyError : It occurs when a dictionary is incorrectly used.
>>> dict = {'a' : 'Stark', 'b': 'Steve'}
>>> dict['c']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'

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 :

Visit: https://gist.github.com/vihar/fb65f19d7bd6b4a416275597d3e875a8#file-handling_exception-py
python3 handling_exception.py
You can't divide by zero.

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.
# do something
except ValueError:
# handle ValueError exception
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
# handle all other exceptions

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

Example: Raising a KeyboardInterrupt
>>> raise KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

Raising MemoryError
>>> raise MemoryError("Argument")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError: Argument

Let's raise a value error and except the error.
Visit: https://gist.github.com/vihar/78a751cf56aa7e58f0076c30c716876b#file-raising_error-py
python3 raising_error.py

Enter a negative integer: 5
That is not a negative number!

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.
Visit: https://gist.github.com/vihar/3844a78f7da3946e25ff4ee04985fe30#file-file_handling-py
Here it tries to open the file text.txt in the current directory or else it raises a FileNotFoundError error.

Python comes with hundreds 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.

import module_name

Let's now import few modules and run functions in them.
>>> import math
>>> math.pi
>>> math.sin(0)
>>> math.cos(45)
Here we imported math module and used sin and cos functions which return the values.
>>> import time
>>> print(time.asctime())
Thu Jul 27 01:47:01 2017

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

There is another way to import to use the import statement.

>>> from time import asctime
>>> asctime()
'Thu Jul 27 01:49:10 2017'

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

Consider a sound package, the way organise your Python code creates awesome packages.
sound/                        Top-level package
    __init__.py               Initialise the sound package
formats/                      Sub-package for file format
effects/                      Sub-package for sound effects
filters/                      Sub-package for filters

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 the command prompt or terminal and say
pip install <package-name>
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.

Source: HOB