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

Python Lab Manual-Final - pdf.24060

python lab manual-final.pdf.24060
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)
52 views

Python Lab Manual-Final - pdf.24060

python lab manual-final.pdf.24060
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/ 41

HIT/

CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s

Hi-Tech Institute of Technology,

Aurangabad
A Pioneer to Shape Global
Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496

DEPARTMENT: COMPUTER SCIENCE & ENGINEERING


DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: Introduction to python programming. Run
simple hello
program.
EXPERIMENT NO.: 02 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III
Aim: Introduction to python programming. Run
simple helloprogram.
Hardware Requirement:

Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”


LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:

Python is a general-purpose interpreted,


interactive, object-oriented, and high-level
programming language. It was createdby Guido van
Rossum during 1985- 1990. Like Perl, Python source
code is also available under the GNU General Public
License (GPL). This tutorial gives enough
understanding on Python programming language.

History of Python
Python was developed by Guido van Rossum in the
late eightiesand early nineties at the National
Research Institute for Mathematics and Computer
Science in the Netherlands.
Python is derived from many other languages,
including ABC,Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting
languages.
Python is copyrighted. Like Perl, Python source code
is nowavailable 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 rolein directing its progress.

First Python Program:


• Open notepad and type
following programPrint (“Hello
World”)
• Save above program with name.py
• Open command prompt and change path to
python programlocation
• Type “python name.py” (without quotes) to run the
program.

Conclusion:

HIT/
CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s

Hi-Tech Institute of Technology,

Aurangabad
A Pioneer to Shape Global
Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496

DEPARTMENT: COMPUTER SCIENCE & ENGINEERING


DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: To study and implement variables, operations
in
python.
EXPERIMENT NO.: 03 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III
Aim: To study and implement variables, operations in
python.

Hardware Requirement:
Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”
LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:

Variable in Python
A Python variable is a reserved memory location to
store values. In other words, a variable in a python
program givesdata to the computer for processing.
Every value in Python has a datatype. Different data
types inPython are Numbers, List, Tuple, Strings,
Dictionary, etc.
Variables can be declared by any name or even
alphabets likea, aa, abc, etc.
How to Declare and use a Variable
Let see an example. We will declare variable "a" and
print it.a=100
print a
Python 1 Example
# Declare a variable and
initialize itf = 0
print f
# re-declaring the variable works

f
=
'g
ur
u9
9'
pr
in
t
f
Python 2 Example
# Declare a variable and
initialize itf = 0
print(f)
# re-declaring the
variable worksf =
'guru99'
print(f)

Python Arithmetic Operators


Assume variable a holds 10 and variable b holds 20, then –
Operator Description Example
+ Adds values on either side of the a + b = 30
Addition operator.
- Subtracts right hand operand a – b = 10
Subtract
fromleft hand operand.
ion

* Multiplies values on either side a * b =


Multipli ofthe operator 200
cation
/ Divides left hand operand by right b / a = 2
Division hand operand
% Divides left hand operand by right b % a = 0
Modulus hand operand and returns remainder
** Performs exponential a**b =10
Exponent (power)calculation on to the
operators power 20
// Floor Division - The division of 9//2 = 4
operands where the result is the and
quotient in which the digits 9.0//2.0
afterthe decimal point are = 4.0,
removed. But if one of the operands 11//3 =
is negative, the result is floored, -4, -
i.e., rounded away from zero 11.0//3
(towards = -4.0
negative infinity) −

Python Comparison Operators


These operators compare the values on either sides
of them anddecide the relation among them. They are
also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then –
Operator Description Example
== If the values of two (a == b) is
operandsare equal, then the nottrue.
condition
becomes true.
!= If values of two operands (a != b)
arenot equal, then condition istrue.
becomes true.
<> If values of two operands (a <> b) is
arenot equal, then condition true. This
becomes true. issimilar to
!= operator.
> If the value of left operand (a > b) is
is greater than the value of nottrue.
right operand, then
condition
becomes true.
< If the value of left operand (a < b)
is less than the value of istrue.
right operand, then
condition
becomes true.
>= If the value of left (a >= b) is
operandis greater than or nottrue.
equal to the value of right
operand,
then condition becomes true.
<= If the value of left (a <= b)
operand is less than or istrue.
equal to the value of right
operand, then
condition becomes true.

