Python Lab Manual-Final - pdf.24060
Python Lab Manual-Final - pdf.24060
CSE/LOM/
S
i
n
c
e
2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
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
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).
Conclusion:
HIT/
CSE/LOM/
S
i
n
c
e
2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
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
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)
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.
Conclusion:
HIT/
CSE/LOM/
S
i
n
c
e
2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
Aurangabad
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
Positional Formatting
Keyword Formatting
print(String1)
String Concatenation
To concatenate, or combine, two strings you can use
the +operator.
a="hello I am
in class"b=12
print(a
+
str(b))
or
print("{}{}".format(a,b))
Conclusion:
HIT/
CSE/LOM/
S
i
n
c
e
2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
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:
List
A list is a collection which is ordered and
changeable. InPython lists are written with square
brackets.
total = 0
creating
a list
list1 =
[1,3,4,5,
2]
# Iterate each
totalfor ele in
range(0,len(list1)):
total = total +
list1[ele]# printing
total value
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
Set
A set is a collection which is unordered and
unindexed. InPython sets are written with curly
brackets.
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
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.
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.
start, end = 4, 10
for num in range(start, end + 1):
if num % 2 == 0:
print(num)
Conclusion:
HIT/
CSE/LOM/
S
i
n
c
e
2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
Aurangabad
Output
Exception Handling
statement:Syntax:
try :
#statements in
try blockexcept :
#executed when error in try block
Many Exceptions
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.
PI = 3.14
circle :'))area = PI * r * r
try:
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of
allowed range")else:
Conclusion:
HIT/
CSE/LOM/
S
i
n
c
e
2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
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
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
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)
Conclusion:
HIT/
CSE/LOM/
S
i
n
c
e
2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
Hi-Tech Institute of Technology,
Aurangabad
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:
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.
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
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())
HIT/
CSE/LOM/
S
i
n
c
e
2
0
0
1
Bhartiya Gramin Punarrachna Sanstha’s
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
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)
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:
print(py_solution().reverse_words('hello .py'))
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()
Conclusion: