PYTHON
PYTHON
CERTIFICATE
Computer Science Branch has been found satisfactory and is approved for submission.
i
CERTIFICATE
ii
iii
ABSTRACT
The objective of a practical training is to learn something about industries practically and
to be familiar with a working style of a technical worker to adjust simply according to
industrial environment. This report deals with the equipment’s their relation and their general
operating principle. Python, an interpreted language which was enveloped by Guido van
Rossum came into implementation in 1989. The language supports both object-oriented and
procedure-oriented approach. Python is designed to be a highly extensible language. Python
works on the
principle of “there is only one obvious way to do a task” rather than “there is more than one
way to solve a particular problem”. Python is very easy to learn and implement. The simpler
syntax, uncomplicated semantics and approach with which Python has been developed makes
it very easier to learn. A large number of python implementations and extensions have been
developed since its inception.
Training Cover provides both six weeks as well as six months industrial training in Python.
Python is divided into two parts as “Core Python” and “Advance Python”. Accordingly, all
the basic and advanced topics are discussed in both of the modules.
iv
TABLE OF CONTENTS
CERTIFICATE ........................................................................................................................ i
CANDIDATE DECLARATION ............................................................................................ ii
ACKNOWLEDGEMENT ..................................................................................................... iii
ABSTRACT…...................................................................................................................... iv
1.2 History
2. Operator… ............................................................................................................................ 4
3.1 List
3.2 Tuple
3.3 Dictionary
4. Functions .............................................................................................................................. 17
v
Chapter 1
INTRODUCTION
1.1 PYTHON
Python is a high-level, interpreted, interactive and object-oriented scripting language. 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.
1
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,
Small Talk, 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.
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.
Interactive Mode:
Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
2
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.
large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It can be easily integrated with C, C++, COM, ActiveX, CORBA and java.
3
Chapter 2
OPERATORS
4
2.1 ARITHMETIC OPERATORS
5
2.2ASSIGNMENT OPERATOR
c = a + b
= Assigns values from right side operands to left side assigns value
operand of a + b into c
+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent to c
=c+a
c -= a is
-= Subtract AND It subtracts right operand from the left operand and equivalent to c
assign the result to left operand =c-a
c *= a is
*= Multiply AND It multiplies right operand with the left operand and equivalent to c
assign the result to left operand =c*a
c /= a is
/= Divide AND It divides left operand with the right operand and equivalent to c
assign the result to left operand = c / ac /= a is
equivalent to
c=c/a
6
2.3 LOGICAL OPERATOR
and Logical AND If both the operands are true (a and b) are true
then condition becomes true.
not Logical NOT Used to reverse the logical state Not(a and b) is false.
of its operand.
7
Python Operators Precedence
~+- Complement, unary plus and minus (method names for the last two are
+@ and -@)
8
Chapter 3
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.
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.
9
Python Expression Results Description
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
10
Python includes following list methods
list. append(obj)
1 Appends object obj to list
list. count(obj)
2 Returns count of how many times obj occurs in list
list. extend(seq)
3 Appends the contents of seq to list
list.index(obj)
4 Returns the lowest index in list that obj appears
list.insert(index, obj)
5 Inserts object obj into list at offset index
list.pop(obj=list[-1])
6 Removes and returns last object or obj from list
list.remove(obj)
7 Removes object obj from list
list.reverse()
8 Reverses objects of list in place
list.sort([func])
9 Sorts objects of list, use compare function if given
11
3.2 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 –
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
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
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. For example:
13
Basic Tuples Operations:
14
3.3 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: {}.
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.
Result –
dict['Name']: Zara
dict['Age']: 7
15
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 –
Result −
dict['Age']: 8 dict['School']: DPS School
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. To explicitly remove
an entire dictionary, just use the del statement. Following is a simple example –
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.
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 code block within every function starts with a colon (:) and is indented.
17
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 Arguments
You can call a function by using the following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
18
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 −
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
Following is a simple example −
Result −
Inside the function local total: 30
Outside the function global total: 0
19
Chapter 5
PYTHON MODULES
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference. Simply, a module is a file
consisting of Python code. A module can define functions, classes and variables. A module
can also include runnable code.
Example:
The Python code for a module named aname normally resides in a file named aname.py.
Here's an example of a simple module, support.py
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches
before importing a module. For example, to import the module support.py, you need to put
the following command at the top of the script
A module is loaded only once, regardless of the number of times it is imported. This prevents
the module execution from happening over and over again if multiple imports occur.
20
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and sub packages and sub-sub packages.
Consider a file Pots.py available in Phone directory. This file has following line of source
code −
Similar way, we have another two files having different functions with the same name as
above −
Phone/_init_.py
To make all of your functions available when you've imported Phone, to put explicit import
statements in _init_.py as follows −
After you add these lines to _init_.py, you have all of these classes available when you import
the Phone package.
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
21
Phone.G3()
RESULT:
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
In the above example, we have taken example of a single functions in each file, but you can
keep multiple functions in your files. You can also define different Python classes in those
files and then you can create your packages out of those classes.
22
Chapter 6
PYTHON FILES I/O
This chapter covers all the basic I/O functions available in Python.
Result:
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).
23
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
This would produce the following result against the entered input −
Enter your input: [x*5 for x in range (2,10,2)]
Received input is: [10, 20, 30, 40]
24
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).
25
Chapter 7
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 −
Exception Handling:
This would be covered in this tutorial. Here is a list standard Exceptions available in
Python: Standard Exceptions.
Assertions:
This would be covered in Assertions in Python
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.
ArithmeticError Base class for all errors that occur for numeric calculation.
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.
26
What is Exception?
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.
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.
27
Chapter 8
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.
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.
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
28
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.
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_.
.
29
The class_suite consists of all the component statements defining class members, data
attributes and functions.
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 −
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
30
When the above code is executed, it produces the following result −
31
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.
You could, however, define the_add_ method in your class to perform vector addition and
then the plus operator would behave as per expectation −
Example
class Vector :
def _init_ (self , a, b):
self .a = a
self . b = b
def _str_ (self ):
return 'Vector (%d, %d)' % (self .a, self . b)
def _add_ (self, other):
return Vector (self .a + other .a, self . b + other . b)
v1 = Vector (2,10)
v2 = Vector (5,-2)
print v1 + v2
Vector (7,8)
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
32
Result −
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter . _secretCount
AttributeError : JustCounter_ instance has no attribute '_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
1
2
2
33
Chapter 9
Python MySQL Database Access
The Python standard for database interfaces is the Python DB-API. Most Python database
interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a
wide range of database servers such as −
GadFly
mSQL
MySQL
PostgreSQL
Informix
Interbase
Oracle
Sybase
34
The DB API provides a minimal standard for working with databases using Python structures
and syntax wherever possible. This API includes the following:
35
REFERENCES
Training Manual
http://python.org
http://diveintopython.org
http://djangoproject.com/
36