0% found this document useful (0 votes)
7 views52 pages

Yogesh Report

Uploaded by

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

Yogesh Report

Uploaded by

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

AN

INDUSTRIAL TRAININGREPORT
ON
“PROGRAMING WITH PYTHON”
submitted
inpartialfulfilment
fortheawardoftheDegreeof
BachelorofTechnology
In Department of Information Technology Engg.

INDUSTRIAL TRAINING TAKEN AT “GRRAS” SOLUTION PVT. LTD., JAIPUR”


DEPARTMENT OF INFORMATION TECHNOLOGY ENGINEERING
ARYACOLLEGE OF ENGINEERING AND I.T.
SP-42,RIICO INDUSTRIAL AREA, KUKAS, JAIPUR(RAJASTHAN)-302028
Rajasthan Technical University, Kota (Raj.)

SUBMITTED BY SUBMITTED TO
Avinash Tiwari Mr.Sachin Yadav(Training Incharge)
17EARIT011 Dr. Akhil Pandey
(Head of Department)

(Dept. of Information TechnologyEngg.)


Session – 2020-21
TABLE OF CONTENTS
TableofContents ....... …………………………………………………..................…………….
ListofFigures ..................................................................................................................................
Listof Tables ...................................................................................................................................
Abstract ........................................................................................................................... .……….

Chapter 1: IntroductionofPYTHON ...................................................................................... 1-4


Python…………………………………………………………………………………………1
Scripting Language &OOPs Concept ...................................................................................... 1
History……………………………………………………………………………………..….2
Why ToLearnPython ...................................................................................................................3
PYTHONFeatures....................................................................................................................... 4

Chapter 2: LocalEnvironment Setup ................................................................................. 5-12


GettingPython .............................................................................................................................5
InstallingPython ......................................................................................................................... 6
Unix and LinuxInstallation ...........................................................................................................6
WindowsInstallation 6………………………………….……………………………………..7

SettingupPATH ........................................................................................................................... 7
RunningPython ........................................................................................................................... 9
2.4.1) Script from theCommandline ............................................................................................ 11
IntegratedDevelopmentEnvironment ...................................................................................... 11
PythonCodeExecution ................................................................................................................12
FirstPythonProgram .................................................................................................................. 12

Chapter 3: StandardDataType……………………………………………………...20-37
PythonNumbers............................................................................................................................20
PythonStrings ............................................................................................................................... 21
PythonLists ................................................................................................................................... 22
PythonTuples ................................................................................................................................ 23
PythonDictionary ......................................................................................................................... 24
DataTypeConversion ................................................................................................................... 24
DecisionMaking ............................................................................................................................ 27
LoopingStatements ....................................................................................................................... 28
Overview ofOOPs Terminology................................................................................................... 30
Chapter4… .................................................................... …………………………………...…38-39

Summary ....................................................................................................................................... 38

Reference &links .......................................................................................................................... 39


LIST OF FIGURES

Fig. No. Name of Figure Page No.

1.1 Van Rossum 2

2.1 Website URL to Download Python 8

2.2 Installing Python 8

2.3 Set Up the Path Variable 9

2.4 Python Execution 12

3.1 Decision Making 27


LIST OF TABLES

Table No. Name of Table Page No.

2.1. Variable Command Line Options in Python 10

2.2. List of Reserved Words 15

3.1. Different Numerical Types 21

3.2 Data Type Conversion 26

3.3 Decision Statements 28

3.4 Looping Statements 29

3.5 Base Overloading Methods 36


ABSTRACT

Python, an open source scripting language, has become the most popular introductory
teaching language at top U.S. universities, especially Georgia Tech University.
Because it is a scripting language, Python automates tasks that would otherwise need
to be performed manually. Python programs also tend to be shorter than equivalent
programs written in Java because of its built-in high-level data types and its dynamic
typing. John Guttag, professor of electrical engineering and computer science at MIT,
believes more colleges are using Python as an introductory programming language is
that it has a very large set of highly useful libraries that have been built over the years
that support things that are easy to use from language proper. Shriram Krishnamurthi, a
professor of computer science at Brown University, agrees Python has made people
feel more comfortable about exposing programming to a much broader audience of
students. Krishnamurthi says Python may be fashionable right now, but he believes it
lacks staying power.
CHAPTER 1

INTRODUCTION

1.1 PYTHON

Python is a high-level, interpreted, interactive and object-oriented


scriptinglanguage. Python is designed to be highly readable. It uses English
keywords frequently where as other languages use punctuation, and it has fewer
syntactical constructions than other languages.

 Python is Interpreted: Python is processed at runtime by the interpreter.


You do not need to compile your program before executing it. This is similar
to PERL and PHP.
 Python is Interactive: You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the
beginnerlevel programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.

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

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

1.3 PYTHON FEATURES:

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

2
Chapter 2

OPERTORS

2.1 ARITHMETIC OPERATORS

Table 2.1: Arithmetic Operators

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplies values on either side of the operator a * b = 200


Multiplication

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder

** Exponent Performs exponential (power) calculation on operators a**b =10 to the


power 20

3
// Floor Division - The division of operands where the 9//2 = 4 and
result is the quotient in which the digits after the
9.0//2.0 = 4.0,
decimal point are removed. But if one of the operands
is negative, the result is floored, i.e., rounded away -11//3 = -4,
from zero (towards negative infinity): 11.0//3 = -4.0

2.2ASSIGNMENT OPERATOR
Table 2.1: Assignment Operators

Operator Description Example

= Assigns values from right side operands to left c = a + b assigns


side operand value of a + b into
c

+= Add AND It adds right operand to the left operand and c += a is equivalent
assign the result to left operand to c

=c+ a

-= Subtract AND It subtracts right operand from the left operand c -= a is equivalent
and assign the result to left operand to c=c

–a

*= Multiply AND It multiplies right operand with the left operand c *= a is equivalent
and assign the result to left operand to c = c * a

4
/= Divide AND It divides left operand with the right operand
and assign the result to left operand c /= a is equivalent
to c = c / ac /= a is
equivalent to c =

c/a

%= Modulus It takes modulus using two operands and assign c %= a is equivalent


the result to left operand to c = c % a
AND

**= Exponent Performs exponential (power) calculation c **= a is

AND on operators and assign value to the left equivalent to c = c


operand ** a

//= Floor It performs floor division on operators and c //= a is equivalent


assign value to the left operand to c =
Division
c // a

2.3 IDENTITY OPERATOR

Table 2.4: Identity Operators


Operator Description Example

Is Evaluates to true if the variables on either side of the x is y, here is


operator point to the same object and false otherwise. results in 1 if
id(x) equals
id(y).

5
is not Evaluates to false if the variables on either side of the x is not y, here
operator point to the same object and true otherwise. is not results in
1 if id(x) is not
equal to id(y

2.4 COMPARISON OPERATOR

Table 2.5: Comparison Operator

Operator Description Example

& Binary Operator copies a bit to the result if it exists (a & b) (means 0000

AND in both operands 1100)

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means


0011 1101)

^ Binary It copies the bit if it is set in one operand but not (a ^ b) = 49 (means
XOR both. 0011 0001)

~ Binary It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means
Ones 1100 0011 in 2's
complement form due
Complement to a signed binary
number.

<< Binary a << 2 = 240 (means


Left Shift The left operands value is moved left by the 1111 0000)
number of bits specified by the right operand.

6
>> Binary The left operands value is moved right by the a >> 2 = 15 (means
Right Shift number of bits specified by the right operand.
0000 1111)

2.5 LOGICAL OPERATOR

Table 2.6: Logical Operators


Operator Description Example

and Logical If both the operands are true then condition becomes (a and b) is true.
AND true.

or Logical OR If any of the two operands are non-zero then (a or b)

condition becomes true. is true.

not Logical Used to reverse the logical state of its operand. Not(a and b) is
NOT false.

2.6 MEMBERSHIP OPERATORS

Table 2.7: Membership Operators


Operator Description Example

in Evaluates to true if it finds a variable in the specified x in y, here in


sequence and false otherwise. results in a 1 if x is
a member of
sequence y.

7
not in Evaluates to true if it does not finds a variable in the x not in y, here not
specified sequence and false otherwise. in results in a

1 if x is not a
member of
sequence y.

2.7 PYTHON OPERATORS PRECEDENCE

Table 3.8: Python precedence Operator

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the last two are
+@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>><< Right and left bitwise shift

& Bitwise 'AND'

8
^| Bitwise exclusive `OR' and regular `OR'

<= <>>= Comparison operators

<> == != Equality operators

= %= Assignment operators
/=//= -=
+= *= =*

is is not Identity operators

in not in Membership operators

not or and Logical operators

9
Chapter3
COLLECTION IN PYTHON

3.1 LIST

The list is a most versatile data type available in Python which can be written as a
list of comma-separated values (items) between square brackets. Important thing
about a list is that items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between


square brackets. For example −
list1 = ['physics', 'chemistry', 1997,
2000]; list2 = [1, 2, 3, 4, 5 ]; list3 =
["a", "b", "c", "d"]

3.2 BASIC LIST OPERATIONS

Lists respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new list, not a string.

Table 3.1: Basic List Operation

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

10
for x in [1, 2, 3]: print x, 123 Iteration

Python includes following list methods

Table 3.2: Python List Methods


Methods with Description
SN

1 list.append(obj)

Appends object obj to list

2 list.count(obj)

Returns count of how many times obj occurs in list

3 list.index(obj)

Returns the lowest index in list that obj appears

4 list.insert(index, obj)

Inserts object obj into list at offset index

5 list.pop(obj=list[-1])

Removes and returns last object or obj from list

6 list.remove(obj)

Removes object obj from list

11
7 list.reverse()

Reverses objects of list in place

8 list.sort([func])

Sorts objects of list, use compare function if given

3.3 TUPLES

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values.


Optionally we can put these comma-separated values between parentheses also. For
example −

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

tup2 = (1, 2, 3, 4, 5 );

The empty tuple is written as two parentheses containing nothing −

tup1 = ();

To write a tuple containing a single value you have to include a comma, even
though there is only one value −

tup1 = (50,);

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and
so on.

12
Accessing Values in Tuples:

To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example –

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

tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]:

", tup1[0] print "tup2[1:5]: ", tup2[1:5]

When the code is executed, it produces the following result −

tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Updating Tuples:

Tuples are immutable which means you cannot update or change the values of tuple
elements. We are able to take portions of existing tuples to create new tuples as the
following example demonstrates −

tup1 = (12, 34.56);

tup2 = ('abc', 'xyz');

tup3 = tup1 + tup2;

print tup3

When the above code is executed, it produces the following result −

(12, 34.56, 'abc', 'xyz')

13
Delete Tuple Elements

Removing individual tuple elements is not possible. There is, of course, nothing
wrong with putting together another tuple with the undesired elements discarded.

To explicitly remove an entire tuple, just use the del statement.

Basic Tuples Operations:

Table 3.3: Basic Tuple Operations

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

3.4 DICTIONARY

Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.

14
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.

Accessing Values in Dictionary:

To access dictionary elements, you can use the familiar square brackets along with
the key to obtain its value. Following is a simple example −

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

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

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

Result –

dict['Name']: Zara dict['Age']:

Updating Dictionary

We can update a dictionary by adding a new entry or a key-value pair, modifying an


existing entry, or deleting an existing entry as shown below in the simple example −

We can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation.

15
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example –

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

del dict['Name']; # remove entry with key

'Name' dict.clear(); # remove all entries in

dict del dict ; # delete entire dictionary

print "dict['Age']:

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

dict['School']

16
CHAPTER 4

FUNCTIONS IN PYTHON

A function is a block of organized, reusable code that is used to perform a single,


related action. Functions provide better modularity for your application and a high
degree of code reusing. Python gives you many built-in functions like print(), etc.
but you can also create your own functions. These functions are called user-defined
functions.

4.1 DEFINING A FUNCTION

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 or docstring.

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

def functionname( parameters ):

"function_docstring" function_suite return


[expression]

17
4.2 CALLING A FUNCTION

Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code. Once the basic structure
of a function is finalized, you can execute it by calling it from another function or
directly from the
Python prompt. Following is the example to call printme() function

# Function definition is here

def printme( str ):

"This prints a passed string into this function" print

str return;

# Now you can call printme function printme("I'm first


call to user defined function!")
printme("Again second call to the same function")
4.3 FUNCTION ARGUMENTS

You can call a function by using the following types of formal arguments:

• Required arguments

• Keyword arguments

• Default arguments

• Variable-length arguments

4.4 SCOPE OF VARIABLES

All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.The scope of a variable
determines the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python –

18
CHAPTER 5

PYTHON FILES I/O

5.1 PRINTING TO THE SCREEN

The simplest way to produce output is using the print statement where you can pass
zero or more expressions separated by commas. This function converts the
expressions you pass into a string and writes the result to standard output as follows

print "Python is really a great language,", "isn't

it?"

Result:

Python is really a great language, isn't it?

5.2 READING KEYBOARD INPUT

Python provides two built-in functions to read a line of text from standard input,
which by default comes from the keyboard. These functions are −

• raw_input

• input

The raw_input Function

The raw_input([prompt]) function reads one line from standard input and returns it
as a string (removing the trailing newline).

str = raw_input("Enter your input: ");

print "Received input is : ", str

19
This prompts you to enter any string and it would display same string on the screen.
When I typed "Hello Python!", its output is like this −

Enter your input: Hello Python

Received input is : Hello Python


The input Function

The input([prompt]) function is equivalent to raw_input, except that it assumes the


input is a valid Python expression and returns the evaluated result to you.

str = input("Enter your input: ");

print "Received input is : ", str

This would produce the following result against the entered input −

Enter your input: [x*5 for x in range(2,10,2)]

Recieved input is : [10, 20, 30, 40]

Opening and Closing Files

Until now, you have been reading and writing to the standard input and output.
Now, we will see how to use actual data files.

Python provides basic functions and methods necessary to manipulate files by


default.
You can do most of the file manipulation using a file object.

The open Function

Before you can read or write a file, you have to open it using Python's builtinopen()
function. This function creates a file object, which would be utilized to call other
support methods associated with it. Syntax

20
file object = open(file_name [, access_mode][, buffering])

Here are parameter details:

• file_name: The file_name argument is a string value that contains the name
of the file that you want to access.

• access_mode: The access_mode determines the mode in which the file has
to be opened, i.e., read, write, append, etc. A complete list of possible values
is given below in the table. This is optional parameter and the default file
access mode is read (r).

• buffering: If the buffering value is set to 0, no buffering takes place. If the


buffering value is 1, line buffering is performed while accessing a file. If you
specify the buffering value as an integer greater than 1, then buffering action
is performed with the indicated buffer size. If negative, the buffer size is the
system default(default behavior).

Here is a list of the different modes of opening a file –

Table 5.1: Modes of Opening a File

Modes Description

r Opens a file for reading only. The file pointer is placed at the beginning of
the file. This is the default mode.

rb Opens a file for reading only in binary format. The file pointer is placed at
the beginning of the file. This is the default mode.

21
r+ Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.

rb+ Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.

w Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.

wb Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.

w+ Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and
writing.

wb+ Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file does not exist, creates
a new file for reading and writing.

A Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.

Ab Opens a file for appending in binary format. The file pointer is at the end of
the file if the file exists. That is, the file is in the append mode. If the file
does not exist, it creates a new file for writing.

22
a+ Opens a file for both appending and reading. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does
not exist, it creates a new file for reading and writing.

ab+ Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading and writing.

The close() Method

The close() method of a file object flushes any unwritten information and closes the
file object, after which no more writing can be done.Python automatically closes a
file when the reference object of a file is reassigned to another file. It is a good
practice to use the close() method to close a file.
Syntax

fileObject.close();

Example

# Open a file fo = open("foo.txt", "wb")

print "Name of the file: ", fo.name

# Close opend file fo.close()

23
5.3 READING AND WRITING FILES

The file object provides a set of access methods to make our lives easier. We would
see how to use read() and write() methods to read and write files.

The write() Method

The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.The write() method does not
add a newline character ('\n') to the end of the string Syntax

fileObject.write(string);

The read() Method

The read() method reads a string from an open file. It is important to note that

Python strings can have binary data. apart from text data. Syntax

fileObject.read([count]);

Here, passed parameter is the number of bytes to be read from the opened file. This
method starts reading from the beginning of the file and if count is missing, then it
tries to read as much as possible, maybe until the end of file.

CHAPTER 6

PYTHON EXCEPTIONS HANDLING

Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them −

24
• Exception Handling: This would be covered in this tutorial.
Here is a list standard Exceptions available in
Python:StandardExceptions.

• Assertions: This would be covered inAssertions in Python

List of Standard Exceptions –

Table 6.1: List of common error messages

EXCEPTION DESCRIPTION
NAME

Exception Base class for all exceptions

StopIteration Raised when the next() method of an iterator does not point to
any object.

SystemExit Raised by the sys.exit() function.

StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.

ArithmeticError Base class for all errors that occur for numeric calculation.

25
OverflowError Raised when a calculation exceeds maximum limit for a numeric
type.

FloatingPointError Raised when a floating point calculation fails.

ZeroDivisionError Raised when division or modulo by zero takes place for all
numeric types.

AssertionError Raised in case of failure of the Assert statement.

AttributeError Raised in case of failure of attribute reference or assignment.

EOFError Raised when there is no input from either the raw_input() or


input() function and the end of file is reached.

ImportError Raised when an import statement fails.

KeyboardInterrupt Raised when the user interrupts program execution, usually by


pressing Ctrl+c.

LookupError Base class for all lookup errors.

26
IndexError Raised when an index is not found in a sequence.

KeyError Raised when the specified key is not found in the dictionary.

NameError Raised when an identifier is not found in the local or global


namespace.

IOError Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
IOError
does not exist.

Raised for operating system-related errors.

SyntaxError Raised when there is an error in Python syntax.

IndentationError Raised when indentation is not specified properly.

SystemError Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.

6.1 WHAT IS EXCEPTION?

27
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. In general, when a Python
script encounters a situation that it cannot cope with, it raises an exception. An
exception is a Python object that represents an error.

When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

6.2 HANDLING AN EXCEPTION

If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include
an except: statement, followed by a block of code which handles the problem as
elegantly as possible.

CHAPTER 7

PYTHON OBJECT ORIENTED

Python has been an object-oriented language since it existed. Because of this,


creating and using classes and objects are downright easy. This chapter helps you
become an expert in using Python's object-oriented programming support.

If you do not have any previous experience with object-oriented (OO)


programming, you may want to consult an introductory course on it or at least a
tutorial of some sort so that you have a grasp of the basic concepts.

However, here is small introduction of Object-Oriented Programming (OOP) to


bring you at speed −

7.1 OVERVIEW OF OOP TERMINOLOGY

• 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

28
(class variables and instance variables) and methods, accessed via dot
notation.

• Class variable: A variable that is shared by all instances of a class. Class


variables are defined within a class but outside any of the class's methods.
Class variables are not used as frequently as instance variables are.

• Data member: A class variable or instance variable that holds data


associated with a class and its objects.

• Function overloading: The assignment of more than one behavior to a


particular function. The operation performed varies by the types of objects or
argument

• Instance variable: A variable that is defined inside a method and belongs


only to the current instance of a class.

• Inheritance: The transfer of the characteristics of a class to other classes that


are derived from it.

• Instance: An individual object of a certain class. An object obj that belongs


to a class Circle, for example, is an instance of the class Circle.

• Instantiation: The creation of an instance of a class.

• Method : A special kind of function that is defined in a class definition.

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

• Operator overloading: The assignment of more than one function to a


particular operator.

29
7.2 CREATING CLASSES

The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −

class ClassName:

'Optional class documentation string'


class_suite
• The class has a documentation string, which can be accessed via

ClassName.__doc__.

• The class_suite consists of all the component statements defining class


members, data attributes and functions.

7.3 CLASS INHERITANCE

Instead of starting from scratch, you can create a class by deriving it from a
preexisting class by listing the parent class in parentheses after the new class name.

The child class inherits the attributes of its parent class, and you can use those
attributes as if they were defined in the child class. A child class can also override
data members and methods from the parent.

Syntax

Derived classes are declared much like their parent class; however, a list of base
classes to inherit from is given after the class name −

class SubClassName (ParentClass1[, ParentClass2, ...]):

'Optional class documentation string' class_suite

30
7.4 OVERRIDING METHODS

You can always override your parent class methods. One reason for overriding

parent's methods is because you may want special or different functionality in your

subclass. Example

class Parent: # define parent class def

myMethod(self):

print 'Calling parent method' class

Child(Parent): # define child class def

myMethod(self):

print 'Calling child method' c =

Child() # instance of child

c.myMethod() # child calls overridden method


When the above code is executed, it produces the following result −

Calling child method

7.5 BASE OVERLOADING METHODS

Following table lists some generic functionality that you can override in your own
classes –

Table 7.1: Base Overloading Methods

SN Method, Description & Sample Call

31
1 __init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call :obj = className(args)

2 __del__( self )
Destructor, deletes an object
Sample Call :delobj

3 __repr__( self )
Evaluatable string representation
Sample Call :repr(obj)

4 __str__( self )
Printable string representation
Sample Call :str(obj)

5 __cmp__ ( self, x )
Object comparison
Sample Call :cmp(obj, x)

7.6 OVERLOADING OPERATORS

Suppose you have created a Vector class to represent two-dimensional vectors, what
happens when you use the plus operator to add them? Most likely Python will yell at
you.

32
You could, however, define the __add__ method in your class to perform vector
addition and then the plus operator would behave as per expectation −
7.7 DATA HIDING

An object's attributes may or may not be visible outside the class definition. You
need to name attributes with a double underscore prefix, and those attributes then
are not be directly visible to outsiders.

Example

class JustCounter:

__secretCount = 0

def count(self):

self.__secretCount += 1 print self.__secretCount


counter = JustCounter() counter.count()
counter.count() print counter.__secretCount
Python protects those members by internally changing the name to include the class
name. You can access such attributes as object._className__attrName. If you
would replace your last line as following, then it works for you −

print counter._JustCounter__secretCount

33
Chapter 8
DJANGO

Django is a high-level Python web framework that enables rapid development of


secure and maintainable websites. Built by experienced developers, Django takes
care of much of the hassle of web development, so you can focus on writing your
app without needing to reinvent the wheel. It is free and open source, has a
thriving and active community, great documentation, and many options for free
and paid-for support.

Django helps you write software that is:

• Complete: Django follows the "Batteries included" philosophy and provides


almost everything developers might want to do "out of the box". Because
everything you need is part of the one "product", it all works seamlessly
together, follows consistent design principles, and has extensive andup-to-
date documentation.

• Versatile: Django can be (and has been) used to build almost any type of
website — from content management systems and wikis, through to social
networks and news sites. It can work with any client-side framework, and
can deliver content in almost any format (including HTML, RSS feeds,
JSON, XML, etc). The site you are currently reading is based on Django!
Internally, while it provides choices for almost any functionality you might
want (e.g. several popular databases, templating engines, etc.), it can also be
extended to use other components if needed.

• Secure: Django helps developers avoid many common security mistakes by


