0% found this document useful (0 votes)
17 views72 pages

Python Material

The document provides an introduction to Python programming, covering its history, features, and applications. It explains basic programming concepts, object-oriented programming, and the setup of the development environment. Additionally, it discusses various applications of Python, including web development, scientific computing, and GUI applications, while also noting its limitations.

Uploaded by

Krish Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views72 pages

Python Material

The document provides an introduction to Python programming, covering its history, features, and applications. It explains basic programming concepts, object-oriented programming, and the setup of the development environment. Additionally, it discusses various applications of Python, including web development, scientific computing, and GUI applications, while also noting its limitations.

Uploaded by

Krish Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

SV.KRISHNA.

, HOD IN COMPS Python

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

 A program is a sequence of instructions that specifies how to perform a


computation. The computation might be something mathematical, such as
solving a system of equations or finding the roots of a polynomial, but it can also
be a symbolic computation, such as searching and replacing text in a document
or (strangely enough) compiling a program. The details look different in different
languages, but a few basic instructions appear in just about every language:

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

 ABC programming language is said to be the predecessor of Python language


which was capable of Exception Handling and interfacing with Amoeba Operating
System.

 Python is influenced by following programming languages: ABC Language.,


Modula-3

Python programming Language

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 1


SV.KRISHNA., HOD IN COMPS Python

 Python is a general-purpose interpreted, interactive, object-oriented, modular


and high-level programming language.

 High level language will be in human readable form and are easy to write as
well as compile or interpret.

 An interpreted language is a type of programming language that executes


instructions directly and freely, without previously compiling a program into
machine-language instructions.

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

 Object-oriented programming is a programming paradigm based on the


concept of "objects", which can contain data, in the form of fields, and code, in
the form of procedures(methods).variables are also known as fields, members,
attributes, or properties.

 Modular programming is the process of subdividing a computer program into


separate sub-programs.

 Low level language is machine readable form of program.Low level


language are compact and require less memory space.

Eg: Assembly language.

 The normal mode is the mode where the scripted and finished .py files are run in
the Python interpreter.

 All scripting languages are programming languages. The scripting language is


basically a language where instructions are written for a run time environment.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 2


SV.KRISHNA., HOD IN COMPS Python

They do not require the compilation step and are rather interpreted. Eg: python,
php

 A programming language is a formal language, which comprises a set of


instructions that produce various kinds of output.

 Programming languages are those which use compiler and Scripting


languages are those which use Interpreter.

Features of Python

 Easy to Learn and Use: Python is easy to learn and use. It is developer-friendly
and high level programming language.

 Expressive Language: Python language is more expressive means that it is


more understandable and readable.

 Interpreted Language: Python is an interpreted language i.e. interpreter


executes the code line by line at a time. This makes debugging easy and thus
suitable for beginners.

 Cross-platform Language: Python can run equally on different platforms such


as Windows, Linux, Unix and Macintosh etc. So, we can say that Python is a
portable 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.

 Object-Oriented Language: Python supports object oriented language and


concepts of classes and objects come into existence.

 Extensible: It implies that other languages such as C/C++ can be used to


compile the code and thus it can be used further in our python code.

 Large Standard Library: Python has a large and broad library and provides rich
set of module and functions for rapid application development.

 GUI Programming Support: Graphical user interfaces can be developed using


Python.

 Integrated: It can be easily integrated with languages like C, C++, JAVA etc.

 Platform independent: Write once and run any where

 Dynamically typed Language: We cannot required to specify the data type


explicitly. Dynamically typed language provides more flexibility to the
programmer. We are not fix the type of the variable.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 3


SV.KRISHNA., HOD IN COMPS Python

Python Architecture:

Applications of python

1) Web Applications

 We can use Python to develop web applications. It provides libraries to handle


internet protocols such as HTML and XML, JSON, Email processing, request,
beautifulSoup, Feedparser, etc.

 One of Python web-framework named Django is used on Instagram. Python


provides many useful frameworks, and these are given below:

Django and Pyramid framework(Use for heavy applications)

Flask and Bottle (Micro-framework)

Plone and Django CMS (Advance Content management)

2) Desktop GUI 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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 4


SV.KRISHNA., HOD IN COMPS Python

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

 Oddo is an example of the all-in-one Python-based application which offers a


