Professional Documents
Culture Documents
• As using dynamic memory allocation in programming languages for example c and c++
the user does not have to pre-allocate or deallocate the memory
o Reference counting
o Garbage collection
• Former to python version 2.0, Reference counting was used by the python interpreter
for the memory management
• The object is being deallocated when the reference count becomes zero show shown
in the following figure
• The literal value 5 is an object as shown in the following figure in the previous slide.
The reference count of object 5 is incremented by 1 in the line 1. As it is dereferenced
in line 2 because its reference count becomes zero. Ultimately, object is deallocated by
the garbage collector
• When there is no method the reference count of the object can reach then a reference
cycle is being created.
• Lists, tuples, instances, classes, dictionaries as well as functions are contained by the
reference cycles
• The simplest way to create a reference cycle is to create an object which refers to itself
as in the following example
• As you can see in the following example create_cycle() creates an object x which refers
to itself, so when the functions returns, the object x will not automatically be freed
• This will cause the memory which is used by the x until the python garbage collector is
invoked
• Now, the reference count is two for the created list. Even though, since it cannot be
used again and it cannot be reached from inside the python.
• It is taken as garbage. This list is never freed in the present version of python
• Since reference cycles take computational work to find out, garbage collection should
be a scheduled activity.
• When the threshold number is greater than the result of number of allocations minus
the number of deallocations, the garbage collection run
• By importing the gc module as well as asking for the garbage collection thresholds one
can check the threshold for new objects ( the objects which known as generation 0
objects in the python)
Output:
• This means when the number of allocations in contrast to the number of deallocations
is greater than 700, then the automatic garbage collector will run
• Any portion of your code which releases large Blocks of memory are good for running
manual garbage collection
• Function can be member of a class, in which case the function is called a “method”
• Python has a large library of built-in functions: Numeric, String, Conversion, functions
for tuples and lists
Example of Function
• When we define a function then we specifies the parameters that are to be included in
the function as well as the blocks of code.
• When the basic structure of a function is completed, One can execute it directly from
the python prompt either from the another function as shown in the example in
upcoming slide
• A called function can modify the values of the arguments or parameter with the help
of reference passed in
• This modification of the values in the called function also reflects back in the calling
function as shown in the following example in upcoming slide
• These are those arguments which are passed to a function in correct positional order
• The number of arguments in the function call must match which the number of
arguments in the definition of the function
• When you will call to the printme() function then you have to pass an argument
otherwise you will get an error as shown in the following example in the upcoming
slide
Example: -
• When a function is called with some values then these values get assigned to the
arguments according to their positions in the function definition.
• In python we can call a function by using keywords. When we use this procedure to
call a function then we can change order of the arguments while calling a function
• This method allows to skip arguments or place them out of the order because the
python interpreter is able to use the keywords provided to match the values with the
parameters
• You can also make keyword calls to the printme() function as shown in the following
figure
• These are those arguments which assumes a default value when value is not provided
in the function call for that argument.
• You can get better idea about the default function by looking at the following figure
• These functions are not named in the function definition, unlike required and default
arguments
• Before the variable name of the which holds the values of all non keyword variable
arguments an asterisk (*) is placed
• During the function call if no additional arguments are specified then this tuple will
remain empty
• For creating small anonymous function you can use lambda keyword
• Lambda cannot contain commands or multiple expressions. Lambda can take any
number of arguments but it returns just one value in the form of an expression
• A direct call to print cannot be made by the anonymous function because it requires an
expression
• Lambda functions have their own local namespace and cannot access variables other
than those in their parameters as well as those in the global namespace
• Example:
Generator-Function Generator-Object
• The function automatically becomes a generator function if the body of a def contains
yield
Example:
• A generator object is returned by the generator functions. Generator objects are used
either by calling the next method on the generator object or using the generator
object in a “for in” loop
• In Python programming language functions are known as first class objects which
means that functions are objects; they can be referenced to, passed to a variable as
well as returned from another function too.
• We can defined a function inside the another function as well as can also be passed as
argument to another function
• In decorates, functions are taken as the arguments into another function and then
called inside the wrapper function
Example:
• After applying the given function to each item of a given iterable (list, tuple excreta.)
map() functions returns a map object (Which is an iterator) of the results.
o Syntax :
map(fun, iter)
Parameters
Example:
• Reduce( fun, seq) function is defined in “functools” module. This function is used to
apply a particular function passed in its argument to all of the list elements mentioned
in the sequence passed along.
Working :
• Firstly , in the sequence first two elements are selected and result is obtained
• Second step is to apply the same function to the previously attained result and the
number just succeeding the second element and the result is again sorted
• Until no more elements are left in the container this this process is continued
• Filter_none
Example:
• The filter() method is used to filter the given sequence by using a function which tests
each element in the sequence to be true or not
Syntax:
filter(function, sequence)
Parameters:
function: function that tests if each element of a
sequence true or not.
sequence: sequence which needs to be filtered, it can
be sets, lists, tuples, or containers of any iterators.
Returns:
returns an iterator that is already filtered.
Example:
Destroying
Overriding
Data Hiding Objects (Garbage
Methods
Collection)
• In spite of making a class from starch You can create a class by driving it from already
made class by listing the parent class (preexisting class) in the parentheses after the
new class name
• Attributes of parent class are inherited by the child class. Moreover, you can use these
attributes as if they were defined in the child class.
• A child class can also override data members as well as methods from the parent
Syntax:
Example:
• Example:
• Data abstraction provides only essential information about the data to the user and
hides background implementations.
• An abstract class can be considered as a blueprint for other classes, It permits you to
make a group of methods that should be made within any child classes built from your
abstract class
• A class is called an abstract class which contain one or more abstract methods. A
method which has declaration but has not any implementation is called as abstract
class
Example:
• It does not permit to access variables as well as methods directly and also it can stop
the accidental alteration of data
• As a class encapsulates all the data which are the member functions, variables etc. So a
class is an example of encapsulation
• Data hiding permits preventing the functions of a program to access directly the
internal representation of a class type
• Outside the class definition, an object’s attributes may or may not be visible. You need
to name attributes with a double underscore prefix, and those attributes then are not
be directly visible to outsiders
Example:
• You can always override your parent class methods when you may want special or
different functionality in your subclass then you override parent’s method
• The procedure by which python on regular intervals of time reclaims blocks of memory
that on longer are in use is termed garbage collection
• During program execution pythons garbage collector runs and when an object’s
reference count reaches zero, is provoked.
• When a object is assigned a new name or placed in container (list, tuple or dictionary)
it’s reference count increase.
• When an object is deleted with del, it’s reference is reassigned, or it’s reference goes
out of scope than it’s reference count decrease.
Example:
• The procedure of converts any kind of python objects such as list, dict etc into byte
streams for example 0s and 1s is called pickling or serializing or flattening or
marshalling.
Example of pickling:
Example of Unpickling:
• As other language, even python provides the runtime errors through exception
handlingMethod.
• A few of the standard exceptions which are most recurrent contain IndexError, IOError,
TypeError, ZeroDivisionError, ImportError.
• Try to access the array element whose index is out of bound and handle the
corresponding exception.
• Multiple threads within a process share the same data space with the main thread so
that sharing of information or communication between them is easier which was not
possible if they were separate processes
• Sometimes threads are called as light-weight processes. Moreover, they do not require
much memory overhead; they are cheaper than processes
• A thread has a starting, an execution order, and a result. It has also an instruction
pointer that keeps track of where within its context it is currently running
• It can temporarily be put on hold also known as sleeping while other threads are
running - this is called yielding.
• The input function is alike to raw_input, except that it assumes the input is a valid
python expression as well as returns the calculated result to you
Example:
• Before you can write either read a file, you need to open it by using a built-in function
in python which is open() function. This function creates a file object which will be
utilized to call other support methods associated with it
Syntax:
Example:
• The close method of a file object deletes any unwritten information as well as closes
the file object, after that no more writing is done
• When the reference object of a file is reassigned to another file then python
automatically closes a file. It is good to choose close() method to close a file
Syntax:
fileObject.close()
Example:
• The write() method writes any string to an open file. It strings can have binary data as
well as not just text it is an essential thing to note
• A newline character (‘\n’) to the end of the string is not added by the write() method
Syntax
fileObject.write(string)
Example:
• The read() method is used to read a string from an open file. It is essential to note that
apart from text python strings can have binary data
Syntax:
fileObject.read([count])
Example:
• To change the current position of file seek (offset, from]) method is used
• Reference position from where the bytes are to be moved are specified by the from
argument
• If from is set to 0, it means use the starting of the file as the reference position as well
as 1 means use the current position as the reference position
• If it is set 2 then the end of the file would be taken as the reference position
Example:
• The rename() method takes two arguments, the current filename as well as the new
filename
Syntax:
os.rename(current_file_name, new_file_name)
Example:
• To delete files by supplying the name of the file which has to be deleted as the
argument remove() method is used
Syntax:
os.remove(file_name)
Example:
• To create directories in the current directories you can use mkdir() method of the os
module. You have to pass an argument to this method which contains the name of the
directory to be created
Example:
Syntax:
os.getcwd()
Example:
• The directory which is passed as an argument in the method is deleted by using rmdir()
method
Syntax:
os.rmdir('dirname')
Example:
• A file which contains a group of functions which you want to include in your
application
Example:
• Packages are a way of structuring many packages as well as modules which helps in a
well organized hierarchy of a data set, making the directories as well as modules easy
to access
• As same as the alike drives as well as folders in an operating system to help to store
files, similarly packages helps us in storing sub-package as well as modules, so that user
can use them when essential
• To give information to the python that a specific directory is a package, a file named
_init_.py is created inside it as well as then it is considered as a package and modules
and sub-packages can be created within it
• Initialization code is used to code the _init_.py file for the package. An _int_.py file can
also be left blank
• Firstly, a directory is created as well as a package name is given to it, preferably related
to its operation
• At the end an _init_.py file is created inside the directory which helps the python to
know that the directory is a package
Package 1 Package 2
• Logging module in the python is very powerful module which is designed to meet the
needs of the enterprise teams as well as the beginners
• You can integrate your log messages with the ones from the third-party python
libraries to generate a homogeneous log for your application because logging is used
by most of the third-party python libraries
import logging
• You can use something called a “logger” to log that messages which you want to see.
By default, there are 5 standard levels demonstrating the severity of events
• Each has a corresponding method which can be used to log events at that level of
severity.
• DEBUG
• INFO
• ERROR
• CRITICAL
• The logging module gives you with a default logger which permits you to get started
without needing to do much configuration.
methods for each level can be called as shown in the following example:
• A one-dimensional array which is capable of holding data of any type such as python
objects, float, string, integer etc.) is known as series. The axis labels are collectively
called index
Output
• Index passed must be of the same length if an data is an ndarray. By default index will
be range(n) where n is an array length i.e [0,1,2,3…. Range(len(array))-1) when no
index is passed
Example:
Output
• If no index is specified then dict can be passed as input. After that, dictionary keys are
taken in a sorted order to construct index. The values in data corresponding to the
labels in the index will be pulled out if index is passed
Example:
Output
• An index must be provided if data is a scalar value. To match the length of index the
value will be repeated
Example:
Output
• A two dimensional data structure is known as data frame i.e., data is aligned in a
tabular fashion in rows as well as columns
Output
Example:
Output
Example:
Output
• All the ndarrays should be of same length. The length of the index should equal to the
length of the array, if index is passed
• By default index will be range(n), where n is the array length if no index is passed
Example:
Output
• To create a DataFrame list of dictionaries can be passed as input data. The dictionary
keys are by default taken as column names
Example:
Output
• To form a DataFrame a series of dictionary can be passed. The resultant is the union of
all the series indexes passed
Example:
Output
Example:
Output
• This will be understand by you by adding a new column to an existing data frame
Example:
Example:
Selection by integer
Selection by Label Slice Rows
location
Example:
Output
Example:
Output
Example:
Output
• By using the append function news rows are added. This function will append the rows
at the end
Example:
Output
Step 1: Create two excel files which contains some data as you need
Step 2: Now, convert these excel files into CSV format as shown in the following figure
Step 1: Create a CSV file as we have created a CSV file named “sheet1.csv”
Step 2: Write a code to open CSV file as shown in the following figure
Step 1: Wire code two make two different tables to which you want to concatenate
Step 1: Create a table according to your need as we have created in the following figure
Step 1: Create a table according to your need as shown in the following figure
• Numpy is a core library for scientific computing and it stands for ‘Numerical Python’.
Numpy contains a powerful n-dimensional array object which provides tools for
integrating c, c++ etc
• For generic data Numpy array can also be used as an efficient multi-dimensional
container.
• Numpy array is a N-dimensional array object in the form of rows and columns. We can
initialize Numpy arrays from nested Python lists and access it elements.
• It is a table of elements which are of same type and indexed by a tuple of positive
integers
• NumPy’s array class is called ndarray. Even it is known by the alias array
• Matplotlib can be used in Python scripts, the Python along with IPython shells, the
Jupyter notebook, web application servers as well as four graphical user interface
toolkits.
• Matplotlib tries to make hard things possible as well as easy things easy
• With few lines of code you can generate plots, power spectra, histograms, bar charts,
scatterplots and error charts
• The pyplot module provides a MATLAB-like interface for simple plotting, specially when
combined with python
• you have full control of, line styles, font properties, axes properties etc, through an
object oriented interface or through a collection of functions familiar to MATLAB users.
Example:
features help in −
Step 1: Create a table according to your need and data of which you want to visualize in
the form of graphs
Step 1: Create a list k as shown in figure and pass it through the plot to get visualization
through graph of this list. As we have given label of y axis similarly you can give x axis label
as well
• Data science is field of study which includes extraction of meaningful information form
the large amount of data by using several scientific methods, algorithms as well as
processes.
• Data science has developed because of the evolution of mathematical statistics, big
data as well as data analysis
• Data science allows you for transmitting a business problem into a research project and
then convert it back into a practical solution
• A system which can learn from example through self-improvement as well as without
being explicitly coded by programmer is an example of machine learning
• In machine learning best thing is that the computer can be trained to automate tasks
which are impossible for an human being
• A computer software that acts as the network of neurons in a brain is called deep
learning.
• It is called deep learning because it makes use of deep neural network. Even though, it
is a part of machine learning
• All the layers which comes between these two layers are called as Hidden layers. The
word deep means the network join neurons in more than two layers
• The neuron will process and then propagate the input signal which is received by the
layer above it
• The strength of the signal which is given to the neuron in the next layer depend on the
activation function, bias along with weight
• Large amount of data is consumed by the network and operates them through
multiple layers; the network can learn more and more complex features of the data at
each layer
• When machine learning algorithms runs it contains a sequence of tasks which includes
pre-processing, feature extraction, model fitting as well as validation stages
• Such as when classifying text documents may involve text segmentation as well as
cleaning, extracting features, and training a classification model with cross validation
• Even though there are many libraries which we can use for each stage, in large amount
of datasets connecting the dots is not as easy as it may look
• Most machine learning are not designed for distributed computation either they do
not provide any maintenance for pipeline creation as well as tuning
• The machine learning pipeline is a high-level API for Mllib which lives under the
“spark.ml” package
• Transformer as well as Estimator both are the basic types of pipeline stages
• Such as tokenizer is a transformer which transforms a dataset with text into an dataset
with tokenized words
• To procedure a model, an estimator must be first fit on the input dataset. Which is a
transformer that transforms the input dataset for example logistic regression is an
estimator which trains on a dataset with labels as well as features and produces a
logistic regression
• As Django contains batteries which makes it easier for Django developers to complete
common web development tasks such as user authentication, URL routing as well as
database schema migration
• Whereas, flash is lightweight, simple as well as minimalist web framework. It does not
have some built-in features as provided by the Django
• To keep the core of a web application simple as well as extensible it is very helpful for
developers
• Not like flash, By providing a ready-to-use admin framework Django makes it easier for
users to manage common project administration tasks
• The developers even have option to customize the admin interface to meet particular
business requirements
• To simplify website content administration as well as user management they can even
take advantage of the admin interface
Template Engine
• Flash is made based on jinja2 template engine. Jinja2 is also inspired by Django’s
template system as a fully featured template engine for python
• To define a web application’s user facing layer without putting extra time as well as
efforts Django comes with a built-in template engine which enables the developers to
do this
• Not like flash, Django has a built-in bootstrapping tool named Django-admin
• Django also permits developers to divide a single project into a number of applications
• To create new applications with the project Django-admin can be used by the
developers. To add functionality to the web applications based on varied business
requirements they can further use the applications
• To work with widely used databases such as MySQL, Oracle, SQLITE as well as
PostgreSQL developers can use the ORM system
• To perform common database operations without writing lengthy SQL queries the
ORM system also permit the developers
• In contrast Django, flash does not have a built-in ORM system. It requires developers to
work with databases and perform database operations via SQLAlchemy.
• By using SQLAlchemy as SQL toolkit as well as ORM system for python developers can
work with databases
• Flask requires developers to each project as a single application. While, the developers
can add multiple models as well as views to the same application. In contrast, Django
allows developers to divide a project into multiple applications
• Henceforth, it becomes easier for developers to write single applications as well as add
functionality to the web application by integrating the applications into the project
• The small applications are further helpful for developers to extend as well as maintain
the web applications written in python
• Django MVC architecture provides solution of lots of problems which were faced in
traditional approach for web development
• On the internet for every website there are three key components either code
partitions which are Input Logic, Business Logic as well as UI Logic
• The input logic is the dataset as well as how the data gets to organized in the database
these are the particular tasks to achieve by these partitions of code
• It just takes that input as well as sends it to the database in the wanted format
• The output from the server in the HTML either desired format is managed by the
business logic which is the key controller
• The UI Logic as the name suggests are the HTML, CSS and JavaScript pages.
• All the code was written in the single file when traditional approach was used. Every
piece of code increases the webpage size, which is downloaded as well as rendered by
the browser
• It was not a big issue in the prior time, the webpages were largely static and websites
as well as did not contain much multimedia and large coding
• Even, this architecture makes difficulty for developers during testing as well as
maintaining the project as everything is inside one file
• The MVC pattern has three components, namely Model, View, as well as Controller
Controller
Model View
• This difference between the components helps the developers to concentrate on one
aspect of the web- application as well as therefore, better code for one functionality
better testing, scalability as well as debugging
1. Model
• It is the part of the web application what acts as a mediator in the middle of the
website interface as well as the database
• In technical terms, it is the object which implements the logic for the application’s
data domain
• There are times, when data from a particular dataset may be taken by the application
as well as directly send it to the view without needing any database then the dataset is
considered as a model
• We need to have some kind of database as we must be requiring some user input even
though we are creating a simple blog site if we want any sort of website
The Model is the component which contains Business Logic in Django architecture
For example
• You are actually sending information to the controller which then transfers it to the
models which in turn applies business logic on it as well as store in the database, when
you sign up on any website
2. View
• User interface of the web-application is known as view as well as it contains the parts
such as HTML, CSS and frontend technologies. Commonly, this UI creates from the
models components i.e., the content comes from the Models components
For example
• When you interact with the website either click on any link, the new webpages that
website produces is actually the particular views which stores as well as generates
when we are interacting with the specific components
• The controller is the main control component means controller manages the user
interaction as well as selects a view according to the model
• The prime task of the controller is to select a view component according to the user
interaction as well as apply the model component as well
For example
• After combining two previous examples, we can very clearly see that the component
which is actually selecting diverse views as well as transferring the data to the model’s
component is the controller