providing a framework that has been engineered to "do the right things" to
protect the website automatically. For example, Django provides a secure
way to manage user accounts and passwords, avoiding common mistakes like
putting session information in cookies where it is vulnerable (instead cookies
just contain a key, and the actual data is stored in the database) or directly

34
storing passwords rather than a password hash. A password hash is a
fixedlength value created by sending the password through acryptographic
hashfunction.Django can check if an entered password is correct by running
it through the hash function and comparing the output to the stored hash
value.

However due to the "one-way" nature of the function, even if a stored hash
value is compromised it is hard for an attacker to work out the original
password.

• Scalable: Django uses a component-based “shared-nothing”architecture


(each part of the architecture is independent of the others, and can hence be
replaced or changed if needed). Having a clear separation between the
different parts means that it can scale for increased traffic by adding
hardware at any level: caching servers, database servers, or application
servers. Some of the busiest sites have successfully scaled Django to meet
their demands (e.g. Instagram and Disqus, to name just two).

• Maintainable: Django code is written using design principles and patterns


that encourage the creation of maintainable and reusable code. In particular,
it makes use of the Don't Repeat Yourself (DRY) principle so there is no
unnecessary duplication, reducing the amount of code. Django also promotes
the grouping of related functionality into reusable "applications" and, at a
lower level, groups related code into modules (along the lines of theModel
View Controller (MVC) pattern).

• Portable: Django is written in Python, which runs on many platforms. That


means that you are not tied to any particular server platform, and can run
your applications on many flavours of Linux, Windows, and Mac OS X.
Furthermore, Django is well-supported by many web hosting providers, who
often provide specific infrastructure and documentation for hosting Django
sites.

8.1 WHAT DOES DJANGO CODE LOOK LIKE?

35
In a traditional data-driven website, a web application waits for HTTP requests
from the web browser (or other client). When a request is received the application
works out what is needed based on the URL and possibly information in POST
data or GET data. Depending on what is required it may then read or write
information from a database or perform other tasks required to satisfy the request.
The application will then return a response to the web browser, often dynamically
creating an HTML page for the browser to display by inserting the retrieved data
into placeholders in an HTML template.

8.2 FLOW CHART OF DJANGO APPLICATION

Django web applications typically group the code that handles each of these steps
into separate files:

Fig8.1: Flow chart of Django Application

36
Explanation of parts of flow chart is as follows:

• URLs: While it is possible to process requests from every single URL via a
single function, it is much more maintainable to write a separate view
function to handle each resource. A URL mapper is used to redirect HTTP
requests to the appropriate view based on the request URL. The URL mapper
can also match particular patterns of strings or digits that appear in an URL,
and pass these to a view function as data.

• View: A view is a request handler function, which receives HTTP requests


and returns HTTP responses. Views access the data needed to satisfy
requests via models, and delegate the formatting of the response to templates.
• Models: Models are Python objects that define the structure of an
application's data, and provide mechanisms to manage (add, modify, delete)
and query records in the database.

• Templates: A template is a text file defining the structure or layout of a file


(such as an HTML page), with placeholders used to represent actual
content. A view can dynamically create an HTML page using an HTML
template, populating it with data from a model. A template can be used to
define the structure of any type of file; it doesn't have to be HTML!

37
CHAPTER 9

RESULT AND ANALYSIS OF PROJECT


Home Page:-

Fig 9.1: Home Page

New Banking User Page: -

38
Fig 9.2: New Banking User Page

New Banking User Page (When invalid entries are inserted): -

Fig 9.3: New Banking User Page

39
User Table Page: -

Fig 9.4: User Table Page

User Details Page: -

Fig 9.5: User Details Page

40
User Edit Page: -

Fig 9.6: User Edit Page

SignIn Page: -

Fig 9.7: SignIn Page

41
SignUp Page: -

Fig 9.8:SignUp Page

CHAPTER 10