range of business applications. Python provides a Tryton platform which is used
to develop the business application.

7) Audio or Video-based Applications

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 5


SV.KRISHNA., HOD IN COMPS Python

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

Gstreamer , Pyglet , QT Phonon

8) 3D CAD Applications

 The CAD (Computer-aided design) is used to design engineering related


architecture. It is used to develop the 3D representation of a part of a system.
Python can create a 3D CAD application by using the following functionalities.

Fandango (Popular ), CAMVOX, HeeksCNC, AnyCAD, RCAM


9) Enterprise Applications
 Python can be used to create applications that can be used within an Enterprise
or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.

10) Image Processing Application

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

OpenCV, Pillow, SimpleITK

Limitations of Python

 Performance wise python is not up to the mark.


 Not that much frequently used for developing mobile applications.

Setting up development environment

Python download and Installation

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 6


SV.KRISHNA., HOD IN COMPS Python

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 7


SV.KRISHNA., HOD IN COMPS Python

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 8


SV.KRISHNA., HOD IN COMPS Python

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 9


SV.KRISHNA., HOD IN COMPS Python

Running Python:

 Python is a well known high-level programming language. The Python script is


basically a file containing code written in Python. The file containing python script
has the extension ‘.py’ or can also have the extension ‘.pyw’ if it is being run on a
windows machine. To run a python script, we need a python interpreter that
needs to be downloaded and installed.

 we first have to check whether a python interpreter is installed on the system


or not. So in windows, open ‘cmd’ (Command Prompt) and type the following
command.

 Here are the ways with which we can run a Python script.

 Interactive Mode
 Command Line
 IDE (PyCharm)

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 10


SV.KRISHNA., HOD IN COMPS Python

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 11


SV.KRISHNA., HOD IN COMPS Python

 IDE (PyCharm)

 To run Python script on a IDE (Integrated Development Environment)


like PyCharmyou will have to do the following:
 Create a new project.
 Give a name to that project as ‘GfG’ and click on Create.
 Select the root directory with the project name we specified in the last
step. Right click on it, go in New and click on ‘Python file’ option. Then
give the name of the file as ‘hello’ (you can specify any name as per your
project requirement). This will create a ‘hello.py’ file in the project root
directory.
Note: You don’t have to specify the extension as it will take it
automatically.

Operators in python

Operator is a symbol that performs certain operations on operands.

Python provides the following set of operators

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

 Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication and division.

+ ==>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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 13


SV.KRISHNA., HOD IN COMPS Python

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

 Relational operators compare the values. It either


returns True or False according to the condition.
 > (greater than), >= (greaterthan or equal to), < (lessthan), <= (lessthan or
equal to), == (double equal), != (not equal)

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

 Chaining of relational operators is possible. In the chaining, if all comparisons


returns True then only result is True. If at least one comparison returns False then
the result is False

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

 They allow a program to make a decision based on multiple conditions. Each


operand is considered a condition that can be evaluated to a true or false value.

and, or ,not

For boolean types behavior:

 and ==>If both arguments are True then only result is True
 or ==>If atleast one arugemnt is True then result is True
 not ==>complement

For non boolean type’s behavior

 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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 15


SV.KRISHNA., HOD IN COMPS Python

 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

 Assignment operators are used to assign values to the variables. We can


combine assignment operator with some other operator to form compound
assignment operator.
 The following is the list of all possible compound assignment operators in Python

+= , -= ,*= ,/= , %= ,//= ,**= ,&= ,|= ,^= , >>= ,<<=

Program:

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 16


SV.KRISHNA., HOD IN COMPS Python

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

 Ternary operators also known as conditional expressions are operators that


evaluate something based on a condition being true or false.
Syntax:

 x = firstValue if condition else secondValue


 If condition is True then firstValue will be considered else secondValue will be
considered.

Program

a,b=10,20
x=30 if a<b else 40
print(x)

Output:
30

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 17


SV.KRISHNA., HOD IN COMPS Python

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

Python defines the following 2 special operators


1. Identity Operators
2. Membership operators

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

Declaring Variable and Assigning Values


 We don't need to declare explicitly variable in Python. When we assign any
