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

PPL Lab Manual 2022-23

The document provides details about experiments to be conducted in the Python Programming Lab course. It includes 9 experiments that cover various Python concepts like mathematical operations, data types (strings, lists, tuples, dictionaries), conditional statements, loops, functions, classes/objects, inheritance, NumPy, Pandas, and GUI programming. The goal of the experiments is to help students learn and implement these Python features through hands-on practice.

Uploaded by

22405004nilay
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)
68 views

PPL Lab Manual 2022-23

The document provides details about experiments to be conducted in the Python Programming Lab course. It includes 9 experiments that cover various Python concepts like mathematical operations, data types (strings, lists, tuples, dictionaries), conditional statements, loops, functions, classes/objects, inheritance, NumPy, Pandas, and GUI programming. The goal of the experiments is to help students learn and implement these Python features through hands-on practice.

Uploaded by

22405004nilay
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/ 40

Electrical Engineering Department

Python Programming Lab

Class: SE Electrical Engg. Sem IV Subject: PPL

LIST OF EXPERIMENT

1. To implement mathematical operations in python.

2. To study string, list tuple, and dictionary in python.

3. To implement conditional statements and loop statements in python.

4. To study and implement functions in python.

5. To implement class, object, constructor and exception handling in python

6. To implement inheritance in python.

7. Exploring the basics of the Numpy package of Python.

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

Aim: To implement mathematical operations in python.

Theory:

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It


was created by 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.

Why to Learn Python?

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

Types of Operator

Python language supports the following types of operators.

● Arithmetic Operators
● Comparison (Relational) Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators

2
● Membership Operators
● Identity Operators

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

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


Multiplication

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

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

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


the power 20

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

CONCLUSION : Hence we are successfully implemented to implement mathematical operations in python.

4
EXPERIMENT NO : 2

Aim: To study string, list tuple, and dictionary in python.

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.

# Creating a String with single Quotes


String1 = 'Welcome to the python'
print("String with the use of Single Quotes: ")
print(String1)

Code & Output:


# Creating a String with single Quotes
String1 = 'Welcome to the world of python'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String with double Quotes


String1 = "I'm an engineer"
print("\nString with the use of Double Quotes: ")
print(String1)

#Creating a Tuple with the use of string


Tuple1 = ('hello', 'world')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with the use of list


list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a List of numbers

5
List = [10, 20, 30]
print("\nList of numbers: ")
print(List)

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary with dict() method


Dict = dict({1: 'one', 2: 'two', 3:'three'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary with each item as a Pair


Dict = dict([(1, 'one'), (2, 'two')])
print("\nDictionary with each item as a pair: ")
print(Dict)

Output :
String with the use of Single Quotes:
Welcome to the world of python

String with the use of Double Quotes:


I'm an engineer

Tuple with the use of String:


('hello', 'world')

Tuple using List:


(1, 2, 4, 5, 6)

List of numbers:
[10, 20, 30]
Empty Dictionary:
{}

Dictionary with the use of dict():


{1: 'one', 2: 'two', 3: 'three'}

Dictionary with each item as a pair:


{1: 'one', 2: 'two'}

CONCLUSION : Hence we are successfully implemented to

6
EXPERIMENT NO : 3

Aim: To implement conditional statements and loop statements in python.

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 −

Decision making statements in Python

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.

r.No. Statement & Description

1 if statements

An if statement consists of a boolean expression followed by one or more 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.

Sr.No. Loop Type & Description

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.

Code & Output:

Syntax (if statement)


if expression:

statement(s)

var1 = 100

if var1:

print "1 - Got a true expression value"

print var1

var2 = 0

if var2:

print "2 - Got a true expression value"

print var2

print "Good bye!"

Output:
1 - Got a true expression value

100

Good bye!

Syntax (if else statement)

10
if expression:

statement(s)

else:

statement(s)

var1 = 100

if var1:

print "1 - Got a true expression value"

print var1

else:

print "1 - Got a false expression value"

print var1

var2 = 0

if var2:

print "2 - Got a true expression value"

print var2

else:

print "2 - Got a false expression value"

print var2

print "Good bye!"

Output:
1 - Got a true expression value

100

2 - Got a false expression value

11
Good bye!

Syntax (nested if else statement)


if expression1:

statement(s)

if expression2:

statement(s)

elif expression3:

statement(s)

elif expression4:

statement(s)

else:

statement(s)

else:

statement(s)

var = 100

if var < 200:

print "Expression value is less than 200"

if var == 150:

print "Which is 150"

elif var == 100:

print "Which is 100"

elif var == 50:

print "Which is 50"

elif var < 50:

print "Expression value is less than 50"

else:

12
print "Could not find true expression"

print "Good bye!"

Output:
Expression value is less than 200

Which is 100

Good bye!

Syntax (while loop)


while expression:

statement(s)

count = 0

while (count < 9):

print 'The count is:', count

count = count + 1

print "Good bye!"

Output:
The count is: 0

The count is: 1

The count is: 2

The count is: 3

The count is: 4

The count is: 5

The count is: 6

The count is: 7

13
The count is: 8

Good bye!

Syntax (for loop)


for iterating_var in sequence:

statements(s)

for letter in 'Python': # First Example

print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']

for fruit in fruits: # Second Example

print 'Current fruit :', fruit

print "Good bye!"

Output:
Current Letter : P

Current Letter : y

Current Letter : t

Current Letter : h

Current Letter : o

Current Letter : n

Current fruit : banana

Current fruit : apple

Current fruit : mango

Good bye!

Syntax (nested while loop)


while expression:

while expression:

14
statement(s)

statement(s)

i=2

while(i < 100):

j=2

while(j <= (i/j)):

if not(i%j): break

j=j+1

if (j > i/j) : print i, " is prime"

i=i+1

print "Good bye!"

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

Aim: To study and implement functions in python.

Theory & Code & Output:

A function is a block of code which only runs when it is called.

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:

Example

def my_function():

print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example

def my_function():

print("Hello from a function")

my_function()

Arguments

Information can be passed into functions as 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):

print(fname + " Refsnes")

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.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.

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

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):

print(fname + " " + lname)

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

If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):

print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example

def my_function(child3, child2, child1):

print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example

def my_function(country = "Norway"):

print("I am from " + country)

my_function("Sweden")

19
my_function("India")

my_function()

my_function("Brazil")

Passing a List as an Argument

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)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Return Values

To let a function return a value, use the return statement:

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

Aim: To implement class, object, constructor and exception handling in python

Theory & Code & Output:

Python Classes/Objects

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.−

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.

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.

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.

21
CLASS
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

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

Syntax of constructor declaration :

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"

# a method for printing data members


def print_Geek(self):
print(self.geek)

# creating object of the class


obj = GeekforGeeks()

# calling the instance method using the object obj


obj.print_Geek()

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

# creating object of the class


# this will invoke parameterized constructor
obj = Addition(1000, 2000)

# 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 except block lets you handle the error.

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.

These exceptions can be handled using the try statement:

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:

print("The 'try except' is finished")

This can be useful to close objects and clean up resources:

Example

Try to open and write to a file that is not writable:

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

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example

Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

CONCLUSION : Hence we are successfully implemented to implement class, object, constructor and
exception handling in python

27
EXPERIMENT NO : 6

Aim: To implement inheritance in python.

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.

Code & Output:


class A:
def feature1(self):
print('feature 1 working')

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

CONCLUSION : Hence we are successfully implemented to

29
EXPERIMENT NO : 7

Aim: Exploring the basics of the Numpy package of Python.

Theory:

Learn NumPy Library in Python

NumPy Library stands for Numerical Python Library. In this library a NumPy Array object is homogeneous
multidimensional array object.

It provides many routines / functions for processing these arrays.

It is very useful for fast processing on large scale data. It is up to 50x faster than traditional Python lists.

