0% found this document useful (0 votes)
45 views

A Training Report On Bascs of Python

Uploaded by

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

A Training Report On Bascs of Python

Uploaded by

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

A TRAINING REPORT ON BASCS OF PYTHON

An INTERNSHIP REPORT

Submitted to

SAVEETHA INSTITUTE OF MEDICAL AND TECHNICAL


SCIENCES

In partial fulfilment for the award of the degree of

BACHELOR OF
ENGINEERING IN
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
By
Student Name: Balraj C

Reg. No:191711065

SAVEETHA SCHOOL OF ENGINEERING


SAVEETHA INSTITUTE OF MEDICAL AND TECHNICAL
SCIENCES, CHENNAI – 602 105
MAY 2021

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

S.P. Chokkalingam K. Anitha


HEAD OF THE DEPARTMENT MENTOR
Department of Computer Science Associate Professor, Department of
Engineering Computer Science Engineering
Saveetha School of Engineering Saveetha School of Engineering
SIMATS SIMATS

2
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 equipments their relation and their
general operating principle.

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

Foreview Technologies Pvt.Ltd. is an evolutionary concern in its path to build


technically empowered personalities, which would guide the engineering community of
the country to reach new heights in their career and technological development.
Foreview Technologies Pvt.Ltd. Technical team is the core strength of the concern. We
have highly qualified experienced experts who spend their valuable time to enlighten
the students and to impart the latest and innovative technologies the world has acquired
so far. We invite the enthusiastic engineers to enhance their knowledge and to make
themselves as the perfect candidate, technical world looks for. Established in the year
2010, The Foreview Technologies Pvt Ltd in Tambaram West, Chennai is a top player
in the category Project Work for BE in the Chennai. This well-known establishment
acts as a one-stop destination servicing customers both local and from other parts of
Chennai. Over the course of its journey, this business has established a firm foothold in
it’s industry. The belief that customer satisfaction is as important as their products and
services, have helped this establishment garner a vast base of customers, which
continues to grow by the day. This business employs individuals that are dedicated
towards their respective roles and put in a lot of effort to achieve the common vision
and larger goals of the company. In the near future, this business aims to expand its line
of products and services and cater to a larger client base. In Chennai, this establishment
occupies a prominent location in Tambaram West. It is an effortless task in commuting
to this establishment as there are various modes of transport readily available. It is at
Rajagopal Mudaliyar Street, Opp to National Theatre, which makes it easy for rst-time
visitors in locating this establishment. It is known to provide top service in the
following categories: Project Work for BE, Vlsi, Real Time Project Matlab, Ieee Project
Developers, Project Work For Students, Computer Training Home Advanced Java,
Matlab Software Developers, Placement Training Programme.

4
DECLARATION BY THE CANDIDATE

I declare that the report entitled “A TRAINING REPORT ON BASICS OF PYTHON”


submitted by me for the degree of Bachelor of Engineering is the record of the
internship work carried out by me under the guidance of “FOREVIEW
TECHNOLOGIES PVT. LTD.” and this work has not formed the basis for the award
of any degree, diploma, associateship, fellowship, titled in this or any University or
other similar institution of higher learning.

SIGNATURE

(Balraj C)

(Reg. No. 191711065)

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 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.
 Python is a Beginner's Language: Python is a great language for the
beginner-level 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.

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.

1.3 Python Features


Python's features include:

 Easy-to-learn: Python has few keywords, simple structure, and a clearly


defined syntax. This allows the student to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
 Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
 Databases: Python provides interfaces to all major commercial databases.
 GUI Programming: Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
 Scalable: Python provides a better structure and support for large programs
than shell scripting.

Python has a big list of good features:

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

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 a – b = -10


operand.

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


Multiplicatio
n

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

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


and returns remainder

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


operators power 20

// Floor Division - The division of operands where 9//2 = 4 and


the result is the quotient in which the digits after 9.0//2.0 = 4.0, -
the decimal point are removed. But if one of the 11//3 = -4, -
operands is negative, the result is floored, i.e., 11.0//3 = -4.0
rounded away from zero (towards negative
infinity):
11
2.2ASSIGNMENT OPERATOR

Operator Description Example

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