value to the variable that variable is declared automatically.
 The equal (=) operator is used to assign value to a variable.

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

Assigning single value 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

Assigning multiple values to multiple variables

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

Python contains several in-built functions.


 type()- to check the type of the variable. Eg:type(a)
 id()- to get the address of the object.
 print()- to print the values.

Note: In python everything is treated as object only.


Data Types:

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 20


SV.KRISHNA., HOD IN COMPS Python

 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

 Decimal Form(Base-10): It is the default number system in python. The


allowed digits are 0 to 9.
Eg: a=10
 Binary Form(Base-2): It allowed the digits are 0 and 1. Literal value should be
prefixed with 0b or 0B. Eg: 1.x=0B1111 2. x=0B1011
 Octal Form(Base-8): The allowed digits are 0 to 7. Literal value should be
prefixed with 0o or 0O. Eg: 0o123.
 Hexadecimal Form(Base-16): The allowed digits are 0-9, a-f(both lower case
and upper case letters). Literal value should be prefixed with 0x or 0X. Eg: 0xaf

Examples

Base Conversions

Python provide inbuilt functions for base conversions.


 bin(): We can use bin() to convert from any base to binary. Eg: bin(0o723)
 oct(): We can use oct() to convert from any base to octal.Eg: oct(10)
 hex(): We can use hex() to convert from any base to hexadecimal. Eg: hex(100)

Examples

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 21


SV.KRISHNA., HOD IN COMPS Python

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 22


SV.KRISHNA., HOD IN COMPS Python

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

 Range Data Type represents a sequence of numbers. The elements present in


range Data type are not modifiable. i.e. range Data type is immutable.
 Range object does not support item assignment
 We can access elements present in the range data type by using index
 Syntax: list(range(values))
list(range(begin,end))
list(range(begin,end,step))
 Where step represents the increment or decrement the values in a range

6) Str Datatype

 str represents String data type.


 A String is a sequence of characters enclosed within single quotes or double
quotes.
 By using single quotes or double quotes we cannot represent multi line string
