Python 6
Python 6
“PYTHON LANGUAGE”
The satisfaction that accompanies that the successful completion of any task would be
incomplete without the mention of people whose ceaseless cooperation made it possible, whose
We are grateful to our project guide Mr. Ashwani Kumar Gupta for the guidance, inspiration
and constructive suggestions that helpful us in the preparation of this project. We also thank our
Student Name
Neha Singh
Department of Computer Science & Engineering
MADAN MOHAN MALAVIYA UNIVERSITY OF TECHNOLOGY,
GORAKHPUR
Certificate
This is to certify that Neha Singh, Student of M.Tech. (CSE) Program of this institute has
successfully completed his project titled Python Language under the guidance of Mr. Ashwani
Kumar Gupta as a part of the course curriculum of M.Tech.(CSE).
To the best of my knowledge this project is an authentic record of student’s own work.
During the execution of this project student’s sincerity and devotion was found par
excellence.
TechSrijan Consultancy Services Pvt. Ltd. Founded on March 2018. With the aim of
providing short duration, high quality and high intensity Training
(Summer/Winter/Vocational/industrial) on various technologies like Python, Java, Web
Development using Php MySql, Andriod ,Nodejs, C & C++ ,Web Designing and Fundamentals
of Computer & Networking to B.Tech/Diploma/BCA students .
“There is huge gap between industry and academics. Our aim is to fulfill the gap between
academics and industry .We are sharing the challenges faced , solutions adopted for Computer
Science & Engineering programme to bring industry- academia together to make the students
industry ready”.
TechSrijan Consultancy Services Pvt. Ltd. offers different types of training like:
Industrial Training
Summer Training
Vocational Training
Winter Training
At TechSrijan we provide the entire necessary computer training which helps the
beginners and also the experienced workers so that they can achive better recognition in
this competitive world.
Learning after Training
This report contains the project and their brief description, which has been taught to me in my
summer training.
Therefore, this training was very useful for me as I have gained a lot of knowledge and learnt
various interesting and important thing.
TABLE OF CONTENTS
Acknowledgements
Certificate
Index
Introduction about the Industry
Learning after Training
INDEX
CHAPTER 1 Introduction [01]
Python is relatively simple, so it's easy to learn since it requires a unique syntax that focuses on
readability. Developers can read and translate Python code much easier than other languages. In
turn, this reduces the cost of program maintenance and development because it allows teams to
work collaboratively without significant language and experience barriers.
Additionally, Python supports the use of modules and packages, which means that programs can
be designed in a modular style and code, can be reused across a variety of projects. Once you've
developed a module or package you need, it can be scaled for use in other projects, and it's easy
to import or export these modules.
History of Python - Python was developed by Guido van Rossum in the late eighties and early
nineties at the National Research Institute for Mathematics and Computer Science in the
Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, Smalltalk, and UNIX shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).Python is now maintained by a core development team at the institute,
although Guido van Rossum still holds a vital role in directing its progress.
Python's name is derived from the British comedy group Monty Python, whom Python
creator Guido van Rossum enjoyed while developing the language. Monty Python references
appear frequently in Python code and culture.
Versions in Python –There were many versions of pythons since its release in 1994.The
following python versions are major and notable minor releases.
Python 1.0 - January 1994
Python 1.5 - December 31, 1997
Python 1.6 - September 5, 2000
Python 2.0 - October 16, 2000
Python 2.1 - April 17, 2001
Python 2.2 - December 21, 2001
Python 2.3 - July 29, 2003
Python 2.4 - November 30, 2004
Python 2.5 - September 19, 2006
Python 2.6 - October 1, 2008
Python 2.7 - July 3, 2010
Python 3.0 - December 3, 2008
Python 3.1 - June 27, 2009
Python 3.2 - February 20, 2011
Python 3.3 - September 29, 2012
Python 3.4 - March 16, 2014
Python 3.5 - September 13, 2015
Python 3.6 - December 3, 2016
Python 3.7.2 - June 27, 2018
Python 3.7.3 - March 25, 2019
Why Python? - The language’s core philosophy is summarized in the document ,which
includes aphorism such as-
Beautiful is better than ugly
Simple is better than complex
Complex is better than complicated
Readability counts
Explicit is better than implicit
Python Features -
Python's features include −
Easy-to-learn -Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
GUI Programming − Python supports GUI applications that can be created and ported
to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell
scripting.
Python 2 Python 3
It is more stable and transparent version of the It is the future of Python designed to address
python programming language. the design flaws in the previous version.
The print syntax is treated as a statement The print is explicitly treated as a function and
rather than function which requires to be replaced by the print () function in Python 3
wrapped in parenthesis. which requires an extra pair of parenthesis.
ASCII string type is used by default to store Unicode is the implicit type by default.
strings.
It simply returns an integer to the nearest It makes integer division more intuitive by
whole number when dividing two integers. using true division for integers and floats.
Xrange function reconstructs the sequence Xrange is replaced by range () function in
every time. Python 3.
Getting Python -
The most up-to-date and current source code, binaries, documentation, news, etc., is available
on the official website of Python https://www.python.org/
If the binary code for your platform is not available, you need a C compiler to compile the
source code manually. Compiling the source code offers more flexibility in terms of choice of
features that you require in your installation.
1. Interactive Mode Programming -Type the following text at the Python prompt and press
the Enter –
2. Script Mode Programming-Let us write a simple Python program in a script. Python files
have extension .py. Type the following source code in a test.py file –
Data Structure - Data structures are fundamental concepts of computer science which helps
is writing efficient programs in any language. Python is a high-level, interpreted, interactive and
object-oriented scripting language using which we can study the fundamentals of data structure
in a simpler way as compared to other programming languages
Lines and Indentation – Python provides no braces to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by line indentation, which is
rigidly enforced.
Comments in Python - A hash sign (#) that is not inside a string literal begins a comment. All
characters after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.
1) Single Line Comment - In case user wants to specify a single line comment, then comment
must start with ?#? -
Example –
2) Multi Line Comment - Multi lined comment can be given inside triple quotes.
Example –
Strings - Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. The plus (+) sign is
the string concatenation operator and the asterisk (*) is the repetition operator.
Lists - Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C.
Ordered collection of data.
Supports similar slicing and indexing functionalities as in the case of String.
They are mutable.
For example –
Tuples - A tuple is another sequence data type that is similar to the list. A tuple consists of a number
of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
Immutable in Nature.
No type restriction
For example –
.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and size can
be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
Dictionary - Python's dictionaries are kind of hash table type. They work like associative.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]).
Lists are sequences but the dictionaries are mappings.
They are mapping between a unique key and a value pair.
For example −
Data Type Conversion - Sometimes, you may need to perform conversions between the built-
in types. To convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value.
int (a, base) - This function converts any data type to integer. ‘Base’ specifies the base in
which string is if data type is string.
float () - This function is used to convert any data type to a floating point number.
list () - This function is used to convert any data type to a list type.
dict () - This function is used to convert a tuple of order (key,value) into a dictionary.
Types of Operator - The operator can be defined as a symbol which is responsible for a
particular operation between two operands. Operators are the pillars of a program on which the
logic is built in a particular programming language. Python language supports the following
types of operators -
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Comparison operator - Comparison operators are used to comparing the value of the two
operands and returns boolean true or false accordingly. The comparison operators are described
in the following table
assignment operators - The assignment operators are used to assign the value of the right
expression to the left operand. The assignment operators are described in the following table.
Bitwise operator - The bitwise operators perform bit by bit operation on the values of the two
operands.
Logical Operators - The logical operators are used primarily in the expression evaluation to
make a decision. Python supports the following logical operators.
Membership Operators - Python membership operators are used to check the membership of
value inside a data structure. If the value is present in the data structure, then the resulting value
is true otherwise it returns false.
Loops in Python
Python For Loops - A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).This is less like the for keyword in other programming
language, and works more like an iterator method as found in other object-orientated
programming languages. With the for loop we can execute a set of statements, once for each item
in a list, tuple, set etc.
The break Statement -With the break statement we can stop the loop before it has looped
through all the items.
The continue Statement - With the continue statement we can stop the current iteration of
the loop, and continue with the next:
The range () Function -To loop through a set of code a specified number of times, we can
use the range () function. The range () function returns a sequence of numbers, starting from 0
by default, and increments by 1 (by default), and ends at a specified number.
Else in For Loop - The else keyword in a for loop specifies a block of code to be executed
when the loop is finished.
Nested Loops - A nested loop is a loop inside a loop. The "inner loop" will be executed one
time for each iteration of the "outer loop".
While Loop - A while loop statement in Python programming language repeatedly executes
a target statement as long as a given condition is true.
Syntax -
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Arrays in Python
Array is a container which can hold a fix number of items and these items should be of the same
type. Most of the data structures make use of arrays to implement their algorithms. Following
are the important terms to understand the concept of Array.
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 9.
Array is created in Python by importing array module to the python program. Then the array is
declared as shown in below.
Consider the example of recording temperatures 4 times a day, every day. Some times the
recording instrument may be faulty and we fail to record data. Such data for 4 days can be
presented as a two dimensional array as below.
Day 1 - 11 12 5 2
Day 2 - 15 6 10
Day 3 - 10 8 12 5
Day 4 - 12 15 8 6
print(T[0])
print(T[1][2])
NumPy
NumPy- NumPy is Python package. It stands for Numerical Python, is a library consisting of
multidimensional array objects and a collection of routines for processing those arrays. Using
NumPy, mathematical and logical operations on arrays can be performed.
Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray
was also developed, having some additional functionalities. In 2005, Travis Oliphant created
NumPy package by incorporating the features of Numarray into Numeric package. There are
many contributors to this open source project.
Why use NumPy? - NumPy is memory efficiency, meaning it can handle the vast amount of
data more accessible than any other library. Besides, NumPy is very convenient to work with,
especially for matrix multiplication and reshaping. On top of that, NumPy is fast. In fact,
TensorFlow and Scikit learn to use NumPy array to compute the matrix multiplication in the
back end.
Operations using NumPy - Using NumPy, a developer can perform the following operations −
Operations related to linear algebra. NumPy has in-built functions for linear algebra and
random number generation.
Example -
import numpy as np
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
print("Array is of type: ", type(arr))
print("No. of dimensions: ", arr.ndim)
print("Shape of array: ", arr.shape)
print("Size of array: ", arr.size)
print("Array stores elements of type: ", arr.dtype)
Matplotlib in Python
Matplotlib is a plotting library for Python. It is used along with NumPy to provide an
environment that is an effective open source alternative for MatLab. It can also be used with
graphics toolkits like PyQt and wxPython.
Matplotlib module was first written by John D. Hunter. Since 2012, Michael Droettboom is
the principal developer. Currently, Matplotlib ver. 1.5.1 is the stable version available. The
package is available in binary distribution as well as in the source code form
on www.matplotlib.org.
Conventionally, the package is imported into the Python script by adding the following
statement −
Example -
import numpy as np
y = np.sin(x)
plt.plot(x, y)
plt.show()
Function
A function is a block of organized, reusable code that is used to perform a single, related action.
Defining a Function -
You can define functions to provide the required functionality. These are simple rules to define
a function in Python-
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string
of the function.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
Syntax-
Recursion allows a function to call itself. Fixed steps of code get executed again and again for
new values. We also have to set criteria for deciding when the recursive call ends.
Recursive Function in Python - A recursive function has to terminate to be used in a program.
A recursive function terminates, if with every recursive call the solution of the problem is
downsized and moves towards a base case. A base case is a case, where the problem can be
solved without further recursion. A recursion can lead to an infinite loop, if the base case is not
met in the calls.
Now we come to implement the factorial in Python. It's as easy and elegant as the mathematical
definition.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
Exception handling in python
An exception can be defined as an abnormal condition in a program resulting in the disruption in
the flow of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code is
not executed. Therefore, an exception is the error which python script is unable to tackle with.
Python provides us with the way to handle the Exception so that the other part of the code can
be executed without any disruption. However, if we do not handle the exception, the
interpreter doesn't execute all the code that exists after the that.
Common Exceptions -
A list of common exceptions that can be thrown from a normal python program is given
below.
Example -
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
Turtle Programming in Python
Turtle is a special feathers of Python. Using Turtle, we can easily draw in a drawing board. First
we import the turtle module. Then create a window, next we create turtle object and using turtle
method we can draw in the drawing board.
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
heading() None It returns the current heading
end_fill() None It closes the polygon and fills with the current fill color
Example -
import turtle
my_window = turtle.Screen()
my_pen = turtle.Turtle()
my_pen.forward(150)
my_pen.left(90)
my_pen.forward(75)
my_pen.color("white")
my_pen.pensize(12)
File Handling
File handling is an important part of any web application. Python has several functions for
creating, reading, updating, and deleting files. The key function for working with files in
Python is the open () function.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax -
f = open("demofile.txt")
Example -
Class − A user-defined prototype for an object that defines a set of attributes that characterize
any object of the class. The attributes are data members (class variables and instance variables)
and methods, accessed via dot notation.
Object − A unique instance of a data structure that's defined by its class. An object comprises
both data members (class variables and instance variables) and methods.
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):