Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Python Assignment

Python

Uploaded by

Kesava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Assignment

Python

Uploaded by

Kesava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

EXCEPTION HANDLING

Many of Python’s functions and methods indicate errors or other important events by raising an
exception. An exception is an object like any other Python object, and when converted to a string
(e.g., when printed), the exception produces a message text. A simple form of the syntax for
exception handlers is this:
try:
try_suite
except exception1 as variable1:
exception_suite1

except exceptionN as variableN:
exception_suiteN

Note that the as variable part is optional; we may care only that a particular exception was raised
and not be interested in its message text. The logic works like this. If the statements in the try
block’s suite all execute without raising an exception, the except blocks are skipped. If an
exception is raised inside the try block, control is immediately passed to the suite corresponding
to the first matching exception—this means that any statements in the suite that follow the one
that caused the exception will not be executed. If The logic works like this. If the statements in
the try block’s suite all execute without raising an exception, the except blocks are skipped. If an
exception is raised inside the try block, control is immediately passed to the suite corresponding
to the first matching exception—this means that any statements in the suite that follow the one
that caused the exception will not be executed.

CUSTOM FUNCTIONS

Functions are a means by which we can package up and parameterize functionality. Four kinds
of functions can be created in Python: global functions, local functions, lambda functions, and
methods. Every function we have created so far has been a global function. Global objects
(including functions) are accessible to any code in the same module (i.e., the same .py file) in
which the object is created. Global objects can also be accessed from other modules, as we will
see in the next chapter. Local functions (also called nested functions) are functions that are
defined inside other functions. These functions are visible only to the function where they are
defined; they are especially useful for creating small helper functions that have no use elsewhere.
Lambda functions are expressions, so they can be created at their point of use; however, they are
much more limited than normal functions. Methods are functions that are associated with a
particular data type and can be used only in conjunction with the data type—they are introduced
in Chapter 6 when we cover object-oriented programming. Python provides many built-in

1
functions, and the standard library and third party libraries add hundreds more (thousands if we
count all the methods), so in many cases the function we want has already been written.

MODULES AND PACKAGES

A Python module, simply put, is a .py file. A module can contain any Python code we like. All
the programs we have written so far have been contained in a single .py file, and so they are
modules as well as programs. The key difference is that programs are designed to be run,
whereas modules are designed to be imported and used by programs.

A package is simply a directory that contains a set of modules and a file called __init__.py.
Suppose, for example, that we had a fictitious set of module files for reading and writing various
graphics file formats, such as Bmp.py, Jpeg.py, Png.py, Tiff.py, and Xpm.py, all of which
provided the functions load(), save(), and so on. We could keep the modules in the same
directory as our program, but for a large program that uses scores of custom modules the
graphics modules will be dispersed. By putting them in their own subdirectory, say, Graphics,
they can be kept together. And if we put an empty __init__.py file in the Graphics directory
along with them, the directory will become a package:

Graphics/
__init__.py
Bmp.py
Jpeg.py
As long as the Graphics directory is a subdirectory inside our program’s directory or is in the
Python path, we can import any of these modules and make use of them.

INHERITANCE IN PYTHON

One of the core concepts in object-oriented programming (OOP) languages is inheritance. It is


a mechanism that allows you to create a hierarchy of classes that share a set of properties and
methods by deriving a class from another class. Inheritance is the capability of one class to
derive or inherit the properties from another class. Benefits of inheritance are:
Inheritance allows you to inherit the properties of a class, i.e., base class to another, i.e.,
derived class. The benefits of Inheritance in Python are as follows:
 It represents real-world relationships well.
 It provides the reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.

2
 Inheritance offers a simple, understandable model structure.
 Less development and maintenance expenses result from an inheritance.

POLYMORPHISM IN PYTHON

The word polymorphism means having many forms. In programming, polymorphism means
the same function name being used for different types. The key difference is the data types and
number of arguments used in function.

# len() being used for a string


print(len("SOPHOMORES"))

# len() being used for a list


print(len([10, 20, 30]))

WRITING BINARY DATA TO FILE

It is a common and routine task in Python; the act of writing binary data to a file when you need
to save non-textual data such as images, audio files, or serialized objects. In this article, we will
explore various ways how you can write binary data to a file using Python and provide you with
code examples followed by comprehensive explanations to help you grasp the concept.

To write binary data to a file in Python, you can follow these steps:

First, you should proceed to open the file in binary mode using the open() function. When
opening the file, the mode is declared as 'wb', which stands for write in binary mode. This mode
makes sure that the data you write to the file will be treated as binary data. After the file is
opened in binary mode, you make use of the write() method to write binary data to the file. The
write() method accepts a bytes object as an argument, which contains the binary data you want to
write. After writing the binary data is finished, it is important to close the file to release system
resources. The ‘with statement’ takes care of closing the file for you, but if you are not using it,
ensure to that the close() method is called on the file object.

file_path = “path/to/file.bin”

with open (file_path, “wb”) as file:



file.close()

3
READING BINARY FILE

Reading binary files is an important skill for working with data (non-textual) such as images,
audio, and videos. Using file mode and the “read” method you can easily read binary
files. Python has the ability to handle the data and consent provides various help with certain
criteria. Whether you are dealing with multimedia files, compressed data, or custom binary
formats, Python’s ability to handle binary data empowers you to create powerful and versatile
applications for a wide range of use cases. To read a binary file:

Step 1: Open the binary file in binary mode


To read a binary file in Python, first, we need to open it in binary mode (‘”rb”‘). We can use
the ‘open()’ function to achieve this.
Step 2: Create a binary file
To create a binary file in Python, You need to open the file in binary write mode ( wb ). For
more refer to this article.
Step 3: Read the binary data
After opening the binary file in binary mode, we can use the read() method to read its content
into a variable. The” read()” method will return a sequence of bytes, which represents the
binary data.
Step 4: Process the binary data
Once we have read the binary data into a variable, we can process it according to our specific
requirements. Processing the binary data could involve various tasks such as decoding binary
data, analyzing the content, or writing the data to another binary file.
Step 5: Close the file
After reading and processing the binary data, it is essential to close the file using the “close()”
method to release system resources and avoid potential issues with file access.

# Opening the binary file in binary mode as rb(read binary)


f = open("files.zip", mode="rb")

# Reading file data with read() method


data = f.read()

NUMPY ARRAY SAND VECTORIZED COMPUTATION

NumPy is the fundamental package supported for presenting and computing data with high
performance in Python. It provides some interesting features as folows: Extension package to
Python for multidimensional arrays (ndarrays), various derived objects (such as masked arrays),
matrices providing vectorization operations, and broadcasting capabilities. Vectorization can
significantly increase the performance of array computations by taking advantage of Single

4
Instruction Multiple Data (SIMD) instruction sets in modern CPUs. Fast and convenient
operations on arrays of data, including mathematical manipulation, basic statistical operations,
sorting, selecting, linear algebra, random number generation, discrete Fourier transforms, and so
on. Efficiency tools that are closer to hardware because of integrating C/C++/Fortran code.
NumPy is a good starting package for you to get familiar with arrays and array-oriented
computing in data analysis. Also, it is the basic step to learn other, more effective tools such as
Pandas.

Linear algebra is a branch of mathematics concerned with vector spaces and the mappings
between those spaces. NumPy has a package caled linalg that supports powerful linear algebra
functions. We can use these functions to find eigenvalues and eigenvectors or to perform
singular value decomposition.
The function is implemented using the geev Lapack routines that compute the eigenvalues and
eigenvectors of general square matrices. Another common problem is solving linear systems
such as Ax = b with A as a matrix and x and b as vectors. The problem can be solved easily
using the numpy.linalg.solve function
An important part of any simulation is the ability to generate random numbers. For this purpose,
NumPy provides various routines in the submodule random. It uses a particular algorithm, caled
the Mersenne Twister, to generate pseudorandom numbers. First, we need to define a seed that
makes the random numbers predictable. When the value is reset, the same numbers wil appear
every time. If we do not assign the seed, NumPy automaticaly selects a random seed value based
on the system's random number generator device or on the clock.
NumPy also provides for many other distributions, including the Beta, bionomial, chi-square,
Dirichlet, exponential, F, Gamma, geometric, or Gumbel.

DATA ANALYSIS WITH PANDAS

Pandas is a Python package that supports fast, flexible, and expressive data structures, as well as
computing functions for data analysis. The following are some prominent features that Pandas
supports: Data structure with labeled axes. This makes the program clean and clear and avoids
common errors from misaligned data. Flexible handling of missing data. Intelligent label-based
slicing, fancy indexing, and subset creation of large datasets. Powerful arithmetic operations and
statistical computations on a custom axis via axis label. Robust input and output support for
loading or saving data from and to files, databases, or HDF5 format. Related to Pandas
installation, we recommend an easy way, that is to install it as a part of Anaconda, a cross
platform distribution for data analysis and scientific computing. You can refer to the reference at
http://docs.continuum.io/anaconda/ to download and install the library. After installation, we can
use it like other Python packages. Firstly, we have to import the following packages at the
beginning of the program.

5
>>>import pandas as pd

Let's first get acquainted with two of Pandas' primary data structures: the Series and the Data
Frame. They can handle the majority of use cases in finance, statistic, social science, and many
areas of engineering.

A Series is a one-dimensional object similar to an array, list, or column in table. Each item in a
Series is assigned to an entry in an index. By default, if no index is passed, it will be created to
have values ranging from 0 to N-1, where N is the length of the Series.

Sometimes, we want to filter or rename the index of a Series created from a Python dictionary.
At such times, we can pass the selected index list directly to the initial function, similarly to the
process in the above example. Only elements that exist in the index list wil be in the Series
object. Conversely, indexes that are missing in the dictionary are initialized to default NaN
values by Pandas. The library also supports functions that detect missing data.

The Data Frame is a tabular data structure comprising a set of ordered columns and rows. It can
be thought of as a group of Series objects that share an index (the column names). There are a
number of ways to initialize a Data Frame object. Firstly, let's take a look at the common
example of creating DataFrame from a dictionary of lists.

A Data Frame object can also be created from different data structures such as a list of
dictionaries, a dictionary of Series, or a record array. The method to initialize a Data Frame
object is similar to the examples above. Moreover, Pandas also has support for reading and
writing a Data Frame directly from or to a database such as the read_frame or write_frame
function within the Pandas module.

You might also like