to left side operand value of a + b into
c

+= Add AND It adds right operand to the left operand c += a is


and assign the result to left operand equivalent to c = c
+a

-= Subtract AND It subtracts right operand from the left c -= a is equivalent


operand and assign the result to left to c = c - a
operand

*= Multiply AND It multiplies right operand with the left c *= a is


operand and assign the result to left equivalent to c = c
operand *a

/= Divide AND It divides left operand with the right c /= a is equivalent


operand and assign the result to left to c = c / ac /= a is
operand equivalent to c = c
/a

12
2.3 IDENTITY OPERATOR

Operator Description Example

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


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

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

2.4 COMPARISON OPERATOR

Operator Description Example

& Binary Operator copies a bit to the result if it (a & b) (means 0000 1100)
AND exists in both operands

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

^ 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

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

2.6 MEMBERSHIP OPERATORS

Operator Description Example

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


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

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

** 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'

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

<= < > >= Comparison operators

<> == != Equality operators

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


**=

is is not Identity operators

in not in Membership operators

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.

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"]

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.

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 16 Membership


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

Built-in List Functions & Methods:


Python includes the following list functions −

SN Function with Description

1 cmp(list1, list2)

Compares elements of both lists.

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.

17
Python includes following list methods

SN Methods with Description

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. extend(seq)

Appends the contents of seq to list

4 list.index(obj)

Returns the lowest index in list that obj appears

5 list.insert(index, obj)

Inserts object obj into list at offset index

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

Removes and returns last object or obj from list

7 list.remove(obj)

Removes object obj from list

8 list.reverse()

Reverses objects of list in place

9 list.sort([func])

Sorts objects of list, use compare function if given

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.

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 );

tup3 = "a", "b", "c", "d";

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,);

 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]

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 −

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')

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. For example:

20
Basic Tuples 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

Built-in Tuple Functions

SN Function with Description

1 cmp(tuple1, tuple2):Compares elements of both tuples.

2 len(tuple):Gives the total length of the tuple.

3 max(tuple):Returns item from the tuple with max value.

4 min(tuple):Returns item from the tuple21with min value.


5 tuple(seq):Converts a list into tuple.

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.

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 –
22
dict['Name']: Zara
dict['Age']: 7

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 −

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

dict['Age'] = 8; # update existing entry

dict['School'] = "DPS School"; # Add new entry

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

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

Result −

dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements


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 –
23
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Age']: ", dict['Age']

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

Python includes the following dictionary functions –

SN Function with Description

1 cmp(dict1, dict2)

Compares elements of both dict.

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)

Produces a printable string representation of a dictionary

4 type(variable)

Returns the type of the passed variable. If passed variable is dictionary,


then it would return a dictionary type.

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

def functionname( parameters ):

"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

# Function definition is here 25


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")

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

I'm first call to user defined function!

Again second call to the same 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

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

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.

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 –

total = 0; # This is global variable.

# Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them."

total = arg1 + arg2; # Here total is local variable.

print "Inside the function local total : ", total

return total;

sum( 10, 20 ); 27
print "Outside the function global total : ", total

Result −

Inside the function local total : 30

Outside the function global total : 0

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
28 module, support.py
named aname.py. Here's an example of a simple
def print_func( par ):

print "Hello : ", par

return

The import Statement
The import has the following syntax:

import module1[, module2[,... moduleN]

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/Isdn.py file having function Isdn()


 Phone/G3.py file having function G3()

Now, create one more file __init__.py in Phone directory −

 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 Pots import Pots

from Isdn import Isdn

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.

# Now import your Phone Package.

import Phone

Phone.Pots()

Phone.Isdn()

Phone.G3()
30

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.

Chapter:-6 Python files I/O

This chapter covers all the basic I/O functions available in Python.

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?"


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

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

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.

32
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 built-
in open() function. This function creates a file object, which would be utilized to call
other support methods associated with it.

Syntax

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
33
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).

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")

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

print "Closed or not : ", fo.closed

print "Opening mode : ", fo.mode

print "Softspace flag : ", fo.softspace

This produces the following result −

Name of the file: foo.txt


Closed or not : False
34
Opening mode : wb
Softspace flag : 0
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.