Python Assignment Operators


Assume variable a holds 10 and variable b holds 20, then –
Operator Description Example
= Assigns values from right c = a + b
side operands to left assignsvalue of a
side + b
operand into c
+= Add AND It adds right operand to c += a is
the left operand and equivalent to c
assign the result to =c + a
left
operand
-= Subtract It subtracts right c -= a is
AND operandfrom the left equivalent to c
operand and assign the =c - a
result to left
operand
*= Multiply It multiplies right c *= a is
AND operand with the left equivalent
operand and assign the to c = c *
result to left operand a
/= Divide It divides left operand c /= a is
AND with the right operand equivalent to c
andassign the result to =c / ac /= a is
left operand equivalent to c =
c / a
%= Modulus It takes modulus using c %= a is
AND twooperands and assign equivalent to c
the =
result to left operand c % a
**= Performs exponential c **= a is
Exponent (power) calculation on equivalent to c
AND operators and assign =c ** a
value
to the left operand
//= Floor It performs floor c //= a is
division equivalent to c
Division
on operators and assign
=c // a
value to the left operand
Sample Program Code:
• WAP to declare variables and display types of
respectivevariables
Program to print type of
given variablea = 5
print(a, "is of
type", type(a))a =
2.0
print(a, "is of
type", type(a))a =
1+2j
print(a, "is complex number?",
isinstance(1+2j,complex))Output:
5 is of type<class ‘int’>
2.0 is of type
<class ‘float’>
(1+2j) is complex
number? True
• Write a program for addition of two numbers.

Num1= 2.5
Num2= 3.1
#add
two
number
s
Sum=nu
m1+num
2
#displ
ay the
sum
Print(“the sum is ”, sum)
Extra Programs For Practice:
• Write a program to find square of number.
• Write a program to find area of square.
• Write a program to find area of rectangle.

• Program to Solve Quadratic Equation

Conclusion:

HIT/
CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s

Hi-Tech Institute of Technology,

Aurangabad

A Pioneer to Shape Global


Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496
DEPARTMENT: COMPUTER SCIENCE & ENGINEERING
DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: To study and implement python strings.
EXPERIMENT NO.: 04 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III
Aim: To study and implement python strings.

Hardware Requirement:
Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”
LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:
String Literals- String literals in python are
surrounded byeither single quotation marks, or
double quotation marks. 'hello' is the same as
"hello".
You can display a string literal with the print() function:
Formatting of Strings
Strings in Python can be formatted with the use of
format() method which is very versatile and powerful
tool for formatting of Strings. Format method in
String contains curlybraces {} as placeholders
which can hold arguments according to position or
keyword to specify the order.
Exa
mpl
e
Def
aul
t
ord
er

String1 = "{} {} {}".format('Wel', 'Come',

'Pyhton')print("Print String in default

order: ") print(String1)

Positional Formatting

String1 = "{1} {0} {2}".format('Wel', 'Come',

'Pyhton')print("\nPrint String in Positional

order: ") print(String1)

Keyword Formatting

String1 = "{w} {c} {p}".format(w = 'Wel', f =


‘come', l ='python')

print("\nPrint String in order of Keywords: ")

print(String1)

String Concatenation
To concatenate, or combine, two strings you can use
the +operator.

Sample Program Code:

Concatenate string and integer

a="hello I am
in class"b=12
print(a
+
str(b))
or
print("{}{}".format(a,b))

Extra Programs For Practice:

Print student name, subject NAME OR code and obtained marks

Conclusion:

HIT/
CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s

Hi-Tech Institute of Technology,


Aurangabad
A Pioneer to Shape Global
Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496

DEPARTMENT: COMPUTER SCIENCE & ENGINEERING


DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: To study and implement List, Tuple.
EXPERIMENT NO.: 05 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III
Aim: To study and implement List, Tuple.

Hardware Requirement:
Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”
LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:

Python Collections (Arrays)


There are four collection data types in the Python
programminglanguage:
• List is a collection which is ordered and
changeable.Allows duplicate members.
• Tuple is a collection which is ordered and
unchangeable.Allows duplicate members.
• Set is a collection which is unordered and
unindexed. Noduplicate members.
• Dictionary is a collection which is unordered,
changeableand indexed. No duplicate members.
When choosing a collection type, it is useful to
understand the properties of that type. Choosing
the right type for a particular data set could mean
retention of meaning, and, itcould mean an increase
in efficiency or security.

List
A list is a collection which is ordered and
changeable. InPython lists are written with square
brackets.

Sample Program Code:


Write a Python program to sum all the items in a list.

total = 0

creating

a list

list1 =

[1,3,4,5,

2]

# Iterate each

element in list # and

add them in variale

totalfor ele in

range(0,len(list1)):
total = total +

list1[ele]# printing

total value

print("Sum of all elements in given list: ", total)

Extra Programs For Practice:

Write a Python program to add an item in a tuple.

Conclusion:

HIT/
CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
Hi-Tech Institute of Technology,

Aurangabad
A Pioneer to Shape Global
Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496

DEPARTMENT: COMPUTER SCIENCE & ENGINEERING


DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: To study and implement Set, Dictionaries.
EXPERIMENT NO.: 06 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III
Aim: To study and implement Set, Dictionaries.
Hardware Requirement:
Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”
LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:

Set
A set is a collection which is unordered and
unindexed. InPython sets are written with curly
brackets.

Extra Programs For Practice:

Write a Python program to add member(s) in a set.


Write a Python script to check if a given key
already existsin a dictionary.

Conclusion:

HIT/
CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
Hi-Tech Institute of Technology,

Aurangabad
A Pioneer to Shape Global
Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496

DEPARTMENT: COMPUTER SCIENCE & ENGINEERING


DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: To study and implement loops python.
structure.
EXPERIMENT NO.: 07 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III

Aim: To study and implement loops python.


Hardware Requirement:
Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”
LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:
Python Loop
In general, statements are executed sequentially:
The firststatement in a function is executed first,
followed by the second, and so on. There may be a
situation when you need toexecute a block of code
several number of times.
Programming languages provide various control
structures thatallow for more complicated execution
paths.
A loop statement allows us to execute a statement
or group ofstatements multiple times. Python
programming language provides following types of
loops to handle looping requirements.

1 while loop
Repeats a statement or group of statements while a
given condition is TRUE. It tests the condition
before executing the loop body.

2 for loop
Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.

3 nested loops
You can use one or more loop inside any another
while, for or do..while loop.

Loop Control Statements


Loop control statements change execution from its
normal sequence. When execution leaves a scope, all
automatic objectsthat were created in that scope are
destroyed.
Python supports the following control statements.
Click the following links to check their detail.
Let us go through theloop control statements
briefly

1 break statement
Terminates the loop statement and transfers
executionto the statement immediately following the
loop.

2 continue statement
Causes the loop to skip the remainder of its body and
immediately retest its condition prior to
reiterating.

3 pass statement
The pass statement in Python is used when a
statementis required syntactically but you do not
want any
command or code to execute.

Sample Program Code:


Write a program to display even Nos. from 1 to 10.

Using While Loop


number = 1
while number
<= 10:
if(number
% 2 == 0):
print
(number)
number =
number +
1

Using FOR loop

start, end = 4, 10
for num in range(start, end + 1):
if num % 2 == 0:
print(num)

Extra Programs For Practice:

Write a program in Python, A library charges a fine for


every book returned late. For first 5 days the fine is
50 paisa, for 6-10 daysfine is one rupee and above 10
days fine is 5 rupees. If you returnthe book after 30
days your membership will be cancelled. Write a program
to accept the number of days the member is late to
return the book and display the fine or the appropriate
message Program:

Conclusion:

HIT/
CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s

Hi-Tech Institute of Technology,

Aurangabad

A Pioneer to Shape Global


Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496

DEPARTMENT: COMPUTER SCIENCE & ENGINEERING


DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: To study and implement basic inputs/outputs
and
exception handling.
EXPERIMENT NO.: 08 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III
Aim: To study and implement basic inputs/outputs and
exceptionhandling.
Hardware Requirement:

Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”


LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:
We use the print() function to output data to the
standardoutput device (screen).
We can also output data to a file, but this will be
discussedlater. An example use is given below.
print('This sentence is output to the screen')

# Output: This sentence is output to


the screena = 5
print('The value of
a is', a)# Output:
The value of a is 5

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 expressionsyou pass into a string
and writes the result to standard output as
follows −
Example

print "Python is really a great language,",


"isn't it?"output
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 standardinput and returns it as a string
(removing the trailing newline).
Example
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 outputis like this –

Output

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 expressionand returns the evaluated
result to you.
Example
str = input("Enter your
input: ")print
"Received input is : ",
str

This would produce the following result against the


enteredinput –
Output

Enter your input: [x*5 for x in


range(2,10,2)]Recieved input is :
[10, 20, 30, 40]

Exception Handling

When an error occurs, or exception as we call it,


Python willnormally stop and generate an error
message.
These exceptions can be handled using the try

statement:Syntax:

try :
#statements in
try blockexcept :
#executed when error in try block

Many Exceptions

You can define as many exception blocks as you want,


e.g. if you want to execute a special block of code
for a special kindof error:

Else
You can use the else keyword to define a block of
code to beexecuted if no errors were raised:
Syntax:
try:
#statements in
try blockexcept:
#executed when error in
try blockelse:
#executed if try block is
error-freefinally:
#executed irrespective of exception occured or not

Finally

Finally
The finally block, if specified, will be executed
regardlessif the try block raises an error or not.

Sample Program Code:


Write a Python program to calculate area of circle by
takinginputs from user.

PI = 3.14

r = float(input('Enter the radius of the

circle :'))area = PI * r * r

print("Area of the circle is : %.2f" %area)

Write a program to take a number from user and


accept numberonly when it is in given range

try:

x=int(input('Enter a number upto 100: '))

if x > 100:

raise ValueError(x)

except ValueError:
print(x, "is out of

allowed range")else:

print(x, "is within the allowed range")

Extra Programs For Practice:


Write a program which accepts two numbers from the
user and performs their division and gives error
when denominator is zero.

Conclusion:

HIT/
CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s

Hi-Tech Institute of Technology,

Aurangabad
A Pioneer to Shape Global
Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496

DEPARTMENT: COMPUTER SCIENCE & ENGINEERING


DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: To study and implement python functions.
EXPERIMENT NO.: 09 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III
Aim: To study and implement python functions.
Hardware Requirement:
Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”
LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:
A function is a block of code which only runs when
it iscalled. You can pass data, known as
parameters, into a function. A function can return
data as a result.
Creating a Function
In Python a function is defined using the
def keyword:def my_function(): print("Hello
from a function") Calling a Function
To call a function, use the function name followed by
parenthesis:
def my_function(): print("Hello from a function")
my_function()
Parameters
Information can be passed to functions as
parameter. Parameters are specified after the
function name, inside the parentheses. You can add
as many parameters as you want, justseparate them
with a comma.The following example has a function
with one parameter (fname). When the function is
called, we pass along a first name, which is used
inside the function to print the full name:

def my_function(fname): print(fname + "


Refsnes")my_function("Emil")
my_function("Tobias")

my_function("Linus") Default Parameter Value

The following example shows how to use a default


parameter value. If we call the function without
parameter, it uses thedefault value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden") my_function("India")
my_function()my_function("Brazil")
You can send any data types of parameter to a
function (string, number, list, dictionary etc.),
and it will be treated as the same data type inside
the function. E.g. if yousend a List as a parameter,
it will still be a List when it reaches the
function:

def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana",
"cherry"]my_function(fruits)
Return Values
To let a function return a value, use the return
statement:def my_function(x):
return 5 * x
print(my_function(3)) print(my_function(5))
print(my_function(9)) Recursion

Python also accepts function recursion, which means a


defined function can call itself. Recursion is a
common mathematical and programming concept. It means
that a function calls itself.This has the benefit of
meaning that you can loop through data to reach a
result.

The developer should be very careful with recursion


as it canbe quite easy to slip into writing a
function which never terminates, or one that uses
excess amounts of memory or

processor power. However, when written correctly


recursion canbe a very efficient and
mathematicallyelegant approach to programming.

Sample Program Code:


• def add():
x

1
0

y
=
2
0
z=x+y
print("value of
z is:",z)add()
• def
add
(x,
y):
add
iti
on
=x+
y
print("addition is",
addition)add(5,7)

Extra Programs For Practice:


Write a Python function to calculate the factorial of a
number

Conclusion:

HIT/
CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
Hi-Tech Institute of Technology,

Aurangabad

A Pioneer to Shape Global


Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496

DEPARTMENT: COMPUTER SCIENCE & ENGINEERING


DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: To study and implement file handling in
python.
EXPERIMENT NO.: 10 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III
Aim: To study and implement file handling in python.

Hardware Requirement:
Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”
LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:

The key function for working with files in


Python isthe open() function.
The open() function takes two parameters; filename,
and mode. There are four different methods (modes)
for opening a file: "r" - Read - Default value. Opens
a file for reading, error ifthe file does not exist
"a" - Append - Opens a file for appending, creates

the file ifit does not exist


"w" - Write - Opens a file for writing, creates the

file if itdoes not exist


"x" - Create - Creates the specified file, returns an

error ifthe file exists


In addition you can specify if the file should be
handled asbinary or text mode
"t" - Text - Default value. Text mode

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

Syntax
To open a file for reading it is enough to specify
the name ofthe file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the
default values,you do not need to specify them.

Open a File on the Server


Assume we have the following file, located in the
same folderas Python:
demofile.txt
Hello! Welcome to demofile.txt This file is for
testingpurposes. Good Luck!
To open the file, use the built-in open() function.
The open() function returns a file object, which has
a read()method for reading the content of the file:
Example
f = open("demofile.txt", "r") print(f.read())
Read Only Parts of the File
By default the read() method returns the whole
text, but youcan also specify how many characters
you want to return: Example
Return the 5 first characters of
the file:f
=open("demofile.txt","r")print(f.
read(5))

Read Lines
You can return one line by using the readline()
method:Example
Read one line of the file:
f
=open("demofile.t
xt","r")
print(f.readline(
))
By calling readline() two times, you can read the two
firstlines:
Example

Read two lines of the file:


f
=open("demofile.t
xt","r")
print(f.readline(
))
print(f.readline(
))
By looping through the lines of the file, you
can read thewhole file, line by line:
Example
Loop through the file line by line:
f =open("demofile.txt","r")forxinf:print(x)

Close Files
It is a good practice to always close the file when
you aredone with it.
Example
Close the file when you are
finish with it:f
=open("demofile.txt","r")
print(f.readline())
f.close()
Write to an Existing File
To write to an existing file, you must add a
parameter to theopen() function
"a" - Append - will append to the end
of the file"w"-Write -will overwrite
any existing content Example
Open the
file "demofile2.txt" and append content to
the file:f =open("demofile2.txt","a")
f.write("Now the file has more
content!")f.close()
open and read the file after the appending:
f =
open("demofile2.txt
", "r")
print(f.read())
Example
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the
content!")

f.close()
open and read the file after the
appending:f =
open("demofile3.txt", "r")
print(f.read())

Create a New File


To create a new file in Python, use the open()
method, withone of the following parameters:
"x" - Create - will create a file, returns an
error if thefile exist
"a" - Append - will create a file if the specified
file doesnot exist
"w" - Write - will create a file if the specified
file doesnot exist
Example
Create a file called "myfile.txt":
f =open("myfile.txt","x")
Result: a new empty file is created!

Sample Program Code:


Write a Python program to read an entire text file

Extra Programs For Practice:


Conclusion:

HIT/
CSE/LOM/
S
i
n
c
e

2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s

Hi-Tech Institute of Technology,

Aurangabad
A Pioneer to Shape Global
Technologies
Approved By AICTE, DTE Govt. of Maharashtra & Affiliated to Dr. Babasaheb Ambedkar Technological University,
Lonere, Raigad
P-119, Bajajnagar, MIDC Waluj, Aurangabad, Maharashtra, India - 431136P: (0240) 2552240, 2553495,
2553496

DEPARTMENT: COMPUTER SCIENCE & ENGINEERING


DEPARTMENT
PRACTICAL EXPERIMENT
INSTRUCTION SHEET
EXPERIMENT TITLE: To study classes and objects in python
EXPERIMENT NO.: 11 SUBJECT: PYTHON PROGRAMMING
CLASS:SY CSE SEMESTER: III
Aim: To study classes and objects in python
Hardware Requirement:
Intel P-IV 2.70 GHz Processor, 1 GB RAM, 256 GB HDD, 15”
LCD
Monitor, Keyboard, Mouse.
Software Requirement:
UBUNTU OS, GCC COMPILER, TERMINAL.
Theory:
Python is an object oriented programming language.
Almost everything in Python is an object, with its
propertiesand methods.
A Class is like an object constructor, or a
"blueprint" forcreating objects.
Create a Class
To create a class, use the
keyword class:Example
Create a class named MyClass, with a
property named x:class
MyClass:
x =5

Create Object
Now we can use the class named myClass to create
objects:Example
Create an object named p1, and print the
value of x:p1 = MyClass()
print(p1.x)

The init () Function


The examples above are classes and objects in
their simplestform, and are not really useful in
real life applications.
To understand the meaning of classes we have to
understand thebuilt-in init () function.
All classes have a function called init (), which
is alwaysexecuted when the class is being initiated.
Use the init () function to assign values to object
properties, or other operations that are necessary
to do whenthe object is being created:
Example
Create a class named Person, use the init ()
function toassign values for name and age:

classPerson:
def init (self, name, age):
self.n
ame =
name
self.a
ge =
age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)

Object Methods
Objects can also contain methods. Methods in objects
arefunctions that belong to the object.

class Person:
def init (self, name,
age):self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 =
Person("John"
, 36)
p1.myfunc()
Sample Program Code:

• Write a Python class to reverse a string


word by word.Input string : 'hello .py'
Expected Output : '.py hello'
class py_solution:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))

print(py_solution().reverse_words('hello .py'))

• Write a python class to perform addition and


subtractionoperations.
class operation:
def init (self, a, b):

s
e
l
f
.
a
=
a

s
e
l
f
.
b
=
b
def add(self):
c=self.a+self
.b
print("additi
on= ", c)
def
sub(s
elf):
d=sel
f.a-
self.
b
print("subtrac
tion= ",d)
a=int(input(“Enter
No.”)
b=int(input(“Enter
No.”)
ob=operation(a,b)
ob.add()
ob.sub()

Extra Programs For Practice:

Write Python Program to Create a Class which


Performs BasicCalculator Operations

Conclusion:

You might also like