Therefore it is one of the most used library in Python by Data Scientists.

Code & Output:


pip install numpy
import numpy as np

# Creating a rank 1 Array


arr = np.array([1, 2, 3])
print("Array with Rank 1 \n",arr)

# Creating a rank 2 Array


arr = np.array([[1, 2, 3],
[4, 5, 6]])
print("\n Array with Rank 2: \n", arr)

# Creating an array from tuple


tuple = np.array((1, 3, 2))
print("\n Array created using passed tuple:\n",tuple)

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

# Adding 1 to every element of a


print ("\n Adding 1 to every element of a:\n ", a + 1)

# Subtracting 2 from each element of b


print ("\nSubtracting 2 from each element of b:\n ", b - 2)

# sum of array elements Performing Unary operations


print ("\nSum of all array elements: ", a.sum())

# Adding two arrays Performing Binary operations


print ("\nArray sum:\n", a + b)

# Integer datatype guessed by Numpy


x = np.array([1, 2])
print(x.dtype)

# Float datatype guessed by Numpy


x = np.array([1.0, 2.0])
print(x.dtype)

# Forced Datatype
x = np.array([1, 2], dtype = np.int64)
print(x.dtype)

# Square root of Array


Sqrt = np.sqrt(x)
print("\nSquare root of x elements: ")
print(Sqrt)

31
Output :

Array with Rank 1


[1 2 3]

Array with Rank 2:


[[1 2 3]
[4 5 6]]

Array created using passed tuple:


[1 3 2]

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

Adding 1 to every element of a:


[[2 3]
[4 5]]

Subtracting 2 from each element of b:


[[ 2 1]
[ 0 -1]]

Sum of all array elements: 10

Array sum:
[[5 5]
[5 5]]

int32
float64
int64

Square root of x elements:


[1. 1.41421356]

CONCLUSION : Hence we are successfully implemented to

32
EXPERIMENT NO : 8

Aim: Program to demonstrate Data Series and Data Frames using Pandas in python.

Theory: Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data


structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is
aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components,
the data, rows, and columns.

Code & Output:


import pandas as pd
import numpy as np

# Calling DataFrame constructor


df = pd.DataFrame()
print(df)

# list of strings
list = ['one', 'two', 'three', 'four','five', 'six', 'seven','eight','nine','ten']

# Calling DataFrame constructor on list


df = pd.DataFrame(list)
print(df)

# Python code demonstrate creating


# DataFrame from dict narray / lists
# By default addresses.
# intialise data of lists.

data = {'Name':['Tom', 'nick', 'krish', 'jack','john','rima','lili'],


'Age':[20, 21, 19, 18,23,45,22]}

# Create DataFrame
df = pd.DataFrame(data)

# Print the output.


print(df)

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']}

# Convert the dictionary into DataFrame


df = pd.DataFrame(data)
print(df)

# select two columns


print(df[['Name', 'Qualification']])
print(ser[3:5])

# using indexing operator


data[3:6]

#create data frame using nested dictionary


studentData = {
0 : {'name' : 'Aadi',
'age' : 16,
'city' : 'New york'},
1 : {
'name' : 'Jack',
'age' : 34,
'city' : 'Sydney'
},
2 : {
'name' : 'Riti',
'age' : 30,
'city' : 'Delhi'
}
}
#Create dataframe from nested dictionary
df= pd.DataFrame(studentData)
print(df)

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

Name Age Address Qualification


0 Jai 27 Delhi Msc
1 Princi 24 Kanpur MA
2 Gaurav 22 Allahabad MCA
3 Anuj 32 Kannauj Phd
Name Qualification
0 Jai Msc
1 Princi MA
2 Gaurav MCA
3 Anuj Phd

0 one
1 two
2 three
3 four
4 five
dtype: object

name rollno city status


3 harry 4400 nagpur pass
4 lili 5500 pune pass
5 jack 6600 mumbai fail

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

You might also like