literals.
 For this requirement we should go for triple single quotes(''') or triple double
quotes(""")
 We can also use triple quotes to use single quote or double quote in our String.
 We can embed one string in another string
 In Python, we can represent char values also by using str type and explicitly char
type is not available.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 23


SV.KRISHNA., HOD IN COMPS Python

 Syntax: Variable name= String Value

Ex str3 = “hello world”

7) List Datatype

 If we want to represent a group of values as a single entity where insertion order


required to preserve and duplicates are allowed then we should go for list data
type.

1. Insertion order is preserved


2. Mutable objects are allowed
3. Heterogeneous objects are allowed
4. Duplicates are allowed
5. Growable in nature
6. Values should be enclosed within square brackets []

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 24


SV.KRISHNA., HOD IN COMPS Python

 If we want to represent a group of values without duplicates where order is not


important then we should go for set Data Type. Set elements are represented
with in curly braces{}

1. Insertion order is not preserved


2. Duplicates are not allowed
3. Heterogeneous objects are allowed
4. Index concept is not applicable
5. It is mutable collection
6. Growable in nature

Examples

10) Dict Datatype

 If we want to represent a group of values as key-value pairs then we should go


for dict data type.Duplicate keys are not allowed but values can be duplicated. If
we are trying to insert an entry with duplicate key then old value will be replaced
with new value. dict is mutable and the order won’t be preserved. The following is
an exampleof dictionary.

11) None Datatype

 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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 25


SV.KRISHNA., HOD IN COMPS Python

Types of Modes

 Python has two basic modes:


1. Interactive Mode
2. Normal Mode (Script Mode)
 The normal mode (script mode) is the mode where the scripted and finished .py
files are run in the Python interpreter.
 Interactive mode is a command line shell which gives immediate feedback for
each statement, while running previously fed statements in active memory.
 As new lines are fed into the interpreter, the fed program is evaluated both in
part and in whole.

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 26


SV.KRISHNA., HOD IN COMPS Python

 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:

"""This is a comment written in more than


just one line-multiline comment"""
print("Hello,World")

Output

Hello World

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 27


SV.KRISHNA., HOD IN COMPS Python

Input and Output Statements

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 28


SV.KRISHNA., HOD IN COMPS Python

Form-1: print() without any argument


Just it prints new line character
Form-2
1) print("String")
2) print("Hello World")
3) We can use escape characters also
4) print("Hello \n World")
5) print("Hello\tWorld")
6) We can use repetetion operator (*) in the string
7) print(10*"Hello")
8) print("Hello"*10)
9) We can use + operator also
10) print("Hello"+"World")
Output

 By default output values are seperated by space. If we want we can specify


separator by using "sep" attribute

Example

a,b,c=10,20,30
print(a,b,c,sep=',')
print(a,b,c,sep=':')

Output:

 If we want output in the same line with spaces

Example
print("Hello",end=' ')
print("VSU",end=' ')
print("mca")

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 29


SV.KRISHNA., HOD IN COMPS Python

Output:

Hello VSU MCA

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

 This method lets us concatenate elements within a string through positional


formatting.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 30


SV.KRISHNA., HOD IN COMPS Python

 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

My name is John, I’m 36


My name is John, I’m 36
My name is John, I’m 36

5) eval()

 eval Function take a String and evaluate the Result.

Example-1
x =eval(“10+20+30” )
print(x)
Output 60

Introduction to object-oriented programming in python.


object-oriented Programming (OOPs) is a programming paradigm that uses objects and
classes in programming. It aims to implement real-world entities like inheritance,
polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 31


SV.KRISHNA., HOD IN COMPS Python

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.

OOPs Concepts in Python


 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance
 Data Abstraction

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.

Syntax: Class Definition


class ClassName:
# Statement

Ex :

class Vsu:

Object of Python Class

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy


of the class with actual values
An object consists of:
 State: It is represented by the attributes of an object. It also reflects the
properties of an object.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 32


SV.KRISHNA., HOD IN COMPS Python

 Behavior: It is represented by the methods of an object. It also reflects the


response of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact
with other objects.

Declaring Claas Objects (Also called instantiating a class)

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

Class and Instance Variables

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.

# Sample class with init method


class Person:

# init method or constructor


def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 34


SV.KRISHNA., HOD IN COMPS Python

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

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other 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 Child Class


To create a class that inherits the functionality from another class, send the parent
class as a parameter when creating the child class:
Example

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

Python Multi-Level inheritance

Multi-Level inheritance is possible in python like other object-oriented languages. Multi-


level inheritance is archived when a derived class inherits another
derived class. There is no limit on the number of levels up to which,
the multi-level inheritance is archived in python.

1. class class1:
2. <class1 declarations>
3. class class2(class1):

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 35


SV.KRISHNA., HOD IN COMPS Python

4. <class2 declarations>
5. class class3(class2):
6. <class3 declarations>
7. ……….

Python Multiple inheritance

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

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 (obj, class) method

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 36


SV.KRISHNA., HOD IN COMPS Python

Consider the following example to perform method overriding in python.

Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Data abstraction in python

Abstraction is an important aspect of object-oriented programming. In python, we can


also perform data hiding by adding the double underscore (___) as a prefix to the
attribute which is to be hidden. After this, the attribute will not be visible outside of the
class through the object

Polymorphism

Polymorphism is another important concept of object-oriented programming. It simply


means more than one form.

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

# create an object of Square


s1 = Square()
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 37
SV.KRISHNA., HOD IN COMPS Python

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)

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 38


SV.KRISHNA., HOD IN COMPS Python

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.

Creating a ndarray object

The ndarray object can be created by using the array routine of the numpy module. For
this purpose, we need to import the numpy.
>>> 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

1 object It represents the collection object. It can be a list, tuple,


dictionary, set, etc.

2 dtype We can change the data type of the array elements by changing
this option to the specified type. The default is none.

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


copied.

4 order There can be 3 possible values assigned to this option. It can be


C (column order), R (row order), or A (any)

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 40


SV.KRISHNA., HOD IN COMPS Python

5 subok The returned array will be base class array by default. We can
change this to make the subclasses passes through by setting
this option to true.

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


To create an array using the list, use the following syntax.
>>> a = numpy.array([1, 2, 3])
To create a multi-dimensional array object, use the following syntax.
>>> a = numpy.array([[1, 2, 3], [4, 5, 6]])
To change the data type of the array elements, mention the name of the data type
along with the collection.
>>> a = numpy.array([1, 3, 5, 7], complex)
Finding the dimensions of the Array
The ndim function can be used to find the dimensions of the array.
>>> import numpy as np
>>> arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])
>>> print(arr.ndim)
Finding the size of each array element
The itemsize function is used to get the size of each array item. It returns the number
of bytes taken by each array element.
Consider the following example

Example
#finding the size of each item in the array
import numpy as np
a = np.array([[1,2,3]])
print("Each item contains",a.itemsize,"bytes")
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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 41


SV.KRISHNA., HOD IN COMPS Python

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 42


SV.KRISHNA., HOD IN COMPS Python

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

1 bool_ It represents the boolean value indicating true or false. It is


stored as a byte.

2 int_ It is the default type of integer. It is identical to long type in C


that contains 64 bit or 32-bit integer.

3 intc It is similar to the C integer (c int) as it represents 32 or 64-bit


int.

4 intp It represents the integers which are used for indexing.

5 int8 It is the 8-bit integer identical to a byte. The range of the value is
-128 to 127.

6 int16 It is the 2-byte (16-bit) integer. The range is -32768 to 32767.

7 int32 It is the 4-byte (32-bit) integer. The range is -2147483648 to


2147483647.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 43


SV.KRISHNA., HOD IN COMPS Python

8 int64 It is the 8-byte (64-bit) integer. The range is -


9223372036854775808 to 9223372036854775807.

9 uint8 It is the 1-byte (8-bit) unsigned integer.

10 uint16 It is the 2-byte (16-bit) unsigned integer.

11 uint32 It is the 4-byte (32-bit) unsigned integer.

12 uint64 It is the 8 bytes (64-bit) unsigned integer.

13 float_ It is identical to float64.

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.

17 complex_ It is identical to complex128.

18 complex6 It is used to represent the complex number where real and


4 imaginary part shares 32 bits each.

19 complex1 It is used to represent the complex number where real and


28 imaginary part shares 64 bits each.

Numpy Array Creation


The ndarray object can be constructed by using the following routines.

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 44


SV.KRISHNA., HOD IN COMPS Python

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

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)
plt.show()

The plot() function is used to draw


points (markers) in a diagram.
By default, the plot() function draws
a line from point to point.
The function takes parameters for
specifying points in the diagram.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 46


SV.KRISHNA., HOD IN COMPS Python

Parameter 1 is an array containing the points on the x-axis.


Parameter 2 is an array containing the points on the y-axis.
If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3,
10] to the plot function.
Draw a line in a diagram from position (1, 3) to position (8, 10):
import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

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

Mark each point with a star:


...
plt.plot(ypoints, marker = '*')

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 47


SV.KRISHNA., HOD IN COMPS Python

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 48


SV.KRISHNA., HOD IN COMPS Python

 Powerful group by functionality for performing split-apply-combine operations on


data sets.
 Data Visulaization
Pandas Data Structures
Pandas generally provide two data structures for manipulating data, They are:
 Series
 DataFrame
Series
Pandas Series is a one-dimensional labeled array capable of holding data of any type
(integer, string, float, python objects, etc.). The axis labels are collectively called
indexes.
Pandas Series is nothing but a column in an Excel sheet. Labels need not be unique but
must be a hashable type. The object supports both integer and label-based indexing
and provides a host of methods for performing operations involving the index.

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

# Creating empty series


ser = pd.Series()
print("Pandas Series: ", ser)
# simple array
data = np.array(['g', 'e', 'e', 'k', 's'])
ser = pd.Series(data)
print("Pandas Series:\n", ser)
DataFrame
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous
tabular data structure with labeled axes (rows and columns). A Data frame is a two-
dimensional data structure, i.e., data is aligned in a tabular fashion in rows and
columns. Pandas DataFrame consists of three principal components, the data, rows,
and columns.
Creating Data Frame
In the real world, a Pandas DataFrame will be created by loading the datasets from
existing storage, storage can be SQL Database, CSV file, or an Excel file. Pandas
DataFrame can be created from lists, dictionaries, and from a list of dictionaries, etc.
import pandas as pd
# Calling DataFrame constructor
df = pd.DataFrame()
print(df)

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 49


SV.KRISHNA., HOD IN COMPS Python

# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks']

# Calling DataFrame constructor on list


df = pd.DataFrame(lst)
print(df)

Load Files Into a DataFrame


If your data sets are stored in a file, Pandas can load them into a DataFrame.
Example
Load a comma separated file (CSV file) into a DataFrame:
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
Read JSON
Big data sets are often stored, or extracted as JSON.
JSON is plain text, but has the format of an object, and is well known in the world of
programming, including Pandas.
import pandas as pd
df = pd.read_json('data.json')
print(df.to_string())
Viewing the Data
One of the most used method for getting a quick overview of the DataFrame, is
the head() method.
The head() method returns the headers and a specified number of rows, starting from
the top.
import pandas as pd
df = pd.read_csv('data.csv')
print(df.head(10))

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

Data cleaning means fixing bad data in your data set.


Bad data could be:
 Empty cells
 Data in wrong format
 Wrong data
 Duplicates
Empty Cells
Empty cells can potentially give you a wrong result when you analyze data.
Remove Rows
One way to deal with empty cells is to remove rows that contain empty cells.
import pandas as pd
df = pd.read_csv('data.csv')
new_df = df.dropna()
print(new_df.to_string())
Replace Empty Values
Another way of dealing with empty cells is to insert a new value instead.
This way you do not have to delete entire rows just because of some empty cells.
The fillna() method allows us to replace empty cells with a value:
import pandas as pd
df = pd.read_csv('data.csv')
df.fillna(130, inplace = True)

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 51


SV.KRISHNA., HOD IN COMPS Python

Unit-III Introduction to Flask framework, Flask Web Development - Flask routes


and views - Templates and rendering in Flask - Forms and user input - Handling API
requests.
UNIT-III
FLASK
Web Framework
Web Application Framework or simply Web Framework represents a collection of
libraries and modules that enables a web application developer to write applications
without having to bother about low-level details such as protocols, thread management
etc.
Flask
Flask is a web application framework written in Python. It is developed by Armin
Ronacher, who leads an international group of Python enthusiasts named Pocco. Flask
is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco
projects.
WSGI
Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web
application development. WSGI is a specification for a universal interface between the
web server and the web applications.
Flask is often referred to as a micro framework. It aims to keep the core of an
application simple yet extensible. Flask does not have built-in abstraction layer for
database handling, nor does it have form a validation support. Instead, Flask supports
the extensions to add such functionality to the application.
Install virtualenv for development environment
virtualenv is a virtual Python environment builder. It helps a user to create multiple
Python environments side-by-side. Thereby, it can avoid compatibility issues between
the different versions of the libraries.
The following command installs virtualenv
pip install virtualenv
To activate corresponding environment, venv\scripts\activate
We are now ready to install Flask in this environment.
pip install Flask

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 52


SV.KRISHNA., HOD IN COMPS Python

Flask Views and Routes


Routes and View Functions like Clients such as web browsers send requests to the web
server, which in turn sends them to the Flask application instance. The application
instance needs to know what code needs to run for each URL requested, so it keeps a
mapping of URLs to Python functions. The association between a URL and the
function that handles it is called a route. The most convenient way to define a
route in a Flask application is through the app.route decorator exposed by the
application instance, which registers the decorated function as a route. The following
example shows how a route is declared using this decorator:

@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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 53


SV.KRISHNA., HOD IN COMPS Python

3 debug
Defaults to false. If set to true, provides a debug information

4 options
To be forwarded to underlying Werkzeug server.

To execute the app we use the following command


(flaskweb) C:\Users\GTHJ\flaskweb>python Test.py
# flaskweb is the virtual environment.
After executing the Test.py file you will get the following screen.

The default port number is 5000.


Debug mode
A Flask application is started by calling the run() method. However, while the
application is under development, it should be restarted manually for each change in
the code. To avoid this inconvenience, enable debug support. The server will then
reload itself if the code changes. It will also provide a useful debugger to track the
errors if any, in the application.
The Debug mode is enabled by setting the debug property of the application object
to True before running or passing the debug parameter to the run() method.
app.debug = True
app.run()
app.run(debug = True)
Flask takes care of dispatching incoming requests to the correct view based on the
request URL and the routes you've defined. In Flask, views can be any callable (like a
function) that receives requests and returns the response for that request. Flask is
responsible for sending the response back to the user. The following code block is your
application’s full source code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "This is an example app"
This code creates the object app, which belongs to the Flask class. The view
function index() is linked to the route / using the app.route decorator.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 54


SV.KRISHNA., HOD IN COMPS Python

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

from flask import Flask, render_template


app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")

if __name__ == "__main__":
app.run()

Templating With Jinja2 in Flask


Now, we’ll create a new route for demonstrating the usage of the Jinja template. We
need to add the route, so just add one more chunk of the code to the “server.py file”

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 55


SV.KRISHNA., HOD IN COMPS Python

@app.route("/<name>")
def welcome(name):
return render_template("welcome.html", name=name)

FORMS & USER INPUT:

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)

The following are the steps to handle form data.

Step 1 : create a html document with a form.


RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 56
SV.KRISHNA., HOD IN COMPS Python

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>

Handling API Requests:

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 57


SV.KRISHNA., HOD IN COMPS Python

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.

There are two ways of creating a REST API in Flask:

1. Using Flask without any external libraries


2. Using flask_restful library
Libraries required:
flask_restful can be installed via the pip command:
pip3 install flask-restful

Method 1: using only Flask


Here, there are two functions: One function to just return or print the data sent through
GET or POST and another function to calculate the square of a number sent through
GET request and print it.

from flask import Flask, jsonify, request


app = Flask(__name__)
@app.route('/', methods = ['GET', 'POST'])
def home():
if(request.method == 'GET'):
data = "hello world"
return jsonify(data)

@app.route('/home/<int:num>', methods = ['GET'])


def disp(num):
return jsonify(num*num)
app.run(debug = True)
if you execute the above program and type the url : “http://127.0.0.1:5000/” , you will
get “ hello world” in the browser.
If you type “http://127.0.0.1:5000/home/10 “ you will get 100 on your browser screen.

Method 2: Using flask-restful


Flask Restful is an extension for Flask that adds support for building REST APIs in
Python using Flask as the back-end. In flask-restful, the main building block is a
resource. Each resource can have several methods associated with it such as GET,
POST, PUT, DELETE, etc. for example, there could be a resource that calculates the
RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 58
SV.KRISHNA., HOD IN COMPS Python

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 59


SV.KRISHNA., HOD IN COMPS Python

Features of Django

1. Open-Source– Django is an open-source python framework, which means we


can download and use it for free. This helps to reduce the overall cost of the
application.
2. Fast Development– Django was designed with the goal of creating a framework
that would allow developers to develop web applications in less time. So, Django
reduces the project implementation, allowing rapid web development.
3. Scalable– Django is scalable in nature, which means we can easily migrate from
a small-scale application to a large-scale application.
4. Secure– Django is a secure framework as it provides tools to assist developers to
avoid typical security problems. It also provides an authentication system to store
manage user accounts and passwords.
5. Largely supported libraries– Django contains a large set of modules and
libraries that can be used to manage different web development tasks.
6. Admin Interface– Django comes with a build-in admin interface. So, we don’t
need to build it from the scratch. Also, we can customize the interface according
to the requirements.
7. Large Community– As Django is one of the most popular web development
framework. So, it has a large and friendly community as well as channels for
sharing and connecting.

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 60


SV.KRISHNA., HOD IN COMPS Python

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.

The models are usually located in a file called models.py.

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 61


SV.KRISHNA., HOD IN COMPS Python

Django - Create Virtual Environment


Virtual Environment
It is suggested to have a dedicated virtual environment for each Django project, and
one way to manage a virtual environment is venv, which is included in Python.

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 62


SV.KRISHNA., HOD IN COMPS Python

Django Create App


What is an App?
An app is a web application that has a specific meaning in your project, like a home
page, a contact form, or a members database.
An App is created by using the following command.
(VSU) C:\Users\GTHJ\VSU\MCA>py manage.py startapp sem2
Now an app is created with the name sem2. Sem2 contains the following
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
Views
Django views are Python functions that takes http requests and returns http response,
like HTML documents.
A web page that uses Django is full of views with different tasks and missions.
Views are usually put in a file called views.py located on your app's folder.
We need to edit the existing views file.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 63


SV.KRISHNA., HOD IN COMPS Python

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 64


SV.KRISHNA., HOD IN COMPS Python

Next modify the urls file in the project folder.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 65


SV.KRISHNA., HOD IN COMPS Python

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.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 66


SV.KRISHNA., HOD IN COMPS Python

Modify the View


Open the views.py file and replace the members view with this:
from django.http import HttpResponse
from django.template import loader
def sem2(request):
template = loader.get_template('first.html')
return HttpResponse(template.render())

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']

Django Models & DataBase


A Django model is a table in your database. In Django, data is created in objects, called
Models, and is actually tables in a database.
To create a model, navigate to the models.py file in the /sem2/ folder.
Open it, and add a Student table by creating a Student class, and describe the table
fields in it:
Projectfolder/appfolder/models.py:
from django.db import models
class Student(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 67


SV.KRISHNA., HOD IN COMPS Python

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

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 68


SV.KRISHNA., HOD IN COMPS Python

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

Display Data in a Web Page:

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

The sem2 view does the following:


 Creates a mymembers object with all the values of the Student model.
 Loads the First.html template.
 Creates an object containing the mymembers object.
 Sends the object to the template.
 Outputs the HTML that is rendered by the template.

Django Model Data Types


Field Name Description

AutoField It is an IntegerField that automatically increments.

It is a 64-bit integer, much like an AutoField except that it is


BigAutoField guaranteed to fit numbers from 1 to
9223372036854775807.

It is a 64-bit integer, much like an IntegerField except that it


BigIntegerField is guaranteed to fit numbers from -9223372036854775808
to 9223372036854775807.

BinaryField A field to store raw binary data.

A true/false field.
BooleanField
The default form widget for this field is a CheckboxInput.

CharField A field to store text-based values.

DateField A date, represented in Python by a datetime.date instance

It is used for date and time, represented in Python by a


DateTimeField
datetime.datetime instance.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 70


SV.KRISHNA., HOD IN COMPS Python

Field Name Description

It is a fixed-precision decimal number, represented in Python


DecimalField
by a Decimal instance.

DurationField A field for storing periods of time.

It is a CharField that checks that the value is a valid email


EmailField
address.

FileField It is a file-upload field.

It is a floating-point number represented in Python by a float


FloatField
instance.

It inherits all attributes and methods from FileField, but also


ImageField
validates that the uploaded object is a valid image.

It is an integer field. Values from -2147483648 to


IntegerField
2147483647 are safe in all databases supported by Django.

GenericIPAddressFiel An IPv4 or IPv6 address, in string format (e.g. 192.0.2.30 or


d 2a02:42fe::4).

NullBooleanField Like a BooleanField, but allows NULL as one of the options.

PositiveIntegerField Like an IntegerField, but must be either positive or zero (0).

PositiveSmallIntegerF Like a PositiveIntegerField, but only allows values under a


ield certain (database-dependent) point.

Slug is a newspaper term. A slug is a short label for


SlugField something, containing only letters, numbers, underscores or
hyphens. They’re generally used in URLs.

It is like an IntegerField, but only allows values under a


SmallIntegerField
certain (database-dependent) point.

TextField A large text field. The default form widget for this field is a

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 71


SV.KRISHNA., HOD IN COMPS Python

Field Name Description

Textarea.

TimeField A time, represented in Python by a datetime.time instance.

URLField A CharField for a URL, validated by URLValidator.

A field for storing universally unique identifiers. Uses


UUIDField Python’s UUID class. When used on PostgreSQL, this stores
in a uuid datatype, otherwise in a char(32).

Field Name Description

A many-to-one relationship. Requires two positional


ForeignKey arguments: the class to which the model is related and the
on_delete option.

A many-to-many relationship. Requires a positional argument:


ManyToManyFie the class to which the model is related, which works exactly
ld the same as it does for ForeignKey, including recursive and
lazy relationships.

A one-to-one relationship. Conceptually, this is similar to a


OneToOneField ForeignKey with unique=True, but the “reverse” side of the
relation will directly return a single object.

RAO’S DEGREE &PG COLLEGE Ph No: 9177972217 Page 72

You might also like