Syntax

fileObject.close();

Example

# Open a file

fo = open("foo.txt", "wb")

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

# Close opend file

fo.close()

Result −

Name of the file: foo.txt

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
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.write( "Python is a great language.\nYeah its great!!\n");

# Close opend file

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.

Python is a great language.


Yeah its great!!

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);

print "Read String is : ", str

# Close opend file

fo.close()

This produces the following result −

Read String is : Python is

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.

The seek(offset[, from]) method changes the current file position. The offset argument


indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.

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);

print "Read String is : ", str

# Check current position

position = fo.tell();

print "Current file position : ", position

# Reposition pointer at the beginning once again

position = fo.seek(0, 0);

str = fo.read(10);

print "Again read String is : ", str

# Close opend file

fo.close()

This produces the following result −

Read String is : Python is


38
Current file position : 10
Again read String is : Python is

Renaming and Deleting Files


Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.

To use this module you need to import it first and then you can call any related
functions.

The rename() Method


The rename() method takes two arguments, the current filename and the new
filename.

Syntax

os.rename(current_file_name, new_file_name)

Example
Following is the example to rename an existing file test1.txt:

import os

# Rename a file from test1.txt to test2.txt

os.rename( "test1.txt", "test2.txt" )

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

# Delete file test2.txt

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

# Changing a directory to "/home/newdir"

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

# This would give location of the current directory

os.getcwd()

The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the
method.

Before removing a directory, all the contents in it should be removed.

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

# This would remove "/tmp/test" directory.

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 −

 File Object Methods: The file object provides functions to manipulate files.


 OS Object Methods: This provides methods to process files as well as
directories.

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 −

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 (class
variables and instance variables) and methods, accessed via dot notation.

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:

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

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

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.

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

Traceback (most recent call last):


47
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

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

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:

 Importing the API module. 49


 Acquiring a connection with the database.
 Issuing SQL statements and stored procedures.
 Closing the connection

9. INTERNSHIP REPORT

DAY1: Introduction

DAY2: Theory of PYTHON

DAY3: features of PYTHON


DAY4: Operators
DAY 5: Arithmetic operators
DAY 6: Assignment operator
DAY 7: Identity operator
DAY 8: Comparison operator
DAY 9: Logical operator

DAY 10: Membership operator

DAY 11: List

DAY 12: Tuples

DAY 13: Dictionary

DAY 14: Functions in PYTHON

DAY 15: Variables in PYTHON

DAY 16: PYTHON modules


DAY 17: PYTHON modules
DAY 18: PYTHON modules
DAY 19: PYTHON files I/0
50
DAY 20: PYTHON files I/0
DAY 22: PYTHON files I/0
DAY 23: PYTHON files I/0
DAY 24: PYTHON object oriented
DAY 25: PYTHON object oriented
DAY 26: The D-Day for the submission of course created in the past sessions and
discussing the scope of course with the possible outcomes. The session of 160mins is
held.
DAY 27: Project evaluation of the interns with individual discussion of member
and the possible application area of project.
DAY 28: The Day 28 started with the presentation of the selected projects live with
the interns who has different innovative ideas and activities held up for the project.
The session lasted about 280mins in the afternoon.
DAY 29: Project presentation of interns to the colleagues with improved segments
by discussing them in previous session.
DAY 30: Project presentation of interns to the colleagues with improved segments
by discussing them in previous session. With the completion of project presentation,
signing OFF from the internship with issuing of certificate.

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:

 It is Free (as in both cost and source code).

 It is trivial to install on a Windows PC allowing students to take


their interest further. For many the hurdle of installing a Pascal
or C compiler on a Windows machine is either too expensive or
too complicated;

 It is a flexible tool that allows both the teaching of traditional


procedural programming and modern OOP; It can be used to
teach a large number of transferable skills;

 It is a real-world programming language that can be and is used


in academia and the commercial world;

 It appears to be quicker to learn and, in combination with its


many libraries, this offers the possibility of more rapid student
development allowing the course to be made more challenging
and varied;

and most importantly, its clean syntax offers increased understanding and
enjoyment for students

52
11. CERTIFICATE

53

You might also like