FLASK
If you're developing a web app in Python, chances are you're leveraging a framework. A
framework "is a code library that makes a developer's life easier when building reliable,
scalable, and maintainable web applications" by providing reusable code or extensions
for common operations. There are a number of frameworks for Python, including Flask,
Tornado, Pyramid, and Django.
Flask is a small and powerful web framework for Python. It's easy to learn and simple to
use, enabling you to build your web app in a short amount of time.
In this article, I'll show you how to build a simple website, containing two static pages
with a small amount of dynamic content. While Flask can be used for building complex,
databasedriven websites, starting with mostly static pages will be useful to introduce a
workflow, which we can then generalize to make more complex pages in the future.

42
Upon completion, you'll be able to use this sequence of steps to jumpstart your next
Flask app.

Installing FLASK
Before getting started, we need to install Flask. Because systems vary, things can
sporadically go wrong during these steps. If they do, like we all do, just Google the error
message or leave a comment describing the problem.
Install virtualenv
Virtualenv is a useful tool that creates isolated Python development environments where
you can do all your development work.
We'll use virtualenv to install Flask. Virtualenv is a useful tool that creates isolated
Python development environments where you can do all your development work.
Suppose you come across a new Python library that you'd like to try. If you install it
system-wide, there is the risk of messing up other libraries that you might have
installed. Instead, use virtualenv to create a sandbox, where you can install and use the
library without affecting the rest of your system. You can keep using this sandbox for
ongoing development work, or you can simply delete it once you've finished using it.
Either way, your system remains organized and clutter-free.
It's possible that your system already has virtualenv. Refer to the command line, and try
running: $ virtualenv –version

Install flask
After installing virtualenv, you can create a new isolated development environment, like
so: $ virtualenvflaskapp
Here, virtualenv creates a folder, flaskapp/, and sets up a clean copy of Python inside for
you to use. It also installs the handy package manager, pip.
Enter your newly created development environment and activate it so you can begin
working within it.
$ cd flaskapp
$ . bin/activate
Now, you can safely install Flask:

43
$ pip install Flask

Setting up the Project Structure

01 .
02 .
03 ├── app
04 │ ├── static
05 │ │ ├── css
06 │ │ ├── img
07 │ │ └── js
08 │ ├── templates
09 │ ├── routes.py
10 │ └── README.md

Within flaskapp/, create a folder, app/, to contain all your files. Inside app/, create a
folder static/; this is where we'll put our web app's images, CSS, and JavaScript files, so
create folders for each of those, as demonstrated above. Additionally, create another
folder, templates/, to store the app's web templates. Create an empty Python file
routes.py for the application logic, such as URL routing.
And no project is complete without a helpful description, so create a README.md file
as well.

CONCLUSION
In programming the constructs we have learnt (loops, conditions, data structures)
mean that we are far more expressive as programmers. Combined with abstractions
we can compose and recompose new programs. Building on our previously defined
concept of a house we now use repetition to define a row of houses.

Computers are complex. Even the smallest operation hides layers of incredible
complexity. Programming is not only about getting a computer to do things. It is

44
about writing code that is useful to humans. Good programming is harnessing
complexity by writing code that rhymes with our intuitions. Good code is code that
we can use with a minimal amount of context and already be productive.

The two major advantages are:

• detail and complexity are hidden.

• the definition of the function object called square is shorter clearer and truer
to its mathematical (conceptual) definition.

This course illustrates that creative programming is about constructing useful


abstractions. It is also about exercising your intuition to make you more productive.

In design we have gone from step by step instructions to defining blocks of code in
such a way as to define higher level concepts. Defining reusable components and
the ability to repeat them is immensely powerful.

Think of everything you can make from Lego bricks. Minecraft is a world build
with cubes. In the real world think of all the components and repetition you
typically find in a skyscraper.

This is where programming starts to become creative. You can define the universe
of things that is of interest to you.

REFERENCES
[1.]Training Manual

[2.]http://python.org

[3.]http://diveintopython.org

45
[4.]http://djangoproject.com

[5.]http://GeeksForGeeks.com

46

You might also like