PPL Lab Manual 2022-23
PPL Lab Manual 2022-23
LIST OF EXPERIMENT
8. Program to demonstrate Data Series and Data Frames using Pandas in python.
9. To create GUI in python containing widgets such as labels, textbox, radio, checkboxes and
custom dialog boxes.
1
EXPERIMENT NO : 1
Theory:
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be
highly readable. It uses English key-words frequently whereas other languages use punctuation, and it has
fewer syntactic constructions than other languages.
Python is a MUST for students and working professionals to become a great Software Engineer specially when
they are working in Web Development Domain. Listed down are some of the key advantages of learning
Python:
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 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.
Types of Operator
● Arithmetic Operators
● Comparison (Relational) Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
2
● Membership Operators
● Identity Operators
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
// Floor Division - The division of operands where the result is the 9//2 = 4 and
quotient in which the digits after the decimal point are removed. But 9.0//2.0 =
if one of the operands is negative, the result is floored, i.e., rounded 4.0, -11//3 =
away from zero (towards negative infinity) − -4, -11.0//3
= -4.0
3
Code & Output:
Hello World using Python.
print ("Hello, Python!");
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
c=a%b
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
Output:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
4
EXPERIMENT NO : 2
Theory:
In Python, Strings are arrays of bytes representing Unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Creating a String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
5
List = [10, 20, 30]
print("\nList of numbers: ")
print(List)
Output :
String with the use of Single Quotes:
Welcome to the world of python
List of numbers:
[10, 20, 30]
Empty Dictionary:
{}
6
EXPERIMENT NO : 3
Theory:
Decision making is anticipation of conditions occurring while execution of the program and specifying actions
taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to
determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the programming
languages −
Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or
7
null, then it is assumed as FALSE value.
Python programming language provides the following types of decision making statements.
1 if statements
2 if...else statements
An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
In general, statements are executed sequentially: The first statement in a function is executed first, followed
by the second, and so on. There may be a situation when you need to execute a block of code several number
of times.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement −
8
Python programming language provides the 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
9
You can use one or more loop inside any another while, for or do..while loop.
statement(s)
var1 = 100
if var1:
print var1
var2 = 0
if var2:
print var2
Output:
1 - Got a true expression value
100
Good bye!
10
if expression:
statement(s)
else:
statement(s)
var1 = 100
if var1:
print var1
else:
print var1
var2 = 0
if var2:
print var2
else:
print var2
Output:
1 - Got a true expression value
100
11
Good bye!
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
var = 100
if var == 150:
else:
12
print "Could not find true expression"
Output:
Expression value is less than 200
Which is 100
Good bye!
statement(s)
count = 0
count = count + 1
Output:
The count is: 0
13
The count is: 8
Good bye!
statements(s)
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
while expression:
14
statement(s)
statement(s)
i=2
j=2
if not(i%j): break
j=j+1
i=i+1
Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
15
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!
CONCLUSION : Hence we are successfully implemented to implement conditional statements and loop
statements in python.
16
EXPERIMENT NO : 4
Creating a Function
Example
def my_function():
Calling a Function
Example
def my_function():
my_function()
Arguments
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as
you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called, we pass along a
17
first name, which is used inside the function to print the full name:
Example
def my_function(fname):
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into a
function.
A parameter is the variable listed inside the parentheses in the function definition.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your function
expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
Example
my_function("Emil", "Refsnes")
18
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function, add a * before the parameter
name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
Example
def my_function(*kids):
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
Example
my_function("Sweden")
19
my_function("India")
my_function()
my_function("Brazil")
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
CONCLUSION : Hence we are successfully implemented to study and implement functions in python.
20
EXPERIMENT NO : 5
Python Classes/Objects
Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of
the class. The attributes are data members (class variables and instance variables) and methods, accessed via
dot notation.
Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class
but outside any of the class's methods. Class variables are not used as frequently as instance variables are.
Data member − A class variable or instance variable that holds data associated with a class and its objects.
Function overloading − The assignment of more than one behavior to a particular function. The operation
performed varies by the types of objects or arguments involved.
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.
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.
21
CLASS
Create a Class
Example
OBJECT
Create Object
Example
The examples above are classes and objects in their simplest form, and are not really useful in real life
applications.
To understand the meaning of classes we have to understand the built-in __init__() function. All classes have
a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function
to assign values to object properties, or other operations that are necessary to do when the object is being
created:
Example
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
22
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used to create a new object.
CONSTRUCTOR
Constructors are generally used for instantiating an object.The task of constructors is to initialize(assign
values) to the data members of the class when an object of class is created.In Python the __init__() method is
called the constructor and is always called when an object is created.
def __init__(self):
# body of the constructor
Types of constructors :
● default constructor :The default constructor is a simple constructor which doesn’t accept any
arguments.It’s definition has only one argument which is a reference to the instance being
constructed.
● parameterized constructor :constructor with parameters is known as parameterized
constructor.The parameterized constructor takes its first argument as a reference to the instance
being constructed known as self and the rest of the arguments are provided by the programmer.
Example of default constructor :
class GeekforGeeks:
# default constructor
def __init__(self):
self.geek = "GeekforGeeks"
Output :
GeekforGeeks
23
Example of parameterized constructor :
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))
def calculate(self):
self.answer = self.first + self.second
# perform Addition
obj.calculate()
# display result
obj.display()
Output :
First number = 1000
Second number = 2000
Addition of two numbers = 3000
24
EXCEPTION HANDLING
The try block lets you test a block of code for errors.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
Example
This statement will raise an error, because x is not defined:
print(x)
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 kind of error:
Example
Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
25
Else
You can use the else keyword to define a block of code to be executed if no errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.
EXAMPLE
try:
print(x)
except:
print("Something went wrong")
finally:
Example
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
The program can continue, without leaving the file object open.
26
Raise an exception
Example
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
You can define what kind of error to raise, and the text to print to the user.
Example
x = "hello"
CONCLUSION : Hence we are successfully implemented to implement class, object, constructor and
exception handling in python
27
EXPERIMENT NO : 6
Theory:
Inheritance in Python
Inheritance is the capability of one class to derive or inherit the properties from another
class. The benefits of inheritance are:
1. It provides reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
2. It is transitive in nature, which means that if class B inherits from another class A, then
all the subclasses of B would automatically inherit from class A.
def feature2(self):
print('feature 2 working')
class B(A):
def feature3(self):
print('feature 3 working')
def feature4(self):
print('feature 4 working')
a1=A()
b1=B()
b1.feature1()
b1.feature2()
b1.feature3()
b1.feature4()
28
Output :
feature 1 working
feature 2 working
feature 3 working
feature 4 working
29
EXPERIMENT NO : 7
Theory:
NumPy Library stands for Numerical Python Library. In this library a NumPy Array object is homogeneous
multidimensional array object.
It is very useful for fast processing on large scale data. It is up to 50x faster than traditional Python lists.
# Initial Array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
print("Initial Array: ")
print(arr)
# Defining Array 1
a = np.array([[1, 2],
[3, 4]])
# Defining Array 2
b = np.array([[4, 3],
30
[2, 1]])
print('Array a \n ',a)
print ('\n Array b \n ',b)
# Forced Datatype
x = np.array([1, 2], dtype = np.int64)
print(x.dtype)
31
Output :
Initial Array:
[[-1. 2. 0. 4. ]
[ 4. -0.5 6. 0. ]
[ 2.6 0. 7. 8. ]
[ 3. -7. 4. 2. ]]
Array a
[[1 2]
[3 4]]
Array b
[[4 3]
[2 1]]
Array sum:
[[5 5]
[5 5]]
int32
float64
int64
32
EXPERIMENT NO : 8
Aim: Program to demonstrate Data Series and Data Frames using Pandas in python.
# list of strings
list = ['one', 'two', 'three', 'four','five', 'six', 'seven','eight','nine','ten']
# Create DataFrame
df = pd.DataFrame(data)
33
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Age':[27, 24, 22, 32],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
import pandas as pd
data=pd.read_csv('fish_stock_account.csv') #reading of dataset
Output :
34
Empty DataFrame
Columns: []
Index: []
0
0 one
1 two
2 three
3 four
4 five
5 six
6 seven
7 eight
8 nine
9 ten
Name Age
0 Tom 20
1 nick 21
2 krish 19
3 jack 18
4 john 23
5 rima 45
6 lili 22
0 one
1 two
2 three
3 four
4 five
dtype: object
0 1 2
name Aadi Jack Riti
age 16 34 30
city New york Sydney Delhi
CONCLUSION : Hence we are successfully implemented to
35
EXPERIMENT NO : 9
Aim: To create GUI in python containing widgets such as labels, textbox, radio, checkboxes and custom dialog
boxes.
Theory:
Program / Code :
# Frame
import tkinter
top = tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
#Label
from tkinter import
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()
#Button
import tkinter
top = tkinter.Tk()
top.title("1st frame")
def clicked():
top1=Tk()
top1.title("2nd frame")
btn1 = Button(top, text="Click Me", command=clicked)
btn1.grid(column=0, row=1)
top.mainloop()
36
#listbox
from tkinter import *
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
Lb1.pack()
top.mainloop()
#file button
from tkinter import *
top = Tk()
mb= Menubutton ( top, text="File", relief=RAISED )
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
mayoVar = IntVar()
ketchVar = IntVar()
mb.menu.add_checkbutton ( label="New",
variable=mayoVar )
mb.menu.add_checkbutton ( label="Open",
variable=ketchVar )
mb.pack()
top.mainloop()
37
#message
from tkinter import *
root = Tk()
var = StringVar()
label = Message( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()
#radiobutton
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Option 2", variable=var, value=2,
command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Option 3", variable=var, value=3,
command=sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop()
38
from tkinter import *
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill=Y )
mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert(END, "This is line number " + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()
#text
from tkinter import *
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="red", foreground="green")
root.mainloop()
39
Conclusion : Thus we have implemented GUI in Python.
40