You are on page 1of 40

Python Exception

An exception can be defined as an unusual condition in a program resulting in the


interruption in the flow of the program.

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.

Python has many built-in exceptions that enable our program to run without


interruption and give the output. These exceptions are given below:

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.

1. ZeroDivisionError: Occurs when a number is divided by zero.


2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

The problem without handling exceptions


As we have already discussed, the exception is an abnormal condition that halts the
execution of the program.

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.

Exception handling in python

The try-expect statement

Syntax

try:    
    #block of code     
    
except Exception1:    
    #block of code    
    
except Exception2:    
    #block of code    
    
#other code    

Consider the following example.

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")     

The except statement with no exception


Python provides the flexibility not to specify the name of exception with the
exception statement.
Consider the following example.

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")   

The except statement using with exception variable


We can use the exception variable with the except statement. It is used by using
the as keyword. this object will return the cause of the exception. Consider the
following example:

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()    

Declaring Multiple Exceptions


The Python allows us to declare the multiple exceptions with the except clause.
Declaring multiple exceptions is useful in the cases where a try block throws multiple
exceptions. The syntax is given below.

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")       

The try...finally block


Python provides the optional finally statement, which is used with the try statement.
It is executed no matter what exception occurs and used to release the external
resource. The finally block provides a guarantee of the execution.

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.

The syntax to use the finally block is given below.

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.

The syntax to use the raise statement is given below.

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 2 Raise the exception with message


try:  
     num = int(input("Enter a positive integer: "))  
     if(num <= 0):  
# we can pass the message in the raise statement  
         raise ValueError("That is  a negative number!")  
except ValueError as e:  
     print(e)  

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.

Consider the following example.

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)      

Python Date and time


Python provides the datetime module work with real dates and times. In real-world
applications, we need to work with the date and time. Python enables us to schedule our
Python script to run at a particular timing.

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.

The datetime classes are classified in the six main classes.

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.

Consider the following example


1. import time;  
#prints the number of ticks spent since 12 AM, 1st January 1970  
print(time.time())  

How to get the current time?


The localtime() functions of the time module are used to get the current time tuple.
Consider the following example.

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.

Index Attribute Values

0 Year 4 digit (for example 2018)

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

7 Day of year 1 to 366

8 Daylight savings -1,0,1 0r 1

The datetime Module


The datetime module enables us to create the custom date objects, perform various
operations on dates like the comparison, etc.

To work with dates as date objects, we have to import the datetime module into the
python source code.

Consider the following example to get the datetime object representation for the


current time.

Example

1. import datetime  
2. #returns the current datetime object     
3. print(datetime.datetime.now())    

Creating date objects


We can create the date objects bypassing the desired date in the datetime
constructor for which the date objects are to be created.

Consider the following example.

Example
1. import datetime    
2. #returns the datetime object for the specified date    
3. print(datetime.datetime(2020,04,04))    

The calendar module


Python provides a calendar object that contains various methods to work with the
calendars.

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)    

Printing the calendar of whole year


The prcal() method of calendar module is used to print the calendar of the entire
year. The year of which the calendar is to be printed must be passed into this
method.

Example

1. import calendar    
2. #printing the calendar of the year 2019    
3. s = calendar.prcal(2020)  

Python Database Programming

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.

Execute the following command to install it using pip installer.

1. >  python -m pip install mysql-connector  

Or follow the following steps.

1. Click the link:

https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7b866
0d09f91d8d5411298bcacbd309f96/mysql-connector-python-8.0.13.tar.gz to
download the source code.

2. Extract the archived file.

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  

5. Run the following command to install the mysql-connector.

$ 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.

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

Creating the connection


To create a connection between the MySQL database and the python application, the
connect() method of mysql.connector module is used.

Pass the database details like HostName, username, and the database password in
the method call. The method returns the connection object.

The syntax to use the connect() is given below.

1. Connection-Object= mysql.connector.connect(host = <host-name> , user = <
username> , passwd = <password> )  

Consider the following example.


Example
import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")  
  
#printing the connection object   
print(myconn)  

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)   

Creating a cursor object


The cursor object can be defined as an abstraction specified in the Python DB-API
2.0. It facilitates us to have multiple separate working environments through the
same connection to the database. We can create the cursor object by calling the
'cursor' function of the connection object. The cursor object is an important aspect of
executing queries to the databases.

The syntax to create the cursor object is given below.

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)  

Creating new databases


In this section of the tutorial, we will create the new database PythonDB.

