Python 4
Python 4
Whenever an exception occurs, the program stops the execution, and thus the
further code is not executed. Therefore, an exception is the run-time errors that are
unable to handle to Python script. An exception is a Python object that represents an
error
Python provides a way to handle the exception so that the code can be executed
without any interruption. If we do not handle the exception, the interpreter doesn't
execute all the code that exists after the exception.
Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the
common standard exceptions. A list of common exceptions that can be thrown from
a standard Python program is given below.
Suppose we have two variables a and b, which take the input from the user and
perform the division of these values. What if the user entered the zero as the
denominator? It will interrupt the program execution and through
a ZeroDivision exception. Let's see the following example.
Example
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")
The above program is syntactically correct, but it through the error because of unusual input.
That kind of programming may not be suitable or recommended for the projects because
these projects are required uninterrupted execution. That's why an exception-handling plays
an essential role in handling these unexpected exceptions. We can handle these exceptions
in the following way.
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
Example 1
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
We can also use the else statement with the try-except statement in which, we can
place the code which will be executed in the scenario if no exception occurs in the try
block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Example 2
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return exception cl
ass
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")
Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement, which will be
executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else block.
Example
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
Syntax
try:
#block of code
except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)
#block of code
else:
#block of code
Example.
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
We can use the finally block with the try block in which we can pace the necessary
code, which must be executed before the try statement throws an exception.
Syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
Example
try:
fileptr = open("file2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
Raising exceptions
An exception can be raised forcefully by using the raise clause in Python. It is useful
in in that scenario where we need to raise an exception to stop the execution of the
program.
For example, there is a program that requires 2GB memory for execution, and if the
program tries to occupy 2GB of memory, then we can raise an exception to stop the
execution of the program.
Syntax
1. raise Exception_class,<value>
Points to remember
1. To raise an exception, the raise statement is used. The exception class name
follows it.
2. An exception can be provided with a value that can be given in the
parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable
which stores the value of the exception.
4. We can pass the value to an exception to specify the exception type.
Example
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Example 3
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
if b is 0:
raise ArithmeticError
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
Custom Exception
The Python allows us to create our exceptions that can be raised from the program
and caught using the except clause. However, we suggest you read this section after
visiting the Python object and classes.
Example
class ErrorInCode(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)
In Python, the date is not a data type, but we can work with the date objects by importing the
module named with datetime, time, and calendar.
In this section of the tutorial, we will discuss how to work with the date and time objects in
Python.
o date - It is a naive ideal date. It consists of the year, month, and day as
attributes.
o time - It is a perfect time, assuming every day has precisely 24*60*60 seconds.
It has hour, minute, second, microsecond, and tzinfo as attributes.
o datetime - It is a grouping of date and time, along with the attributes year,
month, day, hour, minute, second, microsecond, and tzinfo.
o timedelta - It represents the difference between two dates, time or datetime
instances to microsecond resolution.
o tzinfo - It provides time zone information objects.
o timezone - It is included in the new version of Python. It is the class that
implements the tzinfo abstract base class.
Tick
In Python, the time instants are counted since 12 AM, 1st January 1970. The
function time() of the module time returns the total number of ticks spent since 12
AM, 1st January 1970. A tick can be seen as the smallest unit to measure the time.
Example
1. import time;
2.
3. #returns a time tuple
4.
5. print(time.localtime(time.time()))
Time tuple
The time is treated as the tuple of 9 numbers. Let's look at the members of the time
tuple.
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 60
6 Day of weak 0 to 6
To work with dates as date objects, we have to import the datetime module into the
python source code.
Example
1. import datetime
2. #returns the current datetime object
3. print(datetime.datetime.now())
Example
1. import datetime
2. #returns the datetime object for the specified date
3. print(datetime.datetime(2020,04,04))
Consider the following example to print the calendar for the last month of 2018.
Example
1. import calendar;
2. cal = calendar.month(2020,3)
3. #printing the calendar of December 2018
4. print(cal)
Example
1. import calendar
2. #printing the calendar of the year 2019
3. s = calendar.prcal(2020)
Environment Setup
To build the real world applications, connecting with the databases is the necessity
for the programming languages. However, python allows us to connect our
application to the databases like MySQL, SQLite, MongoDB, and many others.
In this section of the tutorial, we will discuss Python - MySQL connectivity, and we
will perform the database operations in python. We will also cover the Python
connectivity with the databases like MongoDB and SQLite later in this tutorial.
Install mysql.connector
To connect the python application with the MySQL database, we must import the
mysql.connector module in the program.
The mysql.connector is not a built-in module that comes with the python installation.
We need to install it to get it working.
1. > python -m pip install mysql-connector
https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7b866
0d09f91d8d5411298bcacbd309f96/mysql-connector-python-8.0.13.tar.gz to
download the source code.
3. Open the terminal (CMD for windows) and change the present working directory
to the source code directory.
$ cd mysql-connector-python-8.0.1
4. Run the file named setup.py with python (python3 in case you have also installed
python 2) with the parameter build.
$ python setup.py build
$ python setup.py install
This will take a bit of time to install mysql-connector for python. We can verify the
installation once the process gets over by importing mysql-connector on the python
shell.
Database Connection
In this section of the tutorial, we will discuss the steps to connect the python
application to the database.
There are the following steps to connect a python application to our database.
Pass the database details like HostName, username, and the database password in
the method call. The method returns the connection object.
1. Connection-Object= mysql.connector.connect(host = <host-name> , user = <
username> , passwd = <password> )
Here, we must notice that we can specify the database name in the connect() method
if we want to connect to a specific database.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "goog
le", database = "mydb")
5.
6. #printing the connection object
7. print(myconn)
1. <my_cur> = conn.cursor()
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google", database = "mydb")
4.
5. #printing the connection object
6. print(myconn)
7.
8. #creating the cursor object
9. cur = myconn.cursor()
10.
11. print(cur)
1. > show databases;
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "goog
le")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. dbs = cur.execute("show databases")
11. except:
12. myconn.rollback()
13. for x in cur:
14. print(x)
15. myconn.close()
Creating the new database
The new database can be created by using the following SQL query.
create database <database-name>
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
#creating the cursor object
cur = myconn.cursor()
try:
#creating a new database
cur.execute("create database PythonDB2")
#getting the list of all the databases which will now include the new database Python
DB
dbs = cur.execute("show databases")
except:
myconn.rollback()
for x in cur:
print(x)
myconn.close()
1. > create table Employee (name varchar(20) not null, id int primary key, salary
float not null, Dept_Id int
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",databas
e = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Creating a table with name Employee having four columns i.e., name, id, salary, and departm
ent id
dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null
primary key, salary float not null, Dept_id int not null)")
except:
myconn.rollback()
myconn.close()
Alter Table
Sometimes, we may forget to create some columns, or we may need to update the
table schema. The alter statement used to alter the table schema if required. Here,
we will add the column branch_name to the table Employee. The following SQL
query is used for this purpose.
1. alter table Employee add branch_name varchar(20) not null
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",databas
e = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#adding a column branch name to the table Employee
cur.execute("alter table Employee add branch_name varchar(20) not null")
except:
myconn.rollback()
myconn.close()
Insert Operation
Adding a record to the table
The INSERT INTO statement is used to add a record to the table. In python, we can
mention the format specifier (%s) in place of values.
We provide the actual values in the form of tuple in the execute() method of the
cursor.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"
#The row values are provided in the form of tuple
val = ("John", 110, 25000.00, 201, "Newyork")
try:
#inserting the values into the table
cur.execute(sql,val)
#commit the transaction
myconn.commit()
except:
myconn.rollback()
print(cur.rowcount,"record inserted!")
myconn.close()
Read Operation
The SELECT statement is used to read the values from the databases. We can restrict
the output of a select query by using various clause in SQL like where, limit, etc.
Python provides the fetchall() method returns the data stored inside the table in the
form of rows. We can iterate the result to get the individual rows.
In this section of the tutorial, we will extract the data from the database by using the
python script. We will also format the output to print it on the console.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",databas
e = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select * from Employee")
#fetching the rows from the cursor object
result = cur.fetchall()
#printing the result
for x in result:
print(x);
except:
myconn.rollback()
myconn.close()
In the following example, we will read the name, id, and salary from the Employee
table and print it on the console.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")
#fetching the rows from the cursor object
result = cur.fetchall()
#printing the result
for x in result:
print(x);
except:
myconn.rollback()
myconn.close()
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",databas
e = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")
#fetching the first row from the cursor object
result = cur.fetchone()
#printing the result
print(result)
except:
myconn.rollback()
myconn.close()
Update Operation
The UPDATE-SET statement is used to update any column inside the table. The
following SQL query is used to update a column.
update Employee set name = 'alex' where id = 110
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",databas
e = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#updating the name of the employee whose id is 110
cur.execute("update Employee set name = 'alex' where id = 110")
myconn.commit()
except:
myconn.rollback()
myconn.close()
Delete Operation
The DELETE FROM statement is used to delete a specific record from the table. Here,
we must impose a condition using WHERE clause otherwise all the records from the
table will be removed.
The following SQL query is used to delete the employee detail whose id is 110 from
the table.
delete from Employee where id = 110
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",databas
e = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Deleting the employee details whose id is 110
cur.execute("delete from Employee where id = 110")
myconn.commit()
except:
myconn.rollback()
myconn.close()
Our Python NumPy Tutorial provides the basic and advanced concepts of the
NumPy. Our NumPy tutorial is designed for beginners and professionals.
NumPy stands for numeric python which is a python package for the computation
and processing of the multidimensional and single dimensional array elements.
What is NumPy
NumPy stands for numeric python which is a python package for the computation
and processing of the multidimensional and single dimensional array elements.
With the revolution of data science, data analysis libraries like NumPy, SciPy, Pandas,
etc. have seen a lot of growth. With a much easier syntax than other programming
languages, python is the first choice language for the data scientist.
NumPy provides a convenient and efficient way to handle the vast amount of data.
NumPy is also very convenient with Matrix multiplication and data reshaping. NumPy
is fast which makes it reasonable to work with a large set of data.
There are the following advantages of using NumPy for data analysis.
pip install numpy
It is best practice to install NumPy with the full SciPy stack. The binary distribution of
the SciPy stack is specific to the operating systems.
Windows
On the Windows operating system, The SciPy stack is provided by the Anaconda
which is a free distribution of the Python SciPy package.
Linux
In Linux, the different package managers are used to install the SciPy stack. The
package managers are specific to the different distributions of Linux. Let's look at
each one of them.
Ubuntu
Execute the following command on the terminal.
$ sudo apt-get install python-numpy
$ python-scipy python-matplotlibipythonipythonnotebook python-pandas
$ python-sympy python-nose
Redhat
On Redhat, the following commands are executed to install the Python SciPy
package stack.
$ sudo yum install numpyscipy python-matplotlibipython
$ python-pandas sympy python-nose atlas-devel
NumPy Ndarray
Ndarray is the n-dimensional array object defined in the numpy which stores the
collection of the similar type of elements. In other words, we can define a ndarray as
the collection of the data type (dtype) objects.
The ndarray object can be accessed by using the 0 based indexing. Each element of
the Array object contains the same size in the memory.
The ndarray object can be created by using the array routine of the numpy module.
For this purpose, we need to import the numpy.
1. >>> a = numpy.array
1. >>> a = numpy.array
We can also pass a collection object into the array routine to create the equivalent n-
dimensional array. The syntax is given below.
1. >>> numpy.array(object, dtype = None, copy = True, order = None, subok =
False, ndmin = 0)
S Paramete Description
N r
1 object It represents the collection object. It can be a list, tuple, dictionary, set, etc.
2 dtype We can change the data type of the array elements by changing this option to
the specified type. The default is none.
4 order There can be 3 possible values assigned to this option. It can be C (column
order), R (row order), or A (any)
5 subok The returned array will be base class array by default. We can change this to
make the subclasses passes through by setting this option to true.
a = numpy.array([1, 2, 3])
>>> a = numpy.array([[1, 2, 3], [4, 5, 6]])
To change the data type of the array elements, mention the name of the data type
along with the collection.
1. >>> a = numpy.array([1, 3, 5, 7], complex)
>>> import numpy as np
>>> arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])
>>> print(arr.ndim)
Example
#finding the size of each item in the array
import numpy as np
a = np.array([[1,2,3]])
print("Each item contains",a.itemsize,"bytes")
Example
import numpy as np
a = np.array([[1,2,3,4,5,6,7]])
print("Array Size:",a.size)
print("Shape:",a.shape)
Reshaping the array objects
By the shape of the array, we mean the number of rows and columns of a multi-
dimensional array. However, the numpy module provides us the way to reshape the
array by changing the number of rows and columns of the multi-dimensional array.
The reshape() function associated with the ndarray object is used to reshape the
array. It accepts the two parameters indicating the row and columns of the new
shape of the array.
Example
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print("printing the original array..")
print(a)
a=a.reshape(2,3)
print("printing the reshaped array..")
print(a)
Example
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print(a[0,1])
print(a[2,0])
NumPy Broadcasting
In Mathematical operations, we may need to consider the arrays of different shapes.
NumPy can perform such operations where the array of different shapes are
involved.
For example, if we consider the matrix multiplication operation, if the shape of the
two matrices is the same then this operation will be easily performed. However, we
may also need to operate if the shape is not similar.
Example
import numpy as np
a = np.array([1,2,3,4,5,6,7])
b = np.array([2,4,6,8,10,12,14])
c = a*b;
print(c)
However, in the above example, if we consider arrays of different shapes, we will get
the errors as shown below.
Example
import numpy as np
a = np.array([1,2,3,4,5,6,7])
b = np.array([2,4,6,8,10,12,14,19])
c = a*b;
print(c)
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing array:")
print(a);
print("Iterating over the array:")
for x in np.nditer(a):
print(x,end=' ')
Order of the iteration doesn't follow any special ordering like row-major or column-
order. However, it is intended to match the memory layout of the array.
Example
import numpy as np
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])
print("Printing the array:")
print(a)
print("Printing the transpose of the array:")
at = a.T
print(at)
#this will be same as previous
for x in np.nditer(at):
print(print("Iterating over the array:")
for x in np.nditer(a):
print(x,end=' ')
Trigonometric functions
Numpy contains the trigonometric functions which are used to calculate the sine,
cosine, and tangent of the different angles in radian.
The sin, cos, and tan functions return the trigonometric ratio for the specified angles.
Consider the following example.
Example
import numpy as np
arr = np.array([0, 30, 60, 90, 120, 150, 180])
print("\nThe sin value of the angles",end = " ")
print(np.sin(arr * np.pi/180))
print("\nThe cosine value of the angles",end = " ")
print(np.cos(arr * np.pi/180))
print("\nThe tangent value of the angles",end = " ")
print(np.tan(arr * np.pi/180))
On the other hand, arcsin(), arccos(), and arctan() functions return the trigonometric
inverse of the specified angles.
The numpy.degrees() function can be used to verify the result of these trigonometric
functions. Consider the following example.
Example
import numpy as np
arr = np.array([0, 30, 60, 90])
print("printing the sin values of different angles")
sinval = np.sin(arr*np.pi/180)
print(sinval)
print("printing the inverse of the sin")
cosec = np.arcsin(sinval)
print(cosec)
print("printing the values in degrees")
print(np.degrees(cosec))
print("\nprinting the cos values of different angles")
cosval = np.cos(arr*np.pi/180)
print(cosval)
print("printing the inverse of the cos")
sec = np.arccos(cosval)
print(sec)
print("\nprinting the values in degrees")
print(np.degrees(sec))
print("\nprinting the tan values of different angles")
tanval = np.tan(arr*np.pi/180)
print(tanval)
print("printing the inverse of the tan")
cot = np.arctan(tanval)
print(cot)
print("\nprinting the values in degrees")
print(np.degrees(cot))
Rounding Functions
The numpy provides various functions that can be used to truncate the value of a
decimal float number rounded to a particular precision of decimal numbers. Let's
discuss the rounding functions.
1. numpy.around(num, decimals)
S Paramete Description
N r
2 decimals It is the number of decimals which to which the number is to be rounded. The
default value is 0. If this value is negative, then the decimal will be moved to the
left.
Example
import numpy as np
arr = np.array([12.202, 90.23120, 123.020, 23.202])
print("printing the original array values:",end = " ")
print(arr)
print("Array values rounded off to 2 decimal position",np.around(arr, 2))
print("Array values rounded off to -1 decimal position",np.around(arr, -1))
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.floor(arr))
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.ceil(arr))
Example
import numpy as np
a = np.array([[2,10,20],[80,43,31],[22,43,10]])
print("The original array:\n")
print(a)
print("\nThe minimum element among the array:",np.amin(a))
print("The maximum element among the array:",np.amax(a))
print("\nThe minimum element among the rows of array",np.amin(a,0))
print("The maximum element among the rows of array",np.amax(a,0))
print("\nThe minimum element among the columns of array",np.amin(a,1))
print("The maximum element among the columns of array",np.amax(a,1))