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

Python 6

This is Python report description.

Uploaded by

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

Python 6

This is Python report description.

Uploaded by

Neha Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Project Report On

“PYTHON LANGUAGE”

Submitted in partial fulfillment of


award of the Degree of
M.Tech., (Session: 2019 – 20)

Submitted to: Submitted by:


Mr. Umesh Chandra Jaiswal Neha Singh
Department of Computer Science & Engg. M.Tech.(CSE&2nd)
Roll No:2018023211
Session: 2019– 2020

Department of Computer Science & Engineering


MADAN MOHAN MALAVIYA UNIVERSITY OF
TECHNOLOGY, GORAKHPUR
ACKNOWLEDGEMENT

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

constant guidance and encouragement crown all efforts with success.

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

colleagues who have helped in successful completion of the project.

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.

I wish them success at every stage of their career.

Mr. Ashwani Kumar Gupta


Introduction about the Industry

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

Our aim is to provide an extremely high level of knowledge to our students to


compliment the high quality of the courses, and the value for money they provide.

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]

CHAPTER 2 Data Structure in Python [02-03]

CHAPTER 3 Operators in Python [04-08]

CHAPTER 4 Loops in Python [09-10]

CHAPTER 5 Arrays in Python [10-16]

CHAPTER 6 Matplotlib in Python [17-21]

CHAPTER 7 Function & Recursion [22]

CHAPTER 8 Conclusion [23]

CHAPTER 9 Future Scope [24]

CHAPTER 10 Learning after Training [25]


INTRODUCTION
What is Python? - Python is a general-purpose interpreted, interactive, object-oriented, and
high-level programming language. It was created by Guido van Rossum during 1985- 1990.
Like Perl, Python source code is also available under the GNU General Public License (GPL).
Python was conceived in the late 1980s as a successor to the ABC language.

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.

How is Python Used? - Python is a general-purpose programming language, which is


another way to say that it can be used for nearly everything. Most importantly, it is an interpreted
language, which means that the written code is not actually translated to a computer-readable
format at runtime. Whereas, most programming languages do this conversion before the program
is even run. This type of language is also referred to as a "scripting language" because it was
initially meant to be used for trivial projects.

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.

 Easy-to-maintain − Python's source code is fairly easy-to-maintain.

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

 Databases − Python provides interfaces to all major commercial databases.

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

Differences between Python 2 and Python 3 -

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/

You can download Python documentation from https://www.python.org/doc/. The


documentation is available in HTML, PDF, and PostScript formats.
Installing Python -
Python distribution is available for a wide variety of platforms. You need to download only the
binary code applicable for your platform and install Python.

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.

First Python Program -


Let us execute programs in different modes of programming.

1. Interactive Mode Programming -Type the following text at the Python prompt and press
the Enter –

>> print "Hello, Python!

This produces the following result –


Hello, Python!

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 –

Print "Hello, Python!"

This produces the following result –


Hello, Python!
Data Structures in Python

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.

Python supports two types of comments:

1) Single Line Comment - In case user wants to specify a single line comment, then comment
must start with ?#? -

Example –

# This is single line comment.

2) Multi Line Comment - Multi lined comment can be given inside triple quotes.

Example –

''''' This Is Multipline comment'''

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 –

list1 = ['physics', 'chemistry', 1997, 2000]


list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

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 –

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

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

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Name']: ", dict['Name']


print "dict['Age']: ", dict['Age']

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.

 ord () - This function is used to convert a character to integer.

 hex () - This function is to convert integer to hexadecimal string.

 oct () - This function is to convert integer to octal string.

 tuple () - This function is used to convert to a tuple.

 set () - This function returns the type after converting to set.

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

 str () - Used to convert integer into a string.

 complex (real, imag) - This function converts real numbers to complex(real,imag)


number.
Operators in Python

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

Arithmetic operators - Arithmetic operators are used to perform arithmetic operations


between two operands. It includes +(addition), - (subtraction), *(multiplication), /(divide),
%(reminder), //(floor division), and exponent (**).

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.

 Element − Each item stored in an array is called an element.


 Index − Each location of an element in an array has a numerical index, which is used to
identify the element.
Array Representation - Arrays can be declared in various ways in different languages. Below
is an illustration.

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

from array import *

arrayName = array(typecode, [Initializers])


Adding Array Elements - You can use the append ( ) method to add an element to an array.
2D Array - Two dimensional array is an array within an array. It is an array of arrays. In this
type of array the position of an data element is referred by two indices instead of one. So it
represents a table with rows an dcolumns of data. In the below example of a two dimensional
array, observer that each array element itself is also an array.

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

The above data can be represented as a two dimensional array as below.

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

Accessing Values in a Two Dimensional Array -


The data elements in two dimensional arrays can be accessed using two indices. One index
referring to the main or parent array and another index referring to the position of the data
element in the inner array. If we mention only one index then the entire inner array is printed for
that index position. The example below illustrates how it works.

from array import *

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [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 −

 Mathematical and logical operations on arrays.

 Fourier transforms and routines for shape manipulation.

 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 −

from matplotlib import pyplot as plt


Here pyplot () is the most important function in matplotlib library, which is used to plot 2D
data.

Example -

import numpy as np

import matplotlib.pyplot as plt

x = np.arange(0, 3 * np.pi, 0.1)

y = np.sin(x)

plt.title("sine wave form")

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-

def functionname ( parameters ):


"function"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same
order that they were defined.
Recursion

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.

1. ZeroDivisionError: Occurs when a number is divided by zero.


2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

Problem without handling exceptions –


Example -
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
print("Hi I am other part of the program")

ZeroDivisionError: division by zero -


Syntax -
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code

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.

Some turtle method -

METHOD PARAMETER DESCRIPTION

Turtle() None It creates and returns a new turtle object

forward() Amount It moves the turtle forward by the specified amount

backward() Amount It moves the turtle backward by the specified amount

right() Angle It turns the turtle clockwise

left() Angle It turns the turtle counter clockwise

penup() None It picks up the turtle’s Pen

pendown() None Puts down the turtle’s Pen

up() None Picks up the turtle’s Pen

down() None Puts down the turtle’s Pen

color() Color name Changes the color of the turtle’s pen

fillcolor() Color name Changes the color of the turtle will use to fill a polygon
heading() None It returns the current heading

position() None It returns the current position

goto() x, y It moves the turtle to position x,y

begin_fill() None Remember the starting point for a filled polygon

end_fill() None It closes the polygon and fills with the current fill color

dot() None Leaves the dot at the current position

stamp() None Leaves an impression of a turtle shape at the current


location

shape() Shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’

Example -

import turtle

my_window = turtle.Screen()

my_window.bgcolor("blue") # creates a graphics window

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.

The open () function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"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

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax -

f = open("demofile.txt")

Example -

f= open ("demofile.txt", "r")


print(f.read())
Object Oriented Programming

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.

Example - Following is the example of a simple Python class −

class Employee:

'Common base class for all employees'

empCount = 0

def __init__(self, name, salary):

self.name = name

self.salary = salary

Employee.empCount += 1

def displayCount(self):

print "Total Employee %d" % Employee.empCount

def displayEmployee(self):

print "Name : ", self.name, ", Salary: ", self.salary

You might also like