Getting the list of existing databases


We can get the list of all the databases by using the following MySQL query.

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()  

Creating the table


In this section of the tutorial, we will create the new table Employee. We have to
mention the database name while establishing the connection object.
We can create the new table by using the CREATE TABLE statement of SQL. In our
database PythonDB, the table Employee will have the four columns, i.e., name, id,
salary, and department_id initially.

The following query is used to create the new table Employee.

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  

Consider the following example.

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.

Consider the following example.

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()

Reading specific columns


We can read the specific columns by mentioning their names instead of using star (*).

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()  

The fetchone() method


The fetchone() method is used to fetch only one row from the table. The fetchone()
method returns the next row of the result-set.

Consider the following example.

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  

Consider the following example.

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()  

Python NumPy Tutorial

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.

Travis Oliphant created NumPy package in 2005 by injecting the features of the


ancestor module Numeric into another module Numarray.
t is an extension module of Python which is mostly written in C. It provides various
functions which are capable of performing the numeric computations with a high
speed.

NumPy provides various powerful data structures, implementing multi-dimensional


arrays and matrices. These data structures are used for the optimal computations
regarding arrays and matrices.

In this tutorial, we will go through the numeric python library NumPy.

The need of NumPy

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.

1. NumPy performs array-oriented computing.


2. It efficiently implements the multidimensional arrays.
3. It performs scientific computations.
4. It is capable of performing Fourier Transform and reshaping the data stored in
multidimensional arrays.
5. NumPy provides the in-built functions for linear algebra and random number
generation.

Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as the


replacement to MATLAB as Python is more complete and easier programming
language than MATLAB.

NumPy Environment Setup


NumPy doesn't come bundled with Python. We have to install it using the python
pip installer. Execute the following command.

 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.

It can be downloaded from the official website: https://www.anaconda.com/. It is also


available for Linux and Mac.

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

Creating a ndarray object


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  

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)  

The parameters are described in the following table.

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.

3 copy It is optional. By default, it is true which means the object is copied.

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.

6 ndmin It represents the minimum dimensions of the resultant array.

To create an array using the list, use the following syntax.

 a = numpy.array([1, 2, 3])  

To create a multi-dimensional array object, use the following syntax.

>>> 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)  

Finding the dimensions of the Array


The ndim function can be used to find the dimensions of the array.

>>> import numpy as np  
>>> arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])  
  
>>> print(arr.ndim)  

Finding the size of each array element


The itemsize function is used to get the size of each array item. It returns the number
of bytes taken by each array element.

Consider the following example.

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")  

Finding the shape and size of the array


To get the shape and size of the array, the size and shape function associated with
the numpy array is used.

Consider the following example.

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.

Let's reshape the array given in the following image.

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)  

Slicing in the Array


Slicing in the NumPy array is the way to extract a range of elements from an array.
Slicing in the array is performed in the same way as it is performed in the python list.
Consider the following example to print a particular element of the array.

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.

Consider the following example to multiply two arrays.

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)  

NumPy Array Iteration


NumPy provides an iterator object, i.e., nditer which can be used to iterate over the
given array using python standard Iterator interface.

Consider the following example.

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=' ')  

NumPy Mathematical Functions


Numpy contains a large number of mathematical functions which can be used to
perform various mathematical operations. The mathematical functions include
trigonometric functions, arithmetic functions, and functions for handling complex
numbers. Let's discuss the mathematical functions.

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.

The numpy.around() function


This function returns a decimal value rounded to a desired position of the decimal.
The syntax of the function is given below.

1. numpy.around(num, decimals)  

It accepts the following parameters.

S Paramete Description
N r

1 num It is the input number.

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.

Consider the following example.

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))  

The numpy.floor() function


This function is used to return the floor value of the input data which is the largest
integer not greater than the input value. Consider the following example.

Example

1. import numpy as np  
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])  
3. print(np.floor(arr))  

The numpy.ceil() function


This function is used to return the ceiling value of the array values which is the
smallest integer value greater than the array element. Consider the following
example.

Example

1. import numpy as np  
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])  
3. print(np.ceil(arr))  

Numpy statistical functions


Numpy provides various statistical functions which are used to perform some
statistical data analysis. In this section of the tutorial, we will discuss the statistical
functions provided by the numpy.
Finding the minimum and maximum elements
from the array
The numpy.amin() and numpy.amax() functions are used to find the minimum and
maximum of the array elements along the specified axis respectively.

Consider the following example.

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))  

You might also like