Unit - 4
Unit - 4
UNIT IV
INTRODUCTION TO PYTHON
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
Python is Interpreted − Python is processed at runtime by the
interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and
interact with the
interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style
or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the
beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.
Uses of Python:
Google Colab is a document that allows you to write, run, and share Python code within
your browser. It is a version of the popular Jupyter Notebook within the Google suite
of tools. Jupyter Notebooks (and therefore Google Colab) allow you to create a
document containing executable code along with text, images, HTML, LaTeX, etc.
which is then stored in your google drive and shareable to peers and colleagues for
editing, commenting, and viewing.
Starting a document
Basic Functions
After you have created a new notebook, you will see an empty code cell. Python code
can be entered into these code cells and executed at any time by either clicking the Play
button to the left of the code cell or by pressing
Command/Ctrl+Enter. On your keyboard..
Add a new code cell by clicking the “+ Code” button in the top left corner of the
document. Add a text cell by clicking the “+ Text” button in the top left corner of the
document.
When a cell is selected, a toolbar will appear in the top right corner of the cell. This
toolbar contains functions specific to that cell. Options include moving the cell up and
down, adding comments, and deleting the cell.
Sharing a Colab notebook As with other Google Apps, Colab Notebooks can be shared.
Look for the “share” button in the top right-hand corner of the window. Google Colab
documents can also be shared in Google Drive, just you do with other types of
documents.
BASIC DATATYPES
Python Data Types are used to define the type of a variable. It defines what type
of data we are going to store in a variable. The data stored in memory can be of
many types. For example, a person's age is stored as a numeric value and his or
her address is stored as alphanumeric characters.
Python has various built-in data types which we will discuss with in this tutorial:
X=10
Y=-5
Pi= 3.14159
Gravity = 9.81
Strings (str): Used to store sequences of characters, enclosed in single ('') or double
("") quotes.
Name = “Alice”
Is_active = true
Is_registered = False
Lists (list): Used to store ordered collections of items, which can be of different data
types.
Numbers= [1,2,3,4,5]
Tuples (tuple): Similar to lists, but immutable (cannot be modified after creation).
Coordinates = (3,5)
Dictionaries (dict): Used to store key-value pairs, where each key maps to a value.
Sets (set): Used to store unique items without any specific order.
Unique_numbers = { 1,2,3,4,5}
Result = None
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a
variable to another string. The new value can be related to
its previous value or to a completely different string
altogether. For example −
The simplest way to produce output is using the print statement where you can pass
zero or more expressions separated by commas. This function converts the
expressions you pass into a string and writes the result to standard output as follows –
The raw_input([prompt]) function reads one line from standard input and returns
it as a string (removing the trailing newline).
#!/usr/bin/python
Until now, you have been reading and writing to the standard input and output.
Now, we will see how to use actual data files.
Python provides basic functions and methods necessary to manipulate files by
default. You can do most of the file manipulation using a file object.
The close() method of a file object flushes any unwritten information and closes
the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned
to another file. It is a good practice to use the close() method to close a file.
fileObject.close()
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n')
to the end of the string −
Syntax
fileObject.write(string)
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")
The read() method reads a string from an open file. It is important to note that
Python strings can have binary data. apart from text data.
fileObject.read([count])
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
This produces the following result −
Read String is : Python is
The rename() method takes two arguments, the current filename and the new
filename.
os.rename(current_file_name, new_file_name)
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
You can use the remove() method to delete files by supplying the name of the file
to be deleted as the argument.
os.remove(file_name)
#!/usr/bin/python
import os
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.
You can type a comment on the same line after a statement or expression –
Multi-Line Comments
'''
This is a multiline
comment.
'''
Docstring Comments
print(add.__doc__)
Handling an exception
If you have some suspicious code that may raise an exception, you can defend
your program by placing the suspicious code in a try: block. After the try: block,
include an except: statement, followed by a block of code which handles the
problem as elegantly as possible.
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block
Here are few important points about the above-mentioned
syntax −
● A single try statement can have multiple except statements. This is
useful when the try block contains statements that may throw
different types of exceptions.
● You can also provide a generic except clause, which handles any
exception.
● After the except clause(s), you can include an else-clause. The code
in the else-block executes if the code in the try: block does not raise
an exception.
● The else-block is a good place for code that does not need the try:
block's protection.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
This produces the following result −
Written content in the file successfully
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using
this kind of try-except statement is not considered a good programming practice
though, because it catches all exceptions but does not make the programmer
identify the root cause of the problem that may occur.
You can use a finally: block along with a try: block. The finally block
is a place to put any code that must execute, whether the
try-block raised an exception or not. The syntax of the
try-finally statement is this −
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests
the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
Python supports the following control statements. Click the following links to
check their detail.
Let us go through the loop control statements briefly
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but
you do not want any command or code to execute.
The list is a most versatile datatype available in Python which can be written as a
list of comma-separated values (items) between square brackets. Important thing
about a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-
separated values between square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated
and so on.
Accessing Values in Lists
To access values in lists, use the square brackets for
slicing along with the index or indices to obtain value
available at that index. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following
result −
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-
hand side of the assignment operator, and you can add to elements in a list with
the append() method. For example
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
Updating Tuples
Tuples are immutable which means you cannot update or
change the values of tuple elements. You are able to take
portions of existing tuples to create new tuples as the
following example demonstrates −
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
Updating Dictionary
You can update a dictionary by adding a new entry or a
key-value pair, modifying an existing entry, or deleting
an existing entry as shown below in the simple example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of items
in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would
return a dictionary type.
The Python Standard Library contains all of Python's syntax, semantics, and
tokens. It has built-in modules that allow the user to access I/O and a few other
essential modules as well as fundamental functions. The Python libraries have
been written in the C language generally. The Python standard library has more
than 200 core modules. Because of all of these factors, Python is a powerful
programming language.
Matplotlib
This library is responsible for the plotting of numerical data. It is utilized in data
analysis for this reason. An open-source library plots superior quality figures, for
example, pie outlines, scatterplots, boxplots, and diagrams, in addition to other
things.
NumPy
One of the most popular open-source Python packages, NumPy focuses on
scientific and mathematical computation. It makes it easy to work with large
matrices and multidimensional data thanks to built-in mathematical functions that
make it easy to compute. It can be used as an N-dimensional container for all
kinds of data, including linear algebra. An N-dimensional array with rows and
columns is defined by the NumPy Array Python object. It can also be used as a
random number generator because of this.
NumPy is preferred over lists in Python because it uses less memory, is faster,
and is easier to use.
Pictures, sound waves, and other parallel crude streams can be addressed as a
multi-faceted exhibit of genuine qualities involving the NumPy interface for
perception. NumPy is required for full-stack developers to use this machine
learning library.
Pandas
Pandas is an open-source library authorized under the Berkeley Programming
Conveyance (BSD). This well-known library is frequently utilized in the field of
data science. They're generally utilized for examination, control, and cleaning of
information, in addition to other things. Without having to switch to another
programming language like R, Pandas enables us to carry out straightforward data
modelling and analysis.
SciPy
Scipy is a Python library. Scientific computing, information processing, and high-
level computing are the primary uses for this open-source library. The library
contains a large number of easy-to-use methods and functions for quick and easy
computation. Scipy can be utilized for numerical calculations close by NumPy.
Some of SciPy's subpackages include cluster, fftpack, constants, integrate, io,
linalg, interpolate, ndimage, odr, optimize, signal, spatial, special, sparse, and
stats.
Scikit- learn
Additionally, Scikit-learn is a Python-based open-source machine learning
library. This library supports both supervised and unsupervised learning methods.
This library already comes pre-installed with a number of well-known algorithms
as well as the SciPy, NumPy, and Matplotlib packages. Spotify music
recommendations are the Scikit-most-learn application that is most widely used.
Seaborn
This package makes statistical model visualization possible. The library, which
is largely based on Matplotlib, makes statistical graphics possible by:
1. Variable examination by means of a Programming interface in view of
datasets.
2. Make complex representations effortlessly, including multi-plot
frameworks.
3. To compare data subsets, univariate and bivariate visualizations are
utilized.
4. A wide range of color schemes are available for pattern displays.
5. Direct relapse assessment and plotting are done consequently.
TensorFlow
TensorFlow is a fast, open-source library for numerical calculations. It is utilized
by ML and deep learning algorithms as well. It was developed by researchers in
the Google Brain group of the Google AI organization and is now widely used by
researchers in physics, mathematics, and machine learning for complex
mathematical computations.
Keras
Keras is a Python-based open-source neural network library that enables in-depth
research into deep neural networks. Keras emerges as a viable option as deep
learning becomes more common because, according to its developers, it is an API
(Application Programming Interface) designed for humans rather than machines.
Keras has a higher rate of adoption in the research community and industry than
TensorFlow or Theano. The TensorFlow backend engine should be downloaded
first before Keras can be installed.
Scrapy
Scrapy is a web scratching device that scratches numerous pages in less than a
moment. Scrapy is additionally an open-source Python library structure for
extricating information from sites. It is a high-speed, high-level scraping and
crawling web library that goes by the name "Scrapinghub ltd."
PyGame
The Standard Directmedia Library (SDL)'s graphics, audio, and input libraries
are accessible through a straightforward interface that can be used on any
platform by this library. With the Python programming language, computer
graphics, and acoustic libraries, it is used to create video games.
PyBrain
When compared to the other Python learning libraries, PyBrain is a quick and
straightforward machine learning library. From the various Python libraries that
are available, PyBrain is also an open-source library for ML algorithms that is
suitable for any beginning researcher.
Statsmodels
Statsmodels is a Python library for statistical model estimation and analysis. The
results of statistical tests and other tasks carried out in the library are of high
quality.
The interface's ease of use The Python programming language is utilized
extensively in numerous actual-world applications. Because it is a dynamically
written high-level language, its use in error debugging is rapidly growing. Python
is becoming more and more prevalent in well-known programs like YouTube and
DropBox. Clients can likewise play out numerous assignments without expecting
to type their code, because of the openness of Python libraries.
HIGH DIMENSIONAL ARRAYS
An array with multiple dimensions can represent relational tables and matrices
and is made up of many one-dimensional arrays, multi-dimensional arrays are
frequently used to store data for mathematical computations, image processing,
and maintaining records.
To understand and implement multi-dimensional arrays in Python,
the NumPy package is used. It is a Python library that gives users access to a
multidimensional array object, a variety of derived objects (such as masked arrays
and matrices), and a selection of functions for quick operations on arrays and
multi-dimensional matrices.
The standard way of Python language creates lists which are very similar to arrays
but remember, there is a very slight difference between a List and an array in
Python programming language. You can learn more about the differences
between lists vs arrays in python. In this article let’s look purely at arrays. The
following example will show the difference between the datatype of creating a
2D array created by the standard way and by using the Numpy package.
#creating 2D array without any package
arr1 = [[0]*3]*2
print(arr1)
print(type(arr1))
Let’s start with implementing a 2 dimensional array using the numpy array
method.
print("Output")
print(array_1)
print("Output")
print(array_2)