Python Basic Tutorials

Python is a high level general purpose programming language which has a clear/easy learning curve. Python programming language is massively used in various domains like Artificial Intelligence, Data Science, Web Development, Utilities Tools and Scripts and many more

Python is a Programming language, and the default Python we use is written in C programming language which is also referred to as CPython (Python implementation in C). There are various implementation of Python Programming language i.e Jython(in JAVA), Skulpt(in JS) e.t.c

To make everything easy: We refer CPython as Python

Exceptions in Python

Errors are the problems in a program due to which the program will terminate. Basically, errors are of two types:

  1. Syntax Errors.
  2. Logical Errors(Exceptions).
Syntax Error

A syntax error is an error produced due to the use of the wrong syntax in the program.

Example

if 2>1      # writing invalid syntax
    print("Two is greater than one!")
Output

line 1
if 2>1
^
SyntaxError: invalid syntax
Logical errors(exceptions)

If the errors are syntactically correct but the errors occur at runtime then this error is known as Logical errors or exceptions. It will not stop the execution of the program but it will affect the normal flow of the program.

Example

a=3
b=0
c=a/b #produces divided by zero error.
print(c)
Output

line 4, in "module"
c=a/b
ZeroDivisionError: division by zero

Other examples would be opening a file in read mode that does not exist which is FileNotFoundError. Also importing a module that does not exist is ImportError.

Exception Handling

Exceptions are those errors that affect the normal flow of the program. Until the occurred exceptions are handled, it will also affect the coupling functions. So, exceptions should be handled properly.

Catching an exception--try...except block.

We can make exception handling more precise by using specific exception handling. By using a specific exception handler we can handle exceptions specifically means different exceptions can be handled in a different way.

Example

def exceptions(num):
    if(num>500):
       result=100/(num-600) #throws exception if num==600.
    elif num>200:
       result=num+'500' #throws exception if num>200 and num<500.
    else:
       print("Hello")

print("result: "+result) #throws exception if num<100.
try:
    exceptions(600)
    exceptions(300)
    exceptions(100)
except ZeroDivisionError:
    print("ZeroDivisionError occured and handled.")
except TypeError:
    print("TypeError occurred and handled.")
except NameError:
    print("NameError occurred and handled.")
Output

ZeroDivisionError occurred and was handled.

//If we comment on the first line of the try block following output will be produced
TypeError occured and handled.

//If we comment on the first two lines of the try block following output will be produced
Hello
NameError occurred and handled.
    

Hence, with the help of specific exception handling, it is possible to handle each exception in a different manner.

Raising an exception in python.

Normally exceptions occur when errors occur in runtime. But in python, We can raise exceptions manually by ourselves by using the 'raise' keyword for some conditions.

Example

num=10
if num%2==0:
   raise Exception('Exception is raised for even number')
    
Output
Exception: Exception raised for even number. 

We can also raise specific errors and pass a message as an argument which can detailly clarify why the error was raised.

Example

num=input("Enter :")
if(int(num)<0):
    raise ValueError("Negative value detected.")
Output:

Enter : -1
ValueError: Negative value detected.
 
Finally Keyword

Finally is used at the bottom of the try...except block. Code or statement inside the finally block always runs no matter what errors occur in the program after the execution of the try...except block.

Example

try:
    print("Hello")
    print(1+'4')
except TypeError:
    print("Can't use + operator between 'int' and 'str'.")
finally:
    print("This code will run no matter what")
    
Output

Hello
Can't use + operator between 'int' and 'str'.
This code will run no matter what.
        
Python assertion

The assertion is the sanity checker by which we can test an expression, if the expression test results false, an exception is raised. Assertions are done using the assert keyword.

Example

print("Hello")
assert 2+2==4
print("Python")
assert 2+1==3
print("TheRightWay!")
assert 3+1==3
print("This will not be printed.")
    
Output

Hello
Python
TheRightWay!

line 6, in "module"
assert 3+1==3
AssertionError

Firstly user declares an expression to be true using the assertion statement. If the expression test returns true then the program's control simply moves to the next line otherwise the program stops running and returns AssertionError Exception. 

Example

a=1
b=0
assert b!=0, "Denominator should not be zero"
print(a/b)
Output

assert b!=0, "Denominator should not be zero"
AssertionError: Denominator should not be zero
    
Handiling Assertion Error.

try:
    a=1
    b=0
    assert b!=0, "Denominator can never be zero in any fraction."
except AssertionError as msg:
    print(msg)
Output

Denominator can never be zero in any fraction.
    
Python try with else block

If we need to execute the additional block of code after the try...except block, if no exceptions occur then its solution would be using else block along with try...except block.

Example

# program to print the square of odd numbers
try:
    num = int(input("Enter a number: "))
    assert num % 2 != 0, "Not an odd number."
except AssertionError as msg:
     print(msg)
else:
     cube=num**3
     print(cube)
    
Output

// providing even number
Enter a number: 2
Not an odd number.

//Providing odd number
Enter a number: 3
27