Python Material
Python Material
Unit-1
Introduction to Python- Introduction to Python programming language - Setting up
development environment - Basic programming concepts. Object-oriented
Programming in Python - Introduction to object-oriented programming - Classes,
methods, and properties in Python - Inheritance, polymorphism, and encapsulation.
Introduction
What is Program
input: Get data from the keyboard, a file, or some other device.
output: Display data on the screen or send data to a file or other device.
math: Perform basic mathematical operations like addition and multiplication.
conditional execution: Check for certain conditions and execute the
appropriate code.
repetition: Perform some action repeatedly, usually with some variation.
Python History
When he began implementing Python, Guido van Rossum was also reading the
published scripts from “Monty Python's Flying Circus”, a BBC comedy series from
the 1970s. Van Rossum thought he needed a name that was short, unique, and
slightly mysterious, so he decided to call the language Python.
Python was first introduced by Guido Van Rossum in 1991 at the National
Research Institute for Mathematics and Computer Science, Netherlands.
Though the language was introduced in 1991, the development began in the
1980s. Previously van Rossum worked on the ABC language at Centrum
Wiskunde & Informatica (CWI) in the Netherlands.
High level language will be in human readable form and are easy to write as
well as compile or interpret.
Interactive mode is a command line shell which gives immediate feedback for
each statement.
The programming languages which can fulfill the needs of a wide variety of
domains are called as general purpose programming languages.“
These languages can fulfill more than one purpose, for example they can be apt
for mathematical calculations, research work and application development at the
same time.
Example
Java can be used for developing interactive web pages as well as making
games.
C++ can be used for writing applications as well as developing system
programs.
Python, Perl, Ruby can be used for web programming as well as
development of desktop
applications.
The normal mode is the mode where the scripted and finished .py files are run in
the Python interpreter.
They do not require the compilation step and are rather interpreted. Eg: python,
php
Features of Python
Easy to Learn and Use: Python is easy to learn and use. It is developer-friendly
and high level programming language.
Free and Open Source: Python language is freely available at official web
address. The source-code is also available. Therefore it is open source.
Large Standard Library: Python has a large and broad library and provides rich
set of module and functions for rapid application development.
Integrated: It can be easily integrated with languages like C, C++, JAVA etc.
Python Architecture:
Applications of python
1) Web Applications
The GUI stands for the Graphical User Interface, which provides a smooth
interaction to any application. Python provides a Tk GUI library to develop a
user interface. Some popular GUI libraries are given below.
Tkinter or Tk
wxWidgetM
Kivy (used for writing multitouch applications )
PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. These
applications are computer program which are used commands to execute.
This kind of application was more popular in the old generation of computers.
Python can develop this kind of application very effectively. It is famous for
having REPL, which means the Read-Eval-Print Loop that makes it the most
suitable language for the command-line applications.
Python provides many free library or module which helps to build the command-
line apps.
The necessary IO libraries are used to read and write.
It helps to parse argument and create console help text out-of-the-box. There are
also advance libraries that can develop independent console apps.
4) Software Development
Python is useful for the software development process. It works as a support
language and can be used to build control and management, testing, etc.
SCons is used to build control.
Buildbot and Apache Gumps are used for automated continuous compilation
and testing.
Round or Trac for bug tracking and project management
5) Scientific and Numeric
This is the era of Artificial intelligence where the machine can perform the task
the same as the human.
Python language is the most suitable language for Artificial intelligence or
machine learning.
It consists of many scientific and mathematical libraries, which makes easy to
solve complex calculations.
Implementing machine learning algorithms require complex mathematical
calculation.
Python has many libraries for scientific and numeric such as Numpy, Pandas,
Scipy, Scikit-learn, etc.
If you have some basic knowledge of Python, you need to import libraries on the
top of the code. Few popular frameworks of machine libraries are given below.
SciPy , Scikit-learn, NumPy , Pandas, Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are
an example of a business application. This kind of application requires
extensively, scalability and readability, and Python provides all these features.
Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python
are TimPlayer, cplay, etc. The few multimedia libraries are given below.
8) 3D CAD Applications
Python contains many libraries that are used to work with the image. The image
can be manipulated according to our requirements. Some libraries of image
processing are given below.
Limitations of Python
Running Python:
Here are the ways with which we can run a Python script.
Interactive Mode
Command Line
IDE (PyCharm)
Interactive Mode
In Interactive Mode, you can run your script line by line in a sequence.To enter in
an interactive mode, you will have to open Command Prompt on your windows
machine and type ‘python’ and press Enter.
Command Line
To run a Python script store in a ‘.py’ file in command line, we have to write
‘python’ keyword before the file name in the command prompt.
IDE (PyCharm)
Operators in python
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 12
SV.KRISHNA., HOD IN COMPS Python
4. Bitwise oeprators
5. Assignment operators
6. Ternary Operator
7. Special operators
1) Arithmetic Operators
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulo operator
// ==>Floor Division operator
** ==>Exponent operator or power operator
Program
a=10
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a%b=',a%b)
print('a**b=',a**b)
Output
a+b= 12
a-b= 8
a*b= 20
a/b= 5.0
a//b= 5
a%b= 0
a**b= 100
Note
/ operator always performs floating point arithmetic. Hence it will always returns
float value. But Floor division (//) can perform both floating point and integral
arithmetic. If arguments are int type then result is int type. If atleast one
argument is float type then result is float type.
We can use +,* operators for str type also. If we want to use + operator for str
type then compulsory both arguments should be str type only otherwise we will
get error.
If we use * operator for str type then compulsory one argument should be int and
other argument should be str type.
2) Relational Operators
Program
a=10
b=20
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
print("a <= b is ",a<=b)
print("a == b is ",a==b)
print("a != b is ",a!=b)
Output
a > b is False
a >= b is False
a < b is True
a <= b is True
a == b is False
a != b is True
Note
Eg:
1) 10<20 ==>True
2) 10<20<30 ==>True
3) 10<20<30<40 ==>True
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 14
SV.KRISHNA., HOD IN COMPS Python
4) 10<20<30<40>50 ==>False
3) Logical Operators
and, or ,not
and ==>If both arguments are True then only result is True
or ==>If atleast one arugemnt is True then result is True
not ==>complement
0 means False
non-zero means True
empty string is always treated as False
Program
a=10
b=20
c=0
print("a and b is ",a and b)
print("a or b is ",a or b)
print("not b is ",not b)
print("c and b is ",c and b)
print("c and b is ",c or b)
print("not c is", not c)
Output:
a and b is 20
a or b is 10
not b is False
c and b is 0
c and b is 20
not c is True
4)Bitwise Operators
Bitwise operators acts on bits and performs bit by bit operation.We can apply
these operators bitwise. These operators are applicable only for int and boolean
types. By mistake if we are trying to apply for any other type then we will get
Error.
& (bitwise and),| (bitwise or), ^(bitwise xor), ~ (bitwise complement),<< (bitwise
left shift), >> (bitwise right shit)
& ==> If both bits are 1 then only result is 1 otherwise result is 0
| ==> If atleast one bit is 1 then result is 1 otherwise result is 0
^ ==>If bits are different then only result is 1 otherwise result is 0
~ ==>Bitwise complement operator 1==>0 & 0==>1
<< ==>Bitwise Left shift
>> ==>Bitwise Right Shift
Note:
The most significant bit acts as sign bit. 0 value represents +ve number where as
1 represents -ve value. Positive numbers will be represented directly in the
memory where as -ve numbers will be represented indirectly in 2's complement
form.
Program
a=10
b=4
print("a & b =", a & b)
print("a | b =", a | b)
print("~a =", ~a)
print("a ^ b =", a ^ b)
print("a<<b=",a<<b)
print("a>>b=",a>>b)
Output:
a&b=0
a | b = 14
~a = -11
a ^ b = 14
a<<b= 160
a>>b= 0
5) Assignment Operators
Program:
a = 21
b = 10
c=0
c += a
print("Line 2 - Value of c is ", c )
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c =2
c %= a
print("Line 5 - Value of c is ", c)
c **= a
print("Line 6 - Value of c is ", c)
c //= a
print("Line 7 - Value of c is ", c)
Output:
Line 2 - Value of c is 21
Line 3 - Value of c is 441
Line 4 - Value of c is 21.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
6) Ternary Operator
Program
a,b=10,20
x=30 if a<b else 40
print(x)
Output:
30
Program
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)
Output:
Enter First Number:4
Enter Second Number:5
Minimum Value: 4
7) Special Operator
1. Identity Operator
We can use identity operators for address comparison. There are two identity
operators are available
1. is
2. is not
r1 is r2 -- returns True if both r1 and r2 are pointing to the same object
r1 is not r2 -- returns True if both r1 and r2 are not pointing to the same
object
Program
a="VSU"
b="VSU"
print(id(a))
print(id(b))
print(a is b)
print(a is not b)
Output:
65621440
65621440
True
False
2. Membership Operator
We can use Membership operators to check whether the given object present in
the given collection.(It may be String, List, Set, Tuple or Dict) .
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 18
SV.KRISHNA., HOD IN COMPS Python
in- Returns True if the given object present in the specified location
not in- Returns if the given object is not present in the specified location
Program
x="hello learning Python is very easy!!!"
print('h' in x)
print('d' in x)
print('d' not in x)
print('Python' in x)
Output:
True
False
True
True
Keywords
Python Keywords are special reserved (fixed) words which convey a special
meaning to the compiler/interpreter.
Each keyword has a special meaning and a specific operation.
These keywords can't be used as variable. Keywords are case sensitive
There are 35 keywords in Python 3.7, 3.8
All the keywords except True, False and None are in lowercase and they must be
written as it is.
Example
import keyword
keyword.kwlist
Multiple Assignment
Python allows us to assign a value or values to multiple variables in a single
statement which is also known as multiple assignment.
1. Assigning single value to multiple variables
2. Assigning multiple values to multiple variables
x=y=z=50
print(x)
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 19
SV.KRISHNA., HOD IN COMPS Python
print(y)
print(z)
Output: 50 50 50
a,b,c=5,10,15
print(a)
print(b)
print(c)
Output:
5 10 15
Data Types
Data type represent the type of data present inside the variable.
In Python we cannot required to specify the type explicitly. Based on value
provided, the type will be assigned automatically. Hence python is dynamically
typed language.
Python contains following data types:
int, float, complex, bool, range, str, list, tuple, set, dict, None
1) Int datatype
We can use int datatype to represent the whole numbers(integral numbers).
Integral Numbers means number without decimal points.
In python2 we have long datatype to represent very large integral values. Eg:
908090800L, -0x1929292L
In python3 there is no long type explicitly and we can represent long values also
by using int type only. Size is not fixed in python.
Syntax: Variable Name= Integer Value (or) Decimal (or) Binary (or) Octal (or)
Hexa Decimal
We can represent the int values in the following ways.
1. Decimal 2. Binary 3. Octal 4. Hexa
Examples
Base Conversions
Examples
2) Float Datatype:
We use float type to represent the floating point values (decimal values).
Eg: f=10.5
We can also represent floating point values by using exponential forms(scientic
notations)
Eg:a=1.2e3 a=6E+5 a=3.12E4
>>> a
1200.0
instead of e we can use E. The main advantage of exponential form is we can
represent big values in less memory.
Syntax: Variable Name= Float Values
Note: We can represent int values in decimal, binary octal and hexa decimal forms.
But we can represent the float values by using decimal form.
Examples
3) Complex Datatype:
A complex number is of two parts one is real part and other one is imaginary
part.
Eg: 3+5j, 10+5.5j, 0.5+0.1j
In the real part if we use int value that we can specify either by decimal, octal,
binary or hexadecimal form.But imaginary part should be specified only by using
decimal form.
Complex datatype has some inbuilt attributes to retrieve the imaginary part and
real part.
Eg: c=5+3j, c.real c.imag
Syntax: Variable Name= Complex Value
4) Bool Datatype
We can use this datatype to represent boolean values. The boolean values are
True and False.
Internally python True as 1 and False as 0.
Syntax: Variable Name=Boolean value
Eg: a=True
type(a)-> True.
5) Range Datatype
6) Str Datatype
7) List Datatype
Examples
8) Tuple Datatype
Tuple data type is exactly same as list data type except that it is immutable. i.e
we cannot change values. Tuple elements can be represented within parenthesis
().
Examples
9) Set Datatype
Examples
None means Nothing or No value associated. If the value is not available, then to
handle such type of cases None introduced. It is something like null value in Java.
Examples
Types of Modes
1)Interactive Mode
Interactive mode is great for quickly and conveniently running single lines or
blocks of code. The python shell that comes with a basic python installation.
The “>>>” indicates that the shell is ready to accept interactive commands. So
for example if you want to print the statement “this is interactive mode”, simply
type the appropriate code and hit enter.
Example
2) Script Mode
If instead you are working with more than a few lines of code, or you’re ready to
write an actual program, script mode is what you need.
Instead of having to run one line or block of code at a time, you can type up all
your code in one text file, or script, and run all the code at once.
In the standard Python shell you can go to “File” -> “New File” (or just hit Ctrl +
N) to pull up a blank script in which to put your code.
Then save the script with a “.py” extension. You can save it anywhere you want
for now, though you may want to make a folder somewhere to store your code as
you test Python out.
To run the script, either select “Run” -> “Run Module” or press F5.
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a
block of code. Python uses indentation. A code block (body of
a function, loop etc.) starts with indentation.
Indentation in Python refers to the (spaces and tabs) that are used at the
beginning of a statement. The statements with the same indentation belong to
the same group called a suite.
Eg: if True:
print('Hello')
Python Comments
1) Single Line Comments
Comments are very important while writing a program. It describes what's going
on inside a program so that a person looking at the source code does not have a
hard time figuring it out.
In Python, we use the hash (#) symbol to start writing a comment.
Eg:#This is a comment
#print out Hello
print('Hello')
Output:
Hello
2)Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line.
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used
as multi-line comment as well.
Example:
Output
Hello World
1) Input Statements
In Python 2 the following 2 functions are available to read dynamic input from the
keyboard.
1. raw_input()
2. input()
1. raw_input()
This function always reads the data from the keyboard in the form of String
Format. We have to convert that string type to our required type by using the
corresponding type casting methods.
Eg:
x=raw_input("Enter First Number:")
print(type(x)) It will always print str type only for any input type
2.input()
input() function can be used to read data directly in our required format. We are
not required to perform type casting.
x=input("Enter Value)
type(x)
10 ===> int
"VSU"===>str
10.5===>float
True==>bool
2) Output Statements
Print()
We use the print() function to output data to the standard output device
(screen). We can also output data to a file.
Example
a,b,c=10,20,30
print(a,b,c,sep=',')
print(a,b,c,sep=':')
Output:
Example
print("Hello",end=' ')
print("VSU",end=' ')
print("mca")
Output:
3) Formatted String
Python uses C-style string formatting to create new, formatted strings. The "%"
operator is used to format a set of variables enclosed in a "tuple" (a fixed size
list), together with a format string, which contains normal text together with
"argument specifiers", special symbols like "%i","%f","%s" and "%d".
%i====>int
%d====>int
%f=====>float
%s======>String type
Syntax print("formatted string" %(variable list))
Example-1
a=10
b=20
c=30
print("a value is %i" %a)
print("b value is %d and c value is %d" %(b,c))
Output
a value is 10
b value is 20 and c value is 30
Example-2
s="vsu"
list=[10,20,30,40]
print("Hello %s ...The List of Items are %s" %(s,list))
Output
Hello vsu ...The List of Items are [10, 20, 30, 40]
4) format()
The format() method formats the specified value(s) and insert them inside the
string's placeholder.
The placeholder is defined using curly brackets: {}. The placeholders can be
identified using named indexes {price}, numbered indexes {0}, or even empty
placeholders {}.
The format() method returns the formatted string. print() with replacement
operator {}
Syntax
string.format(value1, value2...)
Example
#named indexes:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)
print(txt1)
print(txt2)
print(txt3)
Output
5) eval()
Example-1
x =eval(“10+20+30” )
print(x)
Output 60
to bind the data and the functions that work on that together as a single unit so that no
other part of the code can access this data.
Class :
A class is a collection of objects. A class contains the blueprints or the prototype from
which the objects are being created. It is a logical entity that contains some attributes
and methods.
Classes provide a means of bundling data and functionality together. Creating a new
class creates a new type of object, allowing new instances of that type to be made.
Each class instance can have attributes attached to it for maintaining its state. Class
instances can also have methods (defined by their class) for modifying their state.
Ex :
class Vsu:
When an object of a class is created, the class is said to be instantiated. All the
instances share the attributes and the behavior of the class. But the values of those
attributes, i.e. the state are unique for each object. A single class may have any
number of instances.
Ex:
class Vsu:
sname=”studentname”
Htno=”123456”
def printData(self):
print(sname)
print(Htno)
obj= Vsu() # here obj is object and Vsu is the class. => this process is called
instantiation.
Obj.printData()
Output:
studentname
123456
Note: The Self Parameter does not call it to be Self, You can use any other name
instead of it
All instances of a class exchange class variables. They function independently of any
class methods and may be accessed through the use of the class name. Here's an
illustration:
Code:
1. class Person:
2. count = 0 # This is a class variable
3. def __init__(self, name, age):
4. self.name = name # This is an instance variable
5. self.age = age
6. Person.count += 1 # Accessing the class variable using the name of the cl
ass
7. person1 = Person("ABCD", 25)
8. person2 = Person("XYZ", 30)
9. print(Person.count)
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 33
SV.KRISHNA., HOD IN COMPS Python
Constructor
__init__() method
The __init__ method is similar to constructors in C++ and Java. Constructors are used to
initializing the object’s state. Like methods, a constructor also contains a collection of
statements(i.e. instructions) that are executed at the time of Object creation. It runs as
soon as an object of a class is instantiated. The method is useful to do any initialization
you want to do with your object.
p = Person('vsu')
p.say_hi()
__str__() method
Python has a particular method called __str__(). that is used to define how
a class object should be represented as a string.
Python Default Constructor
When we do not include the constructor in the class or forget to declare it, then that
becomes the default constructor. It does not perform any task but initializes the
objects. Consider the following example.
Example
1. class Student:
2. roll_num = 101
3. name = "vsu"
4. def display(self):
5. print(self.roll_num,self.name)
6. st = Student()
7. st.display()
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("vsu", "mca")
x.printname()
Create a class named Student, which will inherit the properties and methods from
the Person class:
class Student(Person):
pass
Use the Student class to create an object, and then execute the printname method:
x = Student("VSU", "MCA")
x.printname()
The above inheritance is called single inheritance. [One base class and one derived
class].
1. class class1:
2. <class1 declarations>
3. class class2(class1):
4. <class2 declarations>
5. class class3(class2):
6. <class3 declarations>
7. ……….
Python provides us the flexibility to inherit multiple base classes in the child class.
1. class Base1:
2. <class declarations>
3. class Base2:
4. <class declarations>
5. class BaseN:
6. <class declarations>
7.
7.
7. class Derived(Base1, Base2, ...... BaseN):
8. <class declarations>
The issubclass(sub, sup) method is used to check the relationships between the
specified classes. It returns true if the first class is the subclass of the second class, and
false otherwise.
The isinstance() method is used to check the relationship between the objects and
classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.
Method Overriding
We can provide some specific implementation of the parent class method in our child
class. When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to
perform method overriding in the scenario where the different definition of a parent
class method is needed in the child class.
Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Data abstraction in python
Polymorphism
That is, the same entity (method or operator or object) can perform different operations
in different scenarios.
Example:
class Polygon:
# method to render a shape
def render(self):
print("Rendering Polygon...")
class Square(Polygon):
# renders Square
def render(self):
print("Rendering Square...")
class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")
s1.render()
# create an object of Circle
c1 = Circle()
c1.render()
UNIT-II
Python Libraries and Packages - Working with popular Python libraries such as
NumPy, Pandas, and Matplotlib - Installing, managing, and publishing Python packages
using pip - Using Python virtual environments effectively.
Module in Python
The module is a simple Python file that contains collections of functions and
global variables and with having a .py extension file. It is an executable file and
to organize all the modules we have the concept called Package in Python.
1. Datetime
2. Regex
3. Random etc.
Example: Save the code in a file called demo_module.py
def myModule(name):
print("This is My Module : "+ name)
Import module named demo_module and call the myModule function inside it.
import demo_module
demo_module.myModule("Math")
Package in Python
The package is a simple directory having collections of modules. This directory
contains Python modules and also having __init__.py file by which the interpreter
interprets it as a Package. The package is simply a namespace. The package also
contains sub-packages inside it.
Examples of Packages:
1. Numpy
2. Pandas
Example:
Student(Package)
| __init__.py (Constructor)
| details.py (Module)
| marks.py (Module)
| collegeDetails.py (Module)
Library in Python
The library is having a collection of related functionality of codes that allows you to
perform many tasks without writing your code. It is a reusable chunk of code that
we can use by importing it into our program, we can just use it by importing that
library and calling the method of that library with a period(.). However, it is often
assumed that while a package is a collection of modules, a library is a collection of
packages.
Examples of Libraries:
1. Matplotlib
2. Pytorch
3. Pygame
4. Seaborn etc.
Numpy
NumPy stands for numeric python which is a python package for the computation and
processing of the multidimensional and single dimensional array elements.
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
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 39
SV.KRISHNA., HOD IN COMPS Python
On the Windows operating system, The SciPy stack is provided by the Anaconda which
is a free distribution of the Python SciPy package.
Linux
In Linux, the different package managers are used to install the SciPy stack. The
package managers are specific to the different distributions of Linux. Let's look at each
one of them.
Ubuntu
Execute the following command on the terminal.
$ sudo apt-get install python-numpy
$ python-scipy python-matplotlibipythonipythonnotebook python-pandas
$ python-sympy python-nose
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.
>>> 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.
>>> numpy.array(object, dtype = None, copy = True, order = None, subok = False, nd
min = 0)
The parameters are described in the following table.
S Paramet Description
N er
2 dtype We can change the data type of the array elements by changing
this option to the specified type. The default is none.
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.
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")
Output:
Each item contains 8 bytes.
Finding the data type of each array item
To check the data type of each array item, the dtype function is used. Consider the
following example to check the data type of the array items.
Example
#finding the data type of each array item
import numpy as np
a = np.array([[1,2,3]])
print("Each item is of the type",a.dtype)
Output:
Each item is of the type int64
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)
Output:
Array Size: 7
Shape: (1, 7)
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)
Output:
printing the original array..
[[1 2]
[3 4]
[5 6]]
printing the reshaped array..
[[1 2 3]
[4 5 6]]
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])
Output:
2
5
Linspace
The linspace() function returns the evenly spaced values over the given interval. The
following example returns the 10 evenly separated values over the given interval 5-15
Example
1. import numpy as np
2. a=np.linspace(5,15,10) #prints 10 values which are evenly spaced over the given
interval 5-15
3. print(a)
NumPy Datatypes
The NumPy provides a higher range of numeric data types than that provided by the
Python. A list of numeric data types is given in the following table.
S Data Description
N type
5 int8 It is the 8-bit integer identical to a byte. The range of the value is
-128 to 127.
14 float16 It is the half-precision float. 5 bits are reserved for the exponent.
10 bits are reserved for mantissa, and 1 bit is reserved for the
sign.
15 float32 It is a single precision float. 8 bits are reserved for the exponent,
23 bits are reserved for mantissa, and 1 bit is reserved for the
sign.
16 float64 It is the double precision float. 11 bits are reserved for the
exponent, 52 bits are reserved for mantissa, 1 bit is used for the
sign.
Numpy.empty
As the name specifies, The empty routine is used to create an uninitialized array of
specified shape and data type.
The syntax is given below.
1. numpy.empty(shape, dtype = float, order = 'C')
It accepts the following parameters.
o Shape: The desired shape of the specified array.
o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.
Example
import numpy as np
arr = np.empty((3,2), dtype = int)
print(arr)
Output:
[[ 140482883954664 36917984]
[ 140482883954648 140482883954648]
[6497921830368665435 172026472699604272]]
NumPy.Zeros
This routine is used to create the numpy array with the specified shape where each
numpy array item is initialized to 0.
The syntax is given below.
numpy.zeros(shape, dtype = float, order = 'C')
It accepts the following parameters.
o Shape: The desired shape of the specified array.
o dtype: The data type of the array items. The default is the float.
o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.
Example
import numpy as np
arr = np.zeros((3,2), dtype = int)
print(arr)
Output:
[[0 0]
[0 0]
[0 0]]
NumPy.ones
This routine is used to create the numpy array with the specified shape where each
numpy array item is initialized to 1.
The syntax to use this module is given below.
1. numpy.ones(shape, dtype = none, order = 'C')
It accepts the following parameters.
o Shape: The desired shape of the specified array.
o dtype: The data type of the array items.
o Order: The default order is the c-style row-major order. It can be set to F for
FORTRAN-style column-major order.
Example
import numpy as np
arr = np.ones((3,2), dtype = int)
print(arr)
Output:
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 45
SV.KRISHNA., HOD IN COMPS Python
[[1 1]
[1 1]
[1 1]]
MATPLOTLIB
What is Matplotlib?
Matplotlib is a low level graph plotting library in python that serves as a visualization
utility.
Matplotlib was created by John D. Hunter.
Matplotlib is open source and we can use it freely.
Matplotlib is mostly written in python, a few segments are written in C, Objective-C and
Javascript for Platform compatibility.
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of Matplotlib
is very easy.
Install it using this command:
C:\Users\Your Name>pip install matplotlib
Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding
the import module statement:
import matplotlib
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias:
import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.
Draw a line in a diagram from position (0,0) to position (6,250):
import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
plt.plot(xpoints, ypoints)
plt.show()
Markers
You can use the keyword argument marker to emphasize each point with a specified
marker
Mark each point with a circle:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o')
plt.show()
Marker Description
'o' Circle
'*' Star
'.' Point
',' Pixel
'x' X
'X' X (filled)
Mark Descripti '+' Plus
er on 'P' Plus (filled)
'<' Triangle 's' Square
Left 'D' Diamond
'>' Triangle 'd' Diamond (thin)
Right
'p' Pentagon
'1' Tri Down
'H' Hexagon
'2' Tri Up 'h' Hexagon
'3' Tri Left 'v' Triangle Down
'4' Tri Right '^' Triangle Up
'|' Vlin
PANDAS
Pandas is a Python library used for working with data sets. It has functions for
analyzing, cleaning, exploring, and manipulating data.The name "Pandas" has a
reference to both "Panel Data", and "Python Data Analysis" and was created by Wes
McKinney in 2008.Pandas allows us to analyze big data and make conclusions based on
statistical theories.Pandas can clean messy data sets, and make them readable and
relevant.Relevant data is very important in data science.
Why Use Pandas?
Fast and efficient for manipulating and analyzing data.
Data from different file objects can be easily loaded.
Flexible reshaping and pivoting of data sets
Provides time-series functionality.
Here is a list of things that we can do using Pandas.
Data set cleaning, merging, and joining.
Easy handling of missing data (represented as NaN) in floating point as well as
non-floating point data.
Columns can be inserted and deleted from DataFrame and higher dimensional
objects.
Creating a Series
In the real world, a Pandas Series will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, or an Excel file. Pandas Series can be
created from lists, dictionaries, and from scalar values,
import pandas as pd
import numpy as np
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks']
There is also a tail() method for viewing the last rows of the DataFrame.
The tail() method returns the headers and a specified number of rows, starting from the
bottom.
Example
Print the last 5 rows of the DataFrame:
print(df.tail()
Info About the Data
The DataFrames object has a method called info(), that gives you more information
about the data set.
Example
Print information about the data:
print(df.info())
Data Cleaning
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 50
SV.KRISHNA., HOD IN COMPS Python
@app.route('/')
def index():
return ‘ <h1>Hello World!</h1>’
‘Decorators are a standard feature of the Python language; they can modify the
behavior of a function in different ways. A common pattern is to use decorators to
register functions as handlers for an event.
Importing flask module in the project is mandatory. An object of Flask class is
our WSGI application.
Flask constructor takes the name of current module (__name__) as argument.
The route() function of the Flask class is a decorator, which tells the application which
URL should call the associated function.
app. route(rule, options)
The rule parameter represents URL binding with the function.
The options is a list of parameters to be forwarded to the underlying Rule object
Finally the run() method of Flask class runs the application on the local development
server.
app.run(host, port, debug, options)
All parameters are optional
Sr.N Parameters & Description
o.
1 host
Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to
‘0.0.0.0’ to have server available externally
2 port
Defaults to 5000
3 debug
Defaults to false. If set to true, provides a debug information
4 options
To be forwarded to underlying Werkzeug server.
Flask Templates
Creating Templates in a Flask Application
To work with templates we need to create a default ‘templates’ folder.
Create a HTML page inside the templates folder.
<!DOCTYPE html>
<html>
<head>
<title>FlaskTest</title>
</head>
<body>
<h2>Welcome To VSU</h2>
<h4>Flask: Rendering Templates</h4>
<!-- this section can be replaced by a child document -->
{% block body %}
<p>This is a Flask application. </p>
{% endblock %}
</body>
</html>
Adding Routes and Rendering Templates
A route is a mapping of a URL with a function or any other piece of code to be rendered
on the webserver. In the Flask, we use the function decorate @app.route to indicate
that the function is bound with the URL provided in the parameter of the route function.
Creating the basic route: In this case, we are binding the URL “/” which is the base
URL for the server with the function “index”.
if __name__ == "__main__":
app.run()
@app.route("/<name>")
def welcome(name):
return render_template("welcome.html", name=name)
Allowing a user to submit data to your web application is a universal need. No matter
what web framework or solution you are using, HTML Forms are the method typically
used to gather and submit data from an end-user to a web application. Forms are an
essential part of web applications, right from the user authentication interface to
survey forms we require on our websites.
Here, When the user requests the page for the first time – he receives it via what we
call a “GET method.”
After filling the form, the user data is sent to the server via the POST method.
These forms are displayed to the user through templates using the <form> attribute of
HTML.
The Sample HTML form looks like this:
<form action="action_to_perform_after_submission" method = "POST">
<p>Field1 <input type = "text" name = "Field1_name" /></p>
<p>Field2 <input type = "text" name = "Field2_name" /></p>
<p>Field3 <input type = "text" name = "Field3_name" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
By default, the browser always uses the GET method to show resources on the
webpage.
Coding the flask file
Consider the following code:
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/form')
def form():
return render_template('form.html')
@app.route('/data/', methods = ['POST', 'GET'])
def data():
if request.method == 'GET':
return f"The URL /data is accessed directly. Try going to '/form' to submit form"
if request.method == 'POST':
form_data = request.form
return render_template('data.html',form_data = form_data)
app.run(host='localhost', port=5000)
Step 2: create a flask file the takes input from the form.
Step 3 : create a html document with flask tags in it to handle the data.
Ex:
Step 1:
<html>
<form action =”/users” method=”POST”>
Enter user Name : <input type=”text” name=”t1”>
Enter password :<input type= “password” name=”t2”>
</form>
</html>
Step2:
from flask import Flask,request,render_template
app=Flask(__name__)
@app.route(“/users” methods=[“GET”,”POST”])
def users():
uname=request.form[“t1”]
return render_template(“users.html”,uname=uname)
app.run()
Step3:
<html>
<h1>Welcome to My Website</h1>
<p>Hello {{uname}}</p>
</html>
In recent years, there has been a trend in web applications to move more and more of
the business logic to the client side, producing an architecture that is known as Rich
Internet Application (RIA). In RIAs, the server’s main (and sometimes only) function is to
provide the client application with data retrieval and storage services. In this model,
the server becomes a web service or Application Programming Interface (API).
More recently, the Representational State Transfer (REST) architecture has emerged as
the favorite for web applications due to it being built on the familiar model of the World
Wide Web. Flask is an ideal framework to build RESTful web services due to its
lightweight nature.
REST stands for REpresentational State Transfer and is an architectural style used in
modern web development. It defines a set of rules/constraints for a web application to
send and receive data.
Flask is a popular micro framework for building web applications. Since it is a micro-
framework, it is very easy to use and lacks most of the advanced functionality which is
found in a full-fledged framework. Therefore, building a REST API in Flask is very simple.
square of a number whenever a get request is sent to it. Each resource is a class that
inherits from the Resource class of flask- restful. Once the resource is created and
defined, we can add our custom resource to the API and specify a URL path for that
corresponding resource.
# using flask_restful
from flask import Flask, jsonify, request
from flask_restful import Resource, Api
app = Flask(__name__)
# creating an API object
api = Api(app)
class Hello(Resource):
def get(self):
return jsonify({'message': 'hello world'})
def post(self):
data = request.get_json()
return jsonify({'data': data})
class Square(Resource):
def get(self, num):
return jsonify({'square': num**2})
# adding the defined resources along with their corresponding urls
api.add_resource(Hello, '/')
api.add_resource(Square, '/square/<int:num>')
app.run(debug = True)
DJANGO
Django is a Python framework that makes it easier to create web sites using Python.
Django was initially designed to develop web applications for a newspaper company,
the Lawrence Journal-World. So, it is fantastic at handling projects with a lot of text
content, media files, and high traffic. However, the use of this framework isn’t limited
to the publishing business only. With each new release in Django, new features are
added, making it efficient enough to build any type of web application. We can use
Django to develop any type of web application from a social media website to an e-
commerce store.
Here are some of the areas where Django is used nowadays.
Platforms with B2B CRM systems, Custom CRM systems
Platforms with features for data analyzing, filtration, etc.
Creating admin dashboards
Creating an emailing system
Creating a verification system
Creating algorithm-based generators
Platforms with machine learning
Features of Django
Django Architecture
Django follows its own convention of Model-View-Controller (MVC) architecture named
Model View Template (MVT). The MVT is a software design pattern that mainly consists
of 3 components Model, View, and Template.
Model
The model provides data from the database.
In Django, the data is delivered as an Object Relational Mapping (ORM), which is a
technique designed to make it easier to work with databases.
The most common way to extract data from a database is SQL. One problem with SQL
is that you have to have a pretty good understanding of the database structure to be
able to work with it.
Django, with ORM, makes it easier to communicate with the database, without having
to write complex SQL statements.
View
A view is a function or method that takes http requests as arguments, imports the
relevant model(s), and finds out what data to send to the template, and returns the
final result.
The views are usually located in a file called views.py.
Template
A template is a file where you describe how the result should be represented.
Templates are often .html files, with HTML code describing the layout of a web page,
but it can also be in other file formats to present other results, but we will concentrate
on .html files.
Django uses standard HTML to describe the layout, but uses Django tags to add logic:
<h1>My Homepage</h1>
<p>My name is {{ firstname }}</p>
The templates of an application is located in a folder named templates.
URLs
Django also provides a way to navigate around the different pages in a website. When
a user requests a URL, Django decides which view it will send it to. This is done in a file
called urls.py.
When you have installed Django and created your first Django web application, and the
browser requests the URL, this is basically what happens:
1. Django receives the URL, checks the urls.py file, and calls the view that matches
the URL.
2. The view, located in views.py, checks for relevant models.
3. The models are imported from the models.py file.
4. The view then sends the data to a specified template in the template folder.
5. The template contains HTML and Django tags, and with the data it returns
finished HTML content back to the browser.
Step 1 .
Step 2.
Change the directory to VSU/Scripts
C:\Users\GTHJ> cd VSU/Scripts
Step 3.
Activate virtual Environment
Step 4:
Install Django using pip.
(VSU) C:\Users\GTHJ\VSU>py -m pip install django
Step 5:
Create a project by using the following command
(VSU) C:\Users\GTHJ\VSU>django-admin startproject MCA
Step 6:
Start the django server by using the following command
(VSU) C:\Users\GTHJ\VSU\MCA>py manage.py runserver
Step 7:
Open any browser and type the following in the address bar http://localhost:8000
you will get a screen like the following
URLs
Create a file named urls.py in the same folder as the views.py file, and type this code in
it:
from django.urls import path
from . import views
urlpatterns = [
path('sem2/', views.sem2, name='sem2')]
The above file should be created in the same folder where the app is created.
After this run the server and type the following in the browser.
http://localhost:8000/sem2/
Templates
The result of a request should be in a html page. This html page is placed in templates
folder and should be included in a view.
Create a templates folder inside the sem2 folder, and create a HTML file
named first.html.
Change Settings
To be able to work We have to tell Django that a new app is created. This is done in
the settings.py file in the project folder. Look up the INSTALLED_APPS [] list and add
the sem2 app like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sem2']
Migrate
Now when we have described a Model in the models.py file, we must run a command to
actually create the table in the database.
Navigate to the /projectfolder/ and run this command:
py manage.py makemigrations sem2
Now when we have described a Model in the models.py file, we must run a command to
actually create the table in the database. Navigate to the /projectfolder/ and run this
command:
py manage.py makemigrations sem2
Django inserts an id field for your tables, which is an auto increment number (first
record gets the value 1, the second record 2 etc.), this is the default behavior of
Django, you can override it by describing your own id field.
Django will create and execute an SQL statement, based on the content of the new file
in the /migrations/ folder.
Run the migrate command:
py manage.py migrate
View SQL
As a side-note: you can view the SQL statement that is executed from the migration
above. All you have to do is to run this command, with the migration number:
py manage.py sqlmigrate members 0001
Add Records
py manage.py shell
from members.models import Member
Member.objects.all()
This should give you an empty QuerySet object, like this:
<QuerySet []>
A QuerySet is a collection of data from a database.
Add a record to the table, by executing these two lines:
>>> r1 = Student(firstname='Emil', lastname='Refsnes')
>>> r1.save()
Execute this command to see if the Member table got a member:
>>> Student.objects.all().values()
You can add multiple records by making a list of Member objects, and
execute .save() on each entry:
>>> member1 = Member(firstname='Tobias', lastname='Refsnes')
>>> member2 = Member(firstname='Linus', lastname='Refsnes')
>>> member3 = Member(firstname='Lene', lastname='Refsnes')
>>> member4 = Member(firstname='Stale', lastname='Refsnes')
>>> member5 = Member(firstname='Jane', lastname='Doe')
>>> members_list = [member1, member2, member3, member4, member5]
>>> for x in members_list:
>>> x.save()
Update Records
To update records that are already in the database, we first have to get the record we
want to update:
>>> from sem2.models import Student
>>> x = Student.objects.all()[4]
x will now represent the member at index 4, which is "Stale Refsnes"
Now we can change the values of this record:
>>> x.firstname = "Stalikken"
>>> x.save()
Delete Records
To delete a record in a table, start by getting the record you want to delete:
>>> from members.models import Member
>>> x = Student.objects.all()[5]
Now we can delete the record:
>>> x.delete()
Add Fields in the Model
To add a field to a table after it is created, open the models.py file, and make your
changes:
mca/sem2/models.py:
from django.db import models
class student(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField()
joined_date = models.DateField()
Create Template
After creating Models, with the fields and data we want in them, it is time to display the
data in a web page.
Start by creating an HTML file named all_members.html and place it in
the /templates/ folder:
<!DOCTYPE html>
<html>
<body>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
<li>{{ x.firstname }} {{ x.lastname }}</li>
{% endfor %}
</ul>
</body>
</html>
{% %} are Django Tags, telling Django to perform some programming logic inside
these brackets
Modify View
Next we need to make the model data available in the template. This is done in the
view.
In the view we have to import the Student model, and send it to the template like this:
from django.http import HttpResponse
from django.template import loader
from . models import Student
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 69
SV.KRISHNA., HOD IN COMPS Python
def members(request):
mymembers = Student.objects.all().values()
template = loader.get_template('First.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))
A true/false field.
BooleanField
The default form widget for this field is a CheckboxInput.
TextField A large text field. The default form widget for this field is a
Textarea.