A Training Report On Bascs of Python
A Training Report On Bascs of Python
An INTERNSHIP REPORT
Submitted to
BACHELOR OF
ENGINEERING IN
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
By
Student Name: Balraj C
Reg. No:191711065
1
SAVEETHA SCHOOL OF ENGINEERING
SAVEETHA INSTITUTE OF MEDICAL AND TECHNICAL
SCIENCES, CHENNAI – 602 105
BONAFIDE CERTIFICATE
Certified that this Final year project report is done is the bonafide work of BALRAJ
C (Reg.No.191711065) who carried out the project under my guidance
SIGNATURE SIGNATURE
2
ABSTRACT
Python, an interpreted language which was developed 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 four weeks 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.
3
COMPANY PROFILE
4
DECLARATION BY THE CANDIDATE
SIGNATURE
(Balraj C)
5
ACKNOWLEDGEMENT
This internship work would not have been possible without the contribution of many
people. It gives me immense pleasure to express my profound gratitude to our
honourable Chancellor Dr. N. M. Veeraiyan, Saveetha University, for their visionary
thoughts and support. I am indebted to extend my gratitude to our Director madam
Mrs. Ramya Deepak, Saveetha School of Engineering, for facilitating us all the
facilities and extended support to gain valuable education and learning experience. I
register my special thanks to Dr. B. Ramesh, Principal, Saveetha School of
Engineering and S. P. CHOKKALINGAM, HOD, Department of Computer Science
Engineering, for the support given to me in the successful conduct of this internship. I
wish to express my sincere gratitude to Chancellor of PYTHON for helping me
throughout my project. I am grateful to project Coordinators, The Internal Members
and the entire faculty of the Department of Computer Science Engineering, for their
constructive criticisms and valuable suggestions which have been a rich source to
improve the quality of this work.
6
TABLE OF CONTENT
Bonafide.Certificate.......................................................................................2
Abstract..........................................................................................................3
Company Profile............................................................................................4
Declaration by the candidate........................................................................5
Acknowledgement.........................................................................................6
Table Of contents..........................................................................................7
1. INTRODUCTION.........................................................................................8
1.1. PYTHON.................................................................................................8
1.2. History of PYTHON...............................................................................8
1.3. Features................................................................................................9
2. OPERATORS........................................................................................................11
3.COLLECTTION IN PYTHON.....................................................................16
4. FUNCTIONS IN PYTHON.........................................................................25
5. PYTHON MODULES…………………………………………………………....28
6. PYTHON FILES I/O……………………………………………………………...31
7. PYTHON OBJECT ORIENTED………………………………………………..43
8. PYTHON MYSQL DATABASE ACCESS…………………………………….49
9. INTERNSHIP REPORT.............................................................................51
10. CONCLUSION..........................................................................................52
11. INTERNSHIP LETTER.............................................................................53
7
Chapter-1 Introduction
1.1 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.
8
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.
9
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
IT supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
10
Chapter-2 Operators
12
2.3 IDENTITY OPERATOR
is not Evaluates to false if the variables on either side of the operator x is not y, here is
point to the same object and true otherwise. not results in 1 if
id(x) is not equal to
id(y
& Binary Operator copies a bit to the result if it (a & b) (means 0000 1100)
AND exists in both operands
^ Binary XOR it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
~ Binary Ones It is unary and has effect of 'flipping' bits. (~a ) = -61 (means 1100 0011 in 2's
Complement complement form due to a signed
binary number.
13
2.5 LOGICAL OPERATOR
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 condition (a or b) is true.
becomes true.
not Logical Used to reverse the logical state of its operand. Not(a and b) is
NOT false.
not in Evaluates to true if it does not finds a variable in the specified x not in y, here
sequence and false otherwise. not in results in a
1 if x is not a
member of
sequence y.
14
Python Operators Precedence
Operator Description
~+- Complement, unary plus and minus (method names for the last two
are +@ and -@)
15
Chapter-03 Collecttion 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.
list2 = [1, 2, 3, 4, 5 ];
1 cmp(list1, list2)
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
17
Python includes following list methods
1 list.append(obj)
2 list.count(obj)
3 list. extend(seq)
4 list.index(obj)
5 list.insert(index, obj)
6 list.pop(obj=list[-1])
7 list.remove(obj)
8 list.reverse()
9 list.sort([func])
18
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.
tup2 = (1, 2, 3, 4, 5 );
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though
there is only one value −
tup1 = (50,);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
19
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 −
20
Basic Tuples Operations:
3.2 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 –
22
dict['Name']: Zara
dict['Age']: 7
Updating Dictionary
Result −
dict['Age']: 8
dict['School']: DPS School
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
3 str(dict)
4 type(variable)
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.
"function_docstring"
function_suite
return [expression]
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
−
print str
return;
Function Arguments
You can call a function by using the following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
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
26
particular identifier. There are two basic scopes of variables in Python −
Global variables Local variables
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 –
return total;
sum( 10, 20 ); 27
print "Outside the function global total : ", total
Result −
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
28 module, support.py
named aname.py. Here's an example of a simple
def print_func( par ):
return
The import Statement
The import has the following syntax:
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.
Packages in Python
Consider a file Pots.py available in Phone directory. This file has following line of
source code −
def Pots(): 29
print "I'm Pots Phone"
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 −
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available when
you import the Phone package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
30
RESULT:
I'm Pots Phone
I'm 3G 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.
This chapter covers all the basic I/O functions available in Python.
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).
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 −
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.
32
str = input("Enter your input: ");
print "Received input is : ", str
This would produce the following result against the entered input −
The open Function
Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be utilized to call
other support methods associated with it.
Syntax
The file Object Attributes
Once a file is opened and you have one file object, you can get various information
related to that file.
Example
# Open a file
fo = open("foo.txt", "wb")
Syntax
fileObject.close();
Example
# Open a file
fo = open("foo.txt", "wb")
fo.close()
Result −
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
35Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file. Example
# Open a file
fo = open("foo.txt", "wb")
fo.close()
The above method would create foo.txt file and would write given content in that file
and finally it would close that file. If you would open this file, it would have following
content.
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]);
36
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.
Example
Let's take a file foo.txt, which we created above.
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
fo.close()
File Positions
The tell() method tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file.
37
If from is set to 0, it means use the beginning of the file as the reference position and
1 means use the current position as the reference position and if it is set to 2 then the
end of the file would be taken as the reference position.
Example
Let us take a file foo.txt, which we created above.
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
position = fo.tell();
str = fo.read(10);
fo.close()
To use this module you need to import it first and then you can call any related
functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt:
import os
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to
39
be deleted as the argument.
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
os.remove("text2.txt")
Directories in Python
All files are contained within various directories, and Python has no problem
handling these too. The os module has several methods that help you create, remove,
and change directories.
The mkdir() Method
You can use the mkdir() method of the os module to create directories in the current
directory. You need to supply an argument to this method which contains the name of
the directory to be created.
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory −
#!/usr/bin/python
40
import os
# Create a directory "test"
os.mkdir("test")
The chdir() Method
You can use the chdir() method to change the current directory. The chdir() method
takes an argument, which is the name of the directory that you want to make the
current directory.
Syntax
os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os
os.chdir("/home/newdir")
The getcwd() Method
The getcwd() method displays the current working directory.
Syntax
os.getcwd()
41
Example
Following is the example to give current directory −
import os
os.getcwd()
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the
method.
Syntax:
os.rmdir('dirname')
Example
Following is the example to remove "/tmp/test" directory. It is required to give fully
qualified name of the directory, otherwise it would search for that directory in the
current directory.
import os
os.rmdir( "/tmp/test" )
42
File & Directory Related Methods
There are three important sources, which provide a wide range of utility methods to
handle and manipulate files & directories on Windows and Unix operating systems.
They are as follows −
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.
43
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.
Creating Classes
The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon44as follows −
class ClassName:
class_suite
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_suite
45
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.
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.
Example
class Vector:
self.a = a
self.b = b
def __str__(self):
def __add__(self,other):
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2 46
When the above code is executed, it produces the following result −
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
Result −
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
48
Chapter:-8 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
Microsoft SQL Server 2000
Informix
Interbase
The DB API provides a minimal standard for working with databases using Python
structures and syntax wherever possible. This API includes the following:
9. INTERNSHIP REPORT
DAY1: Introduction
51
10. CONCLUSION
I believe the trial has shown conclusively that it is both possible and desirable to
use Python as the principal teaching language:
and most importantly, its clean syntax offers increased understanding and
enjoyment for students
52
11. CERTIFICATE
53