Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Python_Programming_LabManuals

The Python Programming (VSEC202) Lab Manual outlines a series of experiments for first-year engineering students at Konkan Gyanpeeth College of Engineering, focusing on Python programming skills. It includes instructions for installing Python and VS Code, a list of lab experiments covering various programming concepts, and guidelines for student conduct in the lab. The manual aims to help students write, test, and debug Python programs while implementing functions, conditionals, and data structures.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python_Programming_LabManuals

The Python Programming (VSEC202) Lab Manual outlines a series of experiments for first-year engineering students at Konkan Gyanpeeth College of Engineering, focusing on Python programming skills. It includes instructions for installing Python and VS Code, a list of lab experiments covering various programming concepts, and guidelines for student conduct in the lab. The manual aims to help students write, test, and debug Python programs while implementing functions, conditionals, and data structures.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

Python Programming (VSEC202) (Lab Manual)

Konkan Gyanpeeth College of Engineering, Karjat

SCIENCE & HUMANITIES

LAB MANUALS
Department- First Year Engineering
Semester- II (NEP-2020)
Course- F.E. (All Branches)
Subject Name- Python Programming (VSEC 202)

Department of science & Humanities, KGCE, Karjat Page 1


Python Programming (VSEC202) (Lab Manual)

Department- Science & Humanities


Semester- II (NEP-2020)
Course- F.E.
Subject Name- Python Programming

PYTHON LAB EXPERIMENT LIST


1. Installation and configure python IDE (Integrated Development Environment).
2. Write a python code to generate Personalized Greeting.
3. Write a python program to calculate areas of any geometric figures like circle,
rectangle and triangle.
4. Write a Python program to calculate the gross salary of an employee. The
program should prompt the user for the basic salary (BS) and then compute the
dearness allowance (DA) as 70% of BS, the travel allowance (TA) as 30% of BS,
and the house rent allowance (HRA) as 10% of BS. Finally, it should calculate the
gross salary as the sum of BS, DA, TA, and HRA and display the result.
5. Write a Python program to explore basic arithmetic operations. The program
should prompt the user to enter two numbers and then perform addition,
subtraction, multiplication, division, and modulus operations on those numbers.
The results of each operation should be displayed to the user.
6. Develop a Python program to manage a task list using lists and tuples, including
adding, removing, updating, and sorting tasks.

7. Create a Python code to demonstrate the use of sets and perform set operations
(union, intersection, difference) to manage student enrollments in multiple
courses / appearing for multiple entrance exams like CET, JEE, NEET etc.

8. Write a Python program to create, update, and manipulate a dictionary of


student records, including their grades and attendance.

9. Develop a Python program that takes a numerical input and identifies whether it
is even or odd, utilizing conditional statements and loops.

10. Design a Python program to compute the factorial of a given integer N.


Department of science & Humanities, KGCE, Karjat Page 2
Python Programming (VSEC202) (Lab Manual)

11. Write a Python program to print a triangle pattern (give any), emphasizing the
transition from C to Python syntax.

12. Implement a simple Python calculator that takes user input and performs basic
arithmetic operations (addition, subtraction, multiplication, division) using
functions.

13. Using function, write a Python program to analyze the input number is prime or
not.

14. Develop a Python program that reads a text file and prints words of specified
lengths (e.g., three, four, five, etc.) found within the file.

15. Create a executable file for any program developed in earlier practical.

16. Write a Python program that takes two numbers as input and performs division.
Implement exception handling to manage division by zero and invalid input errors
gracefully.

17. Demonstrate the use of a Python debugger (e.g., pdb or an IDE with debugging
capabilities) on a sample program with intentional errors. Guide students on
setting breakpoints, stepping through code, and examining variable values.

18. Implement an event management system using OOP concepts to organize and
manage various aspects.

19. Designing Graphical user interface (GUI) using built-in tools in python using
Tkinter.

20. Write a Python script that prompts the user to enter their phone number and
email ID. It then employs Regular Expressions to verify if these inputs adhere to
standard phone number and email address formats.

21. Write a Python program to create a 1D, 2D, and 3D NumPy array. Perform basic
operations like reshaping, slicing, and indexing.

Department of science & Humanities, KGCE, Karjat Page 3


Python Programming (VSEC202) (Lab Manual)

22. Load a CSV file containing information on global COVID-19 cases into a
DataFrame. Display the first few rows, check the data types, and summarize basic
statistics.

23, Plotting graphs: Generate a line plot showing the trend / bar plot to compare
data/ histogram to show distribution/ scatter plot to examine relationships
between variables.

Department of science & Humanities, KGCE, Karjat Page 4


Python Programming (VSEC202) (Lab Manual)

INSTRUCTIONS FOR STUDENTS-


• Students should report to the concerned labs as per the given
timetable.

• Students should make an entry in the log book whenever they enter
the labs during practical or for their own personal work.

• When the experiment is completed, students should shut down the


computers and make the counter entry in the logbook.

• Any damage to the lab computers will be viewed seriously.

• Students should not leave the lab without concerned faculty’s


permission

Department of science & Humanities, KGCE, Karjat Page 5


Python Programming (VSEC202) (Lab Manual)

LAB OBJECTIVES-
➢ To write, test, and debug simple Python programs.

➢ To implement Python programs with conditionals and loops.

➢ Use functions for structuring Python programs.

➢ Represent compound data using Python lists, tuples, and dictionaries. ➢


Read and write data from/to files in Python.

LAB OUTCOMES-
Upon completion of the course, students will be able to-

➢ Write, test, and debug simple Python programs.

➢ Implement Python programs with conditionals and loops.

➢ Develop Python programs step-wise by defining functions and calling


them.

➢ Use Python lists, tuples, dictionaries for representing compound data.

➢ Read and write data from/to files in Python

Department of science & Humanities, KGCE, Karjat Page 6


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO.

INSTALLATION AND CONFIGURE PYTHON IDE (INTEGRATED DEVELOPMENT ENVIRONMENT)

AIM- To install and configure python integrated development environment.

OBJECTIVES- To study the installation of python and set the path for environment.

THEORY- Python is a high-level, general-purpose, interpreted, interactive, object-oriented


dynamic programming language. Student will able to select and install appropriate
installer for Python in windows and package manager for Ubuntu in order to setup
Python environment for running programs.

Installing Python in Windows:

➢ Open any internet browser. Type http:///www.Python.org/downloads/ in address


bar and Enter.

➢ Home page of Python will have displayed as shown in Figure-1.

Department of science & Humanities, KGCE, Karjat Page 7


Python Programming (VSEC202) (Lab Manual)

➢ Click on download the latest version for windows, which shows latest version as
shown in Figure-2.

➢ Open the Python 3.11.2 version pack and double click on it to start installation
and installation windows will be open as shown in Figure-3.

Department of science & Humanities, KGCE, Karjat Page 8


Python Programming (VSEC202) (Lab Manual)

➢ Click on next install now for installation and then Setup progress windows will be
opened as shown in Figure-4.

➢ After complete the installation, Click on close button in the windows as shown in
Figure-5.

Department of science & Humanities, KGCE, Karjat Page 9


Python Programming (VSEC202) (Lab Manual)

Installing Python in Windows:

Starting Python (Command Line)-

✓ Press start button

✓ Click on all programs and then click on Python 3.11.2 (64 bit). You will see the
Python interactive prompt in Python command line.

Department of science & Humanities, KGCE, Karjat Page 10


Python Programming (VSEC202) (Lab Manual)

✓ Python command prompt contains an opening message >>> called command


prompt. The cursor at command prompt waits for to enter Python command. A
complete command is called a statement. For example, check first command to
print message.

✓ To exit from the command line of Python, press Ctrl+z followed by Enter or Enter
exit() or quit() and Enter.

Installing VS Code in Windows:

➢ Click on the link of official website for VS code :


https://code.visualstudio.com/download
➢ Click on download for windows:

Department of science & Humanities, KGCE, Karjat Page 11


Python Programming (VSEC202) (Lab Manual)

➢ Click on downloads, double click on the downloaded ‘VSCodeUserSetup-x64-


1.x.x.exe file:

➢ Once the installer launches, accept the license agreement and then click Next-

➢ Accept the default location for installation and then click Next-

Department of science & Humanities, KGCE, Karjat Page 12


Python Programming (VSEC202) (Lab Manual)

➢ Accept the default Start Menu folder name by clicking Next-

Department of science & Humanities, KGCE, Karjat Page 13


Python Programming (VSEC202) (Lab Manual)

➢ Optionally check the boxes for “Creating a desktop icon”, and adding VS code to the
Right-Clicking menu functionally of windows File Explorer, then click Next-

➢ Confirm the installation option and then click Install

Department of science & Humanities, KGCE, Karjat Page 14


Python Programming (VSEC202) (Lab Manual)

➢ The installation will proceed

➢ Click Finish to exit the installation and (by default) lauch the Visual Studio Code.

Department of science & Humanities, KGCE, Karjat Page 15


Python Programming (VSEC202) (Lab Manual)

➢ After clicking on VS code icon VS code will launch

CONCLUSON- In this way we can install the python and VS code integrated development
environment.

Department of science & Humanities, KGCE, Karjat Page 16


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 01 to 03

PERSONIZED GREETING GENERATOR

AIM- Write a Python code to create personalized greeting.

OBJECTIVES- To understand the basic input output instructions used in python.

THEORY-

Python is a programming language that lets you work quickly and integrate
systems more efficiently. It is a widely-used general-purpose, high-level programming
language. It was designed with an emphasis on code readability, and its syntax allows
programmers to express their concepts in fewer lines of code. In the Python
programming language, there are two ways in which we can run our code:
✓ Interactive mode
✓ Script mode

Interactive mode- In the interactive mode as we enter a command and press enter, the
very next step we get the output. The output of the code in the interactive mode is
influenced by the last command we give. Interactive mode is very convenient for writing
very short lines of code. In python it is also known as REPL which stands for Read
Evaluate Print Loop. Here, the read function reads the input from the user and stores it
in memory. Eval function evaluates the input to get the desired output. Print function
outputs the evaluated result. The loop function executes the loop during the execution
of the entire program and terminates when our program ends. This mode is very
suitable for beginners in programming as it helps them evaluate their code line by line
and understand the execution of code well.

Script mode- In the script mode, a python program can be written in a file. This file can
then be saved and executed using the command prompt. We can view the code at any
time by opening the file and editing becomes quite easy as we can open and view the
entire code as many times as we want. Script mode is very suitable for writing long
pieces of code. It is much preferred over interactive mode by experts in the program.
The file made in the script mode is by default saved in the Python installation folder and
the extension to save a python file is “.py”.

Department of science & Humanities, KGCE, Karjat Page 17


Python Programming (VSEC202) (Lab Manual)

How to run python code in script mode?


In order to run a code in script mode follow the following steps.
Step 1: Open python IDLE Shell and from file menu open new file & write a code in new
untitled file.
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now to execute code click on run -> run module or press F5 key on keyboard.
Step 4: You will see the output on IDLE Shell.

In this program we will use the input and output instruction, the syntax for input and
output instructions are-

Input syntax-

Variable (Identifier) = input(“Statement”)

In python the input taken from user is always a string, if we want to use it in
other data type then convert it.

Output syntax-

Print(“Statement”, variable)

In python if we want to print more than one variable then separate it by comma.

PROGRAM-

Program statement -01

# Program to write personalized greeting


name = input(“Enter the name- “)
print(f“Hello !!! {name} \nHow are You…!”)
Output-
Enter the name- KGCE
Hello !!! KGCE
How are You…!

Department of science & Humanities, KGCE, Karjat Page 18


Python Programming (VSEC202) (Lab Manual)

Program statement -02

# Calculating Areas of Geometric Figures like circle, Rectangle, Triangle

Python Program to find the area of Circle-


r = float(input('Enter the radius of circle- '))
pi = 3.14
# formula for area of circle
a = pi*r*r
# calculate the area
print(“The area of the circle is- “, a)
Output-

Enter the radius of circle- 5


The area of the circle is- 78.3

Python Program to find the area of Rectangle-


l = float(input('Enter the length of rectangle- '))
b = float(input('Enter the breath of rectangle- '))
# formula for area of rectangle
a = l*b
# calculate the area
print(“The area of the rectangle is- “, a)
Output-

Enter the length of rectangle- 5


Enter the breath of rectangle- 4
The area of the rectangle is- 20.0

Python Program to find the area of Triangle-


h = float(input('Enter the height of triangle- '))
b = float(input('Enter the base of triangle- '))
# formula for area of triangle
a = h*b/2
# calculate the area
print(“The area of the rectangle is- “, a)

Department of science & Humanities, KGCE, Karjat Page 19


Python Programming (VSEC202) (Lab Manual)

Output-

Enter the height of triangle- 5


Enter the base of triangle- 4
The area of the rectangle is- 10.0

Program statement -03

# Write a Python program to calculate the gross salary of an employee. The program
should prompt the user for the basic salary (BS) and then compute the dearness
allowance (DA) as 70% of BS, the travel allowance (TA) as 30% of BS, and the house
rent allowance (HRA) as 10% of BS. Finally, it should calculate the gross salary as the
sum of BS, DA, TA, and HRA and display the result.

Python Program to calculate Gross salary of an Employee-

BS = float(input('Enter the Basic Salary of an Employee- '))


DA = (70*BS)/100
TA = (10*BS)/100
HRA = (30*BS)/100
# formula for gross salary of an Employee
Gross_salary = BS + DA + TA + HRA
#calculate gross salary of an Employee
print(“Gross Salary of an Employee is- “, Gross_salary)

Output-

Enter the Basic Salary of an Employee - 10000


Gross Salary of an Employee is- 21000.0

CONCLUSON- In this way we can generate the personalized greeting with the help of input and
output statements.

Department of science & Humanities, KGCE, Karjat Page 20


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 04

WRITE A PYTHON PROGRAM TO EXPLORE BASIC ARITHMETIC OPERATIONS.

AIM- Write a program to demonstrate basic arithmetic operations in Python.

OBJECTIVES- To understand the basic data types, operators and input and output expression
in python and make simple programs on it.

THEORY-

Data Types- Data types are the classification or categorization of data items. It
represents the kind of value that tells what operations can be performed on a particular
data. Since everything is an object in Python programming, data types are actually
classes and variables are instances (object) of these classes. The following are the
standard or built-in data types in Python:

Operators-
Operators in general are used to perform operations on values and variables.
These are standard symbols used for the purpose of logical and arithmetic operations.
The different types of operators are-

Department of science & Humanities, KGCE, Karjat Page 21


Python Programming (VSEC202) (Lab Manual)

✓Arithmetic Operators
✓Comparison Operators
✓Logical Operators
✓Bitwise Operators
✓Assignment Operators
✓Identity Operators and Membership Operators

Arithmetic Operator- Arithmetic operators are used to perform basic mathematical


operations like addition, subtraction, multiplication, and division.

Operator Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

Modulus: returns the remainder when the first operand is divided


% x%y
by the second

** Power: Returns first raised to power second x ** y

Program-
a = int(input(“Enter the first number- “)
b = int(input(“Enter the second number- “)

Department of science & Humanities, KGCE, Karjat Page 22


Python Programming (VSEC202) (Lab Manual)

# Addition
print(“Addition- “, a + b)
# Subtraction
print(“Subtraction- “ , a - b)
# Multiplication
print(“Multiplication- “, a * b)
# Division
print(“Division – “, a / b)
# Modulus
print(“Modulus- “, a % b)
# Floor division
print(“Floor Division- “, a //by)
# Exponentiation
print(“Exponential- “, a ** b)

Output-

Enter the first number- 5


Enter the second number- 2
Addition- 7
Subtraction- 5
Multiplication- 10
Division – 2.5
Modulus- 1
Floor Division- 2
Exponential- 25

CONCLUSON- In this way we can study and write simple programs for arithmetic operations in
python.

Department of science & Humanities, KGCE, Karjat Page 23


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 05

MANAGE A TASK LIST USING LIST & TUPLE.

AIM- Develop a Python program to manage a task list using lists and tuples, including
adding, removing, updating, and sorting tasks.

OBJECTIVES- To understand the basic operations of list and tuple.

THEORY-

Lists - List is simply the collections of different data types which are separated by
comma and enclosed in square bracket. Lists are used to store multiple items in a single
variable. List items are ordered, changeable, and allow duplicate values. The elements
of list can be assessed by indexing.
The different list methods are-

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Department of science & Humanities, KGCE, Karjat Page 24


Python Programming (VSEC202) (Lab Manual)

Tuple Data Type- Tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable i.e. tuples cannot be
modified after it is created i.e. it is readable version of list. It is represented by a tuple
class. Tuples are created by placing a sequence of values separated by a ‘comma’ with
or without the use of parentheses for grouping the data sequence. Tuples can contain
any number of elements and of any datatype (like strings, integers, lists, etc.). The tuple
elements can be assessed by indexing.
The different tuple methods are-

Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position
of where it was found

PROGRAM-

# List
l = [1, 5, 4, 2, 4+7j, True, 4.2, 7]
print(l)
print("----------Adding---------------")
l.append(10)
print(l)
l.insert(0, 50)
print(l)
l.extend([2, 3])
print(l)
l[0] = 30
print(l)

print("----------Delete---------------")
Department of science & Humanities, KGCE, Karjat Page 25
Python Programming (VSEC202) (Lab Manual)

l.remove(4+7j)
print(l)
del_item = l.pop(1)
print(del_item)
del l[0]
print(l)

print("----------Update---------------")
l[-1] = 9
l[1 : 5] = [5, 4, 7, 15]
print(l)

print("----------sorting---------------")
l.sort()
print(l)
l.sort(reverse = True)
print(l)
l.reverse()
print(l)
Output-
[1, 5, 4, 2, (4+7j), True, 4.2, 7]
----------Adding---------------
[1, 5, 4, 2, (4+7j), True, 4.2, 7, 10]
[50, 1, 5, 4, 2, (4+7j), True, 4.2, 7, 10]
[50, 1, 5, 4, 2, (4+7j), True, 4.2, 7, 10, 2, 3]
[30, 1, 5, 4, 2, (4+7j), True, 4.2, 7, 10, 2, 3]
----------Delete---------------
[30, 1, 5, 4, 2, True, 4.2, 7, 10, 2, 3]
[5, 4, 2, True, 4.2, 7, 10, 2, 3]
Department of science & Humanities, KGCE, Karjat Page 26
Python Programming (VSEC202) (Lab Manual)

----------Update---------------
[5, 5, 4, 7, 15, 7, 10, 2, 9]
----------sorting---------------
[2, 4, 5, 5, 7, 7, 9, 10, 15]
[15, 10, 9, 7, 7, 5, 5, 4, 2]
[2, 4, 5, 5, 7, 7, 9, 10, 15]
# Tuple-
t = (4, 1, 2, 3, 6)
print(t)
print("----------Sort--------------")
s = sorted(t)
print(s)
print("----------Reverse-----------")
rev = sorted(t, reverse=True)
print(rev)
Output-

(4, 1, 2, 3, 6)
----------Sort--------------
[1, 2, 3, 4, 6]
----------Reverse-----------
[6, 4, 3, 2, 1]

CONCLUSON- In this way we can study and write different operations on list and tuple in
python.

Department of science & Humanities, KGCE, Karjat Page 27


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 06

SET OPERATIONS FOR MULTIPLE STUDENTS DATA

AIM- Create a Python code to demonstrate the use of sets and perform set operations
to manage student enrollments in multiple courses / appearing for multiple entrance
exams like CET, JEE, NEET etc

.OBJECTIVES- To understand the different operations of set data types

THEORY-

A Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements. Sets can be created by using the built-in set() function with an
iterable object or a sequence by placing the sequence inside curly braces, separated by
a ‘comma’. The type of elements in a set need not be the same, various mixed-up data
type values can also be passed to the set. It is denoted by the class set.
Python Set Operations -
Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference. We can do this with operators or
methods.
Set Union:

Union of A and B is a set of all elements from both sets. Union is performed using
| operator. Same can be accomplished using the union() method.

Department of science & Humanities, KGCE, Karjat Page 28


Python Programming (VSEC202) (Lab Manual)

Set Intersection:

Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the
intersection() method.
Set Difference:

Difference of the set B from set A(A - B) is a set of elements that are only in A but
not in B. Similarly, B - A is a set of elements in B but not in A. Difference is performed
using - operator. Same can be accomplished using the difference() method.
PROGRAM-
# Create sets of students enrolled in different entrance exams
cet_students = {"J", "A", "B", "D", "E"}
jee_students = {"A", "B", "C", "D", "G"}
neet_students = {"E", "G", "A", "C", "F", "H"}
# Union of sets: Students appearing for any of the exams (CET, JEE, or NEET)
all_students = cet_students.union(jee_students).union(neet_students)
print("Students appearing for any exam (CET, JEE, NEET):")
print(all_students)

Department of science & Humanities, KGCE, Karjat Page 29


Python Programming (VSEC202) (Lab Manual)

# Intersection of sets: Students appearing for all three exams (CET, JEE, NEET)
students_in_all_exams = cet_students.intersection(jee_students, neet_students)
print("\nStudents appearing for all three exams (CET, JEE, NEET):")
print(students_in_all_exams)

# Difference of sets: Students enrolled in CET but not in JEE or NEET


cet_only_students = cet_students.difference(jee_students,neet_students)
print("\nStudents enrolled only in CET:")
print(cet_only_students)

# Symmetric Difference of sets: Students enrolled in either CET, JEE, or NEET but not in both
exclusive_students=cet_students.symmetric_difference(jee_students).symmetric_differ
ence(neet_students)
print("\nStudents appearing in only one of the exams (CET, JEE, or NEET, but not
both):")
print(exclusive_students)
Output-
Students appearing for any exam (CET, JEE, NEET):
{'J', 'F', 'E', 'C', 'B', 'D', 'H', 'G', 'A'}
Students appearing for all three exams (CET, JEE, NEET):
{'A'}
Students enrolled only in CET:
{'J'}
Students appearing in only one of the exams (CET, JEE, or NEET, but not both):
{'J', 'F', 'A', 'H'}
CONCLUSON- In this way we can perform the different set operations in python.

Department of science & Humanities, KGCE, Karjat Page 30


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 07

DICTIONARY OPERATION FOR STUDENT’S RECORDS

AIM- Write a Python program to create, update, and manipulate a dictionary of student
records, including their grades and attendance.

.OBJECTIVES- To understand the basic operation of dictionary for student’s database.

THEORY-

A dictionary in Python is collection of data pair in terms of keys and values, used
to store data values like a map, unlike other Data Types that hold only a single value as
an element. Each key-value pair in a Dictionary is separated by a colon : , whereas each
key is separated by a ‘comma’. In Python, a Dictionary can be created by placing a
sequence of elements within curly {} braces, separated by ‘comma’. Values in a
dictionary can be of any datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable. The dictionary can also be created by the built-in
function dict(). An empty dictionary can be created by just placing it in curly braces{}.
The different operations of dictionary are-

Department of science & Humanities, KGCE, Karjat Page 31


Python Programming (VSEC202) (Lab Manual)

PROGRAM-

''' Write a Python program to create, update, and manipulate a dictionary of student
records, including their grades and attendance. '''

print("---------------dictionaries----------------------")
D = {"roll" : 1, "Name" : "A", "Year" : "FE", "Age": 20, "grade" : "Distinction",
"Attendance" : 70}
print(D)
print(type(D))
print("length of dict is : ", len(D))
print(D.keys())
print(D.values())
print("-------------access an item-------------------")
print(D['roll'])
print(D.get("Attendance"))
print("-------------update/add-------------------")
D['grade'] = "First Class"
print("Add new element: ", D)
D['Attendance'] = "80%"
print("Update dictionary : ", D)
D.update(occupation = "software developer")
print(D)
print("-------------Update-------------------")
D["Age"]=25
print(D)
print("-------------delete-------------------")
D.pop("occupation")
print(D)

Department of science & Humanities, KGCE, Karjat Page 32


Python Programming (VSEC202) (Lab Manual)

del D['Age']
print(D)
Output-

---------------dictionaries----------------------
{'roll': 1, 'Name': 'A', 'Year': 'FE', 'Age': 20, 'grade': 'Distinction', 'Attendance': 70}
<class 'dict'>
length of dict is : 6
dict_keys(['roll', 'Name', 'Year', 'Age', 'grade', 'Attendance'])
dict_values([1, 'A', 'FE', 20, 'Distinction', 70])
-------------access an item-------------------
1
70
-------------update/add-------------------
Add new element: {'roll': 1, 'Name': 'A', 'Year': 'FE', 'Age': 20, 'grade': 'First Class',
'Attendance': 70}
Update dictionary : {'roll': 1, 'Name': 'A', 'Year': 'FE', 'Age': 20, 'grade': 'First Class',
'Attendance': '80%'}
{'roll': 1, 'Name': 'A', 'Year': 'FE', 'Age': 20, 'grade': 'First Class', 'Attendance': '80%',
'occupation': 'software developer'}
-------------Update-------------------
{'roll': 1, 'Name': 'A', 'Year': 'FE', 'Age': 25, 'grade': 'First Class', 'Attendance': '80%',
'occupation': 'software developer'}
-------------delete-------------------
{'roll': 1, 'Name': 'A', 'Year': 'FE', 'Age': 25, 'grade': 'First Class', 'Attendance': '80%'}
{'roll': 1, 'Name': 'A', 'Year': 'FE', 'grade': 'First Class', 'Attendance': '80%'}

CONCLUSON- In this way we can perform the different operations on students data using
dictionary in python.

Department of science & Humanities, KGCE, Karjat Page 33


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 08-10

CONTROL FLOW STATEMENTS: CONDITIONAL STATEMENTS (IF, IF...ELSE, NESTED IF)

AIM- Develop a Python program that takes a numerical input and identifies whether it
is even or odd, utilizing conditional statements and loops.

OBJECTIVES- To understand the control statements in python and make simple programs on
it.

THEORY- A simple program written in Python consists of a set of statements that contain
expressions. An expression is a statement (or logical line) that comprises an operand and
operator.
When we execute a Python program, at a time, only one statement executes by
the Python interpreter. We call these statements as sequential statements.
Sequential statements are those statements that execute from top to bottom one
by one (sequentially). The flow of execution takes place from top to bottom in the same
order in which they appear in the program.
However, if we want to change the flow of execution of a program, we can use control
flow statements in Python.
The different types of flow control statements are-

Department of science & Humanities, KGCE, Karjat Page 34


Python Programming (VSEC202) (Lab Manual)

CONDITIONAL STATEMENT-
In Python, condition statements act depending on whether a given condition is true or
false. You can execute different blocks of codes depending on the outcome of a
condition. Condition statements always evaluate to either True or False.
There are three types of conditional statements.

1. if statement
2. if-else
3. if-elif-else
4. nested if-else

If statement- In control statements, The if statement is the simplest form. It takes a


condition and evaluates to either True or False. If the condition is True, then the True
block of code will be executed, and if the condition is False, then the block of code is
skipped, and The controller moves to the next line

If – else statement- The if-else statement checks the condition and executes the if block
of code when the condition is True, and if the condition is False, it will execute
the else block of code.

Department of science & Humanities, KGCE, Karjat Page 35


Python Programming (VSEC202) (Lab Manual)

If the condition is True, then statement 1 will be executed If the condition is False,
statement 2 will be executed. See the following flowchart for more detail.

Multiple If statement/If-elif-else statements- In Python, the if-elif-else condition


statement has an elif blocks to chain multiple conditions one after another. This is
useful when you need to check multiple conditions. With the help of if-elif-else we can
make a tricky decision. The elif statement checks multiple conditions one by one and if
the condition fulfills, then executes that code.

Nested if-else statement -In Python, the nested if-else statement is an if statement
inside another if-else statement. It is allowed in Python to put any number

Department of science & Humanities, KGCE, Karjat Page 36


Python Programming (VSEC202) (Lab Manual)

of if statements in another if statement. Indentation is the only way to differentiate the


level of nesting. The nested if-else is useful when we want to make a series of decisions.

LOOP-

Iterative statements-

Iteration statements or loop statements allow us to execute a block of


statements as long as the condition is true. Loops statements are used when we need
to run same code again and again, each time with a different value.

The iterative statements are of following types-

✓ For loop
✓ While Loop
✓ Nested For Loop
For Loop- In Python, the for loop is used to run a block of code for a certain number of
times. It is used to iterate over any sequences such as list, tuple, string, etc.

Department of science & Humanities, KGCE, Karjat Page 37


Python Programming (VSEC202) (Lab Manual)

Here, variable accesses each item of sequence on each iteration. Loop continues
until we reach the last item in the sequence.

While Loop- While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition is true. In while loop, test expression is checked
first. The body of the loop is entered only if the test expression is True. After one
iteration, the test expression is checked again. This process continues until the test
expression evaluates to False.

Department of science & Humanities, KGCE, Karjat Page 38


Python Programming (VSEC202) (Lab Manual)

PROGRAM-

# Program to find Even or Odd number using conditional statement and loop

Using For Loop-

n = int(input("Enter the number- "))


for i in range(1, n+1):
if I % 2 == 0:
print(f“The given number {i} is Even”)
else:
print(f“The given number {i} is Odd”)

Output-

Enter the number- 5


The given number 1 is Odd
The given number 2 is Even
The given number 3 is Odd
The given number 4 is Even
The given number 5 is Odd
Using While Loop-

n = int(input("Enter the number- "))


i=1
while I <= n:
if I % 2 == 0:
print(f“The given number {i} is Even”)
else:
print(f“The given number {i} is Odd”)
Output-

Enter the number- 5


The given number 1 is Odd
The given number 2 is Even
The given number 3 is Odd
The given number 4 is Even
The given number 5 is Odd

Department of science & Humanities, KGCE, Karjat Page 39


Python Programming (VSEC202) (Lab Manual)

# Design a Python program to compute the factorial of a given integer N

Using For loop-

n = int(input("Enter the number- "))


fact = 1
for i in range(1, n+1):
fact *= i

print("factorial of given number is- ", fact)

Output-

Enter the number- 5


factorial of given number is- 120

Using while loop-

n = int(input('Enter the number- '))


i=1
fact = 1
while n >= i:
fact *= i
i += 1
print("factorial of given number is- ", fact)
Output-

Enter the number- 5


factorial of given number is- 120

Department of science & Humanities, KGCE, Karjat Page 40


Python Programming (VSEC202) (Lab Manual)

# Design a Python program for star pattern

Program-

n=int(input("Enter the number of rows- "))


for i in range(1,n+1):
print(" "*(n-i),end="")
for j in range(1,i+1):
print("*",end=" ")
print()
Output-

*
* *
* * *
* * * *
* * * * *

CONCLUSON- In this way we can study and write simple programs using for loop and while
loop using iterative control statements with conditional statement in python.

Department of science & Humanities, KGCE, Karjat Page 41


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 11-12

FUNCTIONS

AIM- Write a program to demonstrate functions for finding prime number and
calculator in Python.

OBJECTIVES- To understand the basic construction and programming of functions for


different application .

THEORY-

A function is a block of organized, reusable code that is used to perform a single,


related action. Functions provide better modularity for your application and a high
degree of code reusing.

If a group of statements is repeatedly required then it is not recommended to


write these statements every time separately have to define these statements as a
single unit and we can call that unit any number of times based on our requirement
without rewriting. This unit is nothing but function. The main advantage of functions is
code Reusability.

Python supports two types of functions-


✓ Built in Functions
✓ User Defined Functions

Built in Functions- The functions which are coming along with Python software
automatically, are called built in functions or pre defined functions
Ex- id()
type()
input()
eval() etc..

Department of science & Humanities, KGCE, Karjat Page 42


Python Programming (VSEC202) (Lab Manual)

User Defined Functions- The functions which are developed by programmer explicitly
according to business requirements ,are called user defined functions. The syntax for
user defined function is as follows-

Rules for Defining Function in Python

• Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these
parentheses. We also define parameters inside these parentheses.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an
expression to the caller.
• Are turn statement with no arguments is the same as return None.

Parameters-
Parameters are inputs to the function. If a function contains parameters, then at
the time of calling, compulsory we should provide values, otherwise we will get error.
Types of Variables-

Python supports 2 types of variables.


✓ Global Variables
✓ Local Variables

Department of science & Humanities, KGCE, Karjat Page 43


Python Programming (VSEC202) (Lab Manual)

Global Variables- The variables which are declared outside of function are called global
variables. These variables can be accessed in all functions of that module.

Local Variables- The variables which are declared inside a function are called local
variables. Local variables are available only for the function in which we declared it.i.e
from outside of function we cannot access.

PROGRAM-

# Write a Python program to analyze the input number is prime or not.

def prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

n = int(input("Enter a number - "))


if prime(n):
print(f"The given number {n} is a prime number.")
else:
print(f"The given number {n} is not a prime number.")

Output-
Enter a number - 0
The given number 0 is not a prime number.

Enter a number - 7
The given number 7 is a prime number.

Enter a number - 10
The given number 0 is not a prime number.
Department of science & Humanities, KGCE, Karjat Page 44
Python Programming (VSEC202) (Lab Manual)

# Implement a simple Python calculator that takes user input and performs basic
arithmetic operations (addition, subtraction, multiplication, division) using functions.

def add(x, y):


print("Addition- ", x+y)

def sub(x, y):


print("Subtraction- ", x-y)

def mul(x, y):


print("Multiplication- ", x*y)

def div(x, y):


print("Division- ", x/y)

add(5, 4)
sub(5, 4)
mul(5, 4)
div(5, 4)

Output-
Addition- 9
Subtraction- 1
Multiplication- 20
Division- 1.25

-------OR------
def add(x, y):
return "Addition", x+y

def sub(x, y):


return "subtraction", x-y

def mul(x, y):


return "Multiplication", x*y

Department of science & Humanities, KGCE, Karjat Page 45


Python Programming (VSEC202) (Lab Manual)

def div(x, y):


return "Division", x/y

print(add(5, 4))
print(sub(5, 4))
print(mul(5, 4))
print(div(5, 4))

Output-
('Addition', 9)
('subtraction', 1)
('Multiplication', 20)
('Division', 1.25)

CONCLUSON- In this way we can study and write simple programs for different operations
using function in python.

Department of science & Humanities, KGCE, Karjat Page 46


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 13-14

FILE HANDELLING OPERATIONS

AIM- Write a program to demonstrate and implement simple program on different file
handling operations.

OBJECTIVES- To understand the basic concept of different types of files available and its
operation in terms of read, write etc.

THEORY- As a part of programming requirement, we have to store data permanently for


future purpose. For this we should go for files. Files are very common permanent area
to store our data.

There are three types of files-

Text files- It is used to store character data. Ex- abc.txt


Binary files- It is used to store binary data like image, video files or audio files etc

The different operations of file handling are-

CSV File (Comma Separated Value File)- Each Value in a line is separated by
Delimiter(','). CSV is used to store tabular data, such as spreadsheet or database. CSV
Files can be imported to and exported from programs that store data in tables,

Ex - MS Excel.

Opening a file-

Before performing any operation on the file like reading or writing, first, we have to
open that file. For this, we should use Python’s inbuilt function open () but at the time of
opening, we have to specify the mode, which represents the purpose of the opening file.

Syntax- f = open(filename, mode)


Where the following mode is supported:
r- open an existing file for a read operation.

Department of science & Humanities, KGCE, Karjat Page 47


Python Programming (VSEC202) (Lab Manual)

w- open an existing file for a write operation. If the file already contains some data then
it will be overridden but if the file is not present then it creates the file as well.
a- open an existing file for append operation. It won’t override existing data.
r+- To read and write data into the file. The previous data in the file will be overridden.
w+- To write and read data. It will override existing data.
a+- To append and read data from the file. It won’t override existing data.

All the above modes are applicable for text files only. If the above mode suffixed with
‘b’ then these represent binary files. Ex- rb, wb, ab, r+b, w+b, a+b, xb.

Program- To open the file


f = open("FILE PATH", ‘r’)
print(f)
Program- To read the file
FILE_PATH = "C:\Users\kgce\Desktop\Question Bank.docx"
f = open(FILE_PATH, ‘r’)
print(f.read())
Program- To write in the file
FILE_PATH = "C:\Users\kgce\Desktop\Question Bank.docx"
f = open(FILE_PATH, ‘w’)
f.write(“statement”) or f.writelines if we want to write more lines
f.close()
Program- To read from the file
FILE_PATH = "C:\Users\kgce\Desktop\Question Bank.docx"
f = open(FILE_PATH, ‘r’)
print(f.read())
Program- To check particular file exist or not
import os, sys
FILE_PATH = " C:\Users\kgce\Desktop\Question Bank.docx "
fname = input("Enter the file name- ")
if os.path.isfile(fname):
print("File exists", fname)
f = open(FILE_PATH, 'r')

Department of science & Humanities, KGCE, Karjat Page 48


Python Programming (VSEC202) (Lab Manual)

else:
print("File does not exists", fname)
sys.exit(0)

print("The contents of all file is")


print(f.read())

Problem Statement 1:

# Develop a Python program that reads a text file and prints words of specified lengths
(e.g., three, four, five, etc.) found within the file.

f = open("E:\\Python_MAterial\\Practice\\ppp.txt", mode = 'r')


print(f.read())
n_o_l = n_o_w = n_o_c = 0
for line in f:
n_o_l += 1
n_o_c = len(line)
word = line.split()
n_o_w += len(word)
f.close()
print("Number of lines- ", n_o_l)
print("Number of words- ", n_o_w)
print("Number of characters- ", n_o_c)

Output-
Number of lines- 6
Number of words- 10
Number of characters- 71

# Create an executable file for program statement 1.


Steps for creating executable file of python program-
✓ In python console/command prompt install pyinstaller using link
pip install pystaller
✓ Go to the file location and click on top bar and after selecting link enter CMD.
✓ In command prompt write pyinstaller space file name.
✓ It generate two folders i.e build and dist.
Department of science & Humanities, KGCE, Karjat Page 49
Python Programming (VSEC202) (Lab Manual)

✓ Open dist folder, open file name folder then run .exe file
✓ If this file is not execute then click on file press shift and select open with
command prompt or powershell.
✓ The .exe file will run.

Output-
Number of lines- 6
Number of words- 10
Number of characters- 71

CONCLUSON- In this way we can complete the file handling in terms of read, write operation
and also runs the .exe file.

Department of science & Humanities, KGCE, Karjat Page 50


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 15

EXCEPTION HANDELLING
AIM- Write a Python program that takes two numbers as input and performs division.
Implement exception handling to manage division by zero and invalid input errors gracefully.

OBJECTIVES- To understand the basic concept of different types of exception used when
error created at the time of execution of program.

THEORY- Error that can be solved in runtime is called as exception error. In any programming
language there are following types of errors are available.

✓ Compile time error (syntactical error)- This error occurs because of invalid syntax.
- Syntax error -
- Indentation error
✓ Runtime error- While executing a program if something goes wrong because of end
user input or programming logic or memory problem etc then it is known as runtime
error.
- Index error
- Zero division error
- Type error
✓ Logical error
- EOL syntax error
- FileNotFound error

In python all errors are classes. In python the different types of errors are-
✓ SyntaxError: Raised when there is a syntax error in the Python code
✓ TypeError: Raised when an operation or function is applied to an object of
inappropriate type.
✓ ValueError: Raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value.
✓ IndexError: Raised when trying to access an index that does not exist in a
sequence.
✓ KeyError: Raised when trying to access a key that does not exist in a dictionary.
✓ NameError: Raised when a variable name is not defined.
✓ AttributeError: Raised when trying to access an attribute that does not exist.

Department of science & Humanities, KGCE, Karjat Page 51


Python Programming (VSEC202) (Lab Manual)

✓ IOError: Raised when an input/output operation fails.


✓ ZeroDivisionError: Raised when trying to divide a number by zero.
✓ MemoryError: Creating a large list or array that exceeds the available memory
✓ ImportError: Raised when an import statement fails to find and load the
requested module.

Program-
a = int(input("Enter the first number- "))
b = int(input("Enter the second number- "))
print(a/b)
Output-
if a = 0, b = 4 ------------------ 0.0
if a = 4, b = 0 ------------------ ZeroDivisionError
if a = ‘a’, b = 2 ------------------ ValueError
Any code rises error is called as risky code.
Exception Error- An unwanted & unexpected event that disturb normal flow of program
called exception. It is highly recommended to handle the exceptions. The main objective of
exception handling is graceful termination of program.
Exception handling means not repairing exception. We have to define alternative way
to continue rest of the program normally.
It can be handled by try exception/try catch. It is known as exception handling.

Syntax-
Try :
risky code
except:
exception statement- handler
else/finally:
resource cleanup

Department of science & Humanities, KGCE, Karjat Page 52


Python Programming (VSEC202) (Lab Manual)

Program-
try:
a = int(input("Enter the first number- "))
b = int(input("Enter the second number- "))
print(a/b)
except ZeroDivisionError:
print(“Cant divide by Zero”)
except ValueError:
print(“Please provide only integer value”)
OR
x = int(input("Enter first number- "))
y = int(input("Enter second number- "))
try:
print(x/y)
except (ZeroDivisionError, ValueError) as msg:
print("please provide the valid number- ", msg)

CONCLUSON- In this way we can study and write simple programs for exception handling to
handle different types of error raises during runtime in python.

Department of science & Humanities, KGCE, Karjat Page 53


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 16

PYTHON DEBUGGING

AIM- Demonstrate the use of a Python debugger (e.g., pdb or an IDE with debugging
capabilities) on a sample program with intentional errors.

OBJECTIVES- To understand the basic concept of how to debug a program with different
methods.

THEORY- In Python, a debugger is a tool, specifically the pdb module, that allows you to step
through your code line by line, inspect variables, and identify the root cause of errors or
unexpected behavior. The Python Debugger (pdb) is a built-in module that provides an
interactive debugging environment.

A debugger is a program that can help you find out what is going on in a
computer program. You can stop the execution at any prescribed line number, print out
variables, continue execution, stop again, execute statements one by one, and repeat
such actions until you have tracked down abnormal behaviour and found bugs. Here we
shall use the debugger to demonstrate the program flow of the code

Debugging involves setting breakpoints, stepping through code and inspecting


values. Existing debugging tools can be split into three main types:

• standalone UI applications — for example, PuDB, Winpdb. These are applications


designed specifically for debugging, and the UI is basically the same as in IDE,
which then, in my opinion, is not worth wasting your time. However, you can
always learn more about it by yourself if you’re interested;

• code-in tools, where you set breakpoints by adding temporary code to your
program;

• IDEs. All of the popular modern development environments, such as PyCharm,


Visual Studio, PyDev and many more, have integrated debugging tools, allowing
you to run and inspect the code at the same time.

Department of science & Humanities, KGCE, Karjat Page 54


Python Programming (VSEC202) (Lab Manual)

An IDE (integrated development environment) helps you develop software


efficiently. It combines all of the main functions needed for software development —
code editing, building, running, testing and, finally, debugging. IDEs make debugging
considerably easier so unless you’re a rigid fan of a terminal, I would recommend
trying debugging in an IDE.

Steps for debugging-

✓ Write the python code.

✓ After completion of code, go to run button and execute the program.

✓ If we want to check how the program execute line by line then click on run button
and select the Debug python file.

✓ Select the whole program, press shift+ right click and click on watch so that we
can observe line by line execution.

✓ Insert a breakpoint at any instruction where we want a break.

✓ Run/debug the program to check line by line output.

Program-

def greet():
count = 1
print("Hello KGCE")
print(count)

greet()

i=1
while i <=5:
print(i)
i=i+1
Department of science & Humanities, KGCE, Karjat Page 55
Python Programming (VSEC202) (Lab Manual)

Output-
Hello KGCE
1
2
3
4
5

CONCLUSON- In this way we can check the execution of program line by line and as per out
requirement during runtime in python.

Department of science & Humanities, KGCE, Karjat Page 56


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 17

PYTHON OOPS CONCEPT

AIM- Write a python program to apply OOPS principle.

OBJECTIVES- To understand the basic concept of oops using class..

THEORY- Python is an object oriented programming language.

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

A class is a blueprint for creating objects. It defines the structure and behaviour
that the objects created from the class will have. A class contains attributes (variables)
and methods (functions) that define the properties and actions of the object.

In Python, we define a class using the class keyword:

class Car:
def __init__(self, brand, model): # Constructor
self.brand = brand # Attribute
self.model = model # Attribute

def display_info(self): # Method


print(f"Car Brand: {self.brand}, Model: {self.model}")

An object is an instance of a class. It is a real-world entity that has specific values


assigned to the attributes of the class.

class Car:
def __init__(self, brand, model): # Constructor
self.brand = brand # Attribute
self.model = model # Attribute

Department of science & Humanities, KGCE, Karjat Page 57


Python Programming (VSEC202) (Lab Manual)

def display_info(self): # Method


print(f"Car Brand: {self.brand}, Model: {self.model}")
# Creating an object of the Car class
car1 = Car("Toyota", "Corolla")
car1.display_info()
Output-
Car Brand: Toyota, Model: Corolla
• self represents the instance of the class.
• It is used to access attributes and methods inside the class.
• It must be the first parameter of any instance method.

class Person:
def __init__(self, name, age):
self.name = name # Assigning attribute
self.age = age

def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")

# Creating an object
p1 = Person("Alice", 25)
p1.introduce()

Output-
My name is Alice and I am 25 years old.

You can create multiple objects from the same class:


class Car:
def __init__(self, brand, model): # Constructor
self.brand = brand # Attribute
self.model = model # Attribute
Department of science & Humanities, KGCE, Karjat Page 58
Python Programming (VSEC202) (Lab Manual)

def display_info(self): # Method


print(f"Car Brand: {self.brand}, Model: {self.model}")

car1 = Car("Honda", "Civic")


car2 = Car("Ford", "Mustang")

car1.display_info()
car2.display_info()

Output-

Car Brand: Honda, Model: Civic


Car Brand: Ford, Model: Mustang

CONCLUSON- In this way we can execute the class using constructor in python.

Department of science & Humanities, KGCE, Karjat Page 59


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 18

DESIGNING GRAPHICAL USER INTERFACE (GUI) USING BUILT-IN TOOLS (TKINTER)

AIM- Write a program to demonstrate and implement simple program on designing


graphical user interface(GUI) using built-in tool such as tkinter.

OBJECTIVES- To understand the basic concept of graphical user interface using built-in tools.

THEORY- Python offers multiple options for developing GUI (Graphical User Interface). Out
of all the GUI methods, tkinter is the most commonly used method. It is a standard Python
interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and
easiest way to create the GUI applications.
Creating a GUI using tkinter is an easy task.
To create a tkinter app:

✓ Importing the module – tkinter


✓ Create the main window (container)
✓ Add any number of widgets to the main window
✓ Apply the event Trigger on the widgets.

Importing tkinter is same as importing any other module in the Python code.
Syntax-
import tkinter
There are two main methods used which the user needs to remember while
creating the Python application with GUI.
1. Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a
main window, tkinter offers a method ‘Tk(screenName=None, baseName=None,
className=’Tk’, useTk=1)’. To change the name of the window, you can change the
className to the desired one. The basic code used to create the main window of the
application is:

Department of science & Humanities, KGCE, Karjat Page 60


Python Programming (VSEC202) (Lab Manual)

Syntax-
m= tkinter.Tk() where m is the name of the main window object
2. mainloop : There is a method known by the name mainloop() is used when your
application is ready to run. mainloop() is an infinite loop used to run the application, wait
for an event to occur and process the event as long as the window is not closed.

Syntax-
m.mainloop()
Program-

import tkinter
m = tkinter.Tk()
print("widgets are added here")
m.mainloop()

There are a number of widgets which you can put in your tkinter application.
Some of the major widgets are explained below:
Button: To add a button in your application, this widget is used.

The general syntax is:


w=Button(master, option=value)

master is the parameter used to represent the parent window.

Program-
import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
Department of science & Humanities, KGCE, Karjat Page 61
Python Programming (VSEC202) (Lab Manual)

button = tk.Button(r, text='Start', width=50, command=r.destroy)


button.pack()
r.mainloop()

CheckButton: To select any number of options by displaying a number of options to a


user as toggle buttons.

The general syntax is:


w = CheckButton(master, option=value)
There are number of options which are used to change the format of this widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
• Title: To set the title of the widget.
• activebackground: to set the background color when widget is under the
cursor.
• activeforeground: to set the foreground color when widget is under the
cursor.
• bg: to set the normal backgrouSteganography
Break
Secret Code:
Attach a File:nd color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the widget.

Program-
from tkinter import *
master = Tk()
var1 = IntVar()

Department of science & Humanities, KGCE, Karjat Page 62


Python Programming (VSEC202) (Lab Manual)

Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)


var2 = IntVar()
Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)
mainloop()

Frame: It acts as a container to hold the widgets. It is used for grouping and organizing
the widgets.

The general syntax is:


w = Frame(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas.
Program-

from tkinter import *

root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')

Department of science & Humanities, KGCE, Karjat Page 63


Python Programming (VSEC202) (Lab Manual)

blackbutton.pack( side = BOTTOM)


root.mainloop()

CONCLUSON- In this way we can study and write simple programs for different types of built
in functions for graphical user interface in python.

Department of science & Humanities, KGCE, Karjat Page 64


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 19

VALIDATING MOBILE NUMBER & EMAIL ID

AIM- Write a Python script that prompts the user to enter their phone number and
email ID. It then employs Regular Expressions to verify if these inputs adhere to standard
phone number and email address formats.

OBJECTIVES- To understand the basic concept of regular expression in python for validation
of mobile number and Email address .

THEORY- A RegEx, or Regular Expression, is a sequence of characters that forms a search


pattern. They are commonly used for string searching, validation, and text processing in
programming.
Python has a built-in package called re, which can be used to work with Regular
Expressions.

Import the re module:


import re

Basic Symbols and Their Meanings


Symbol Description Example

Matches any single character (except


. a.b matches acb, axb
newline)

^hello matches "hello world", not


^ Matches the start of a string
"world hello"

world$ matches "hello world", not


$ Matches the end of a string
"world hello"

\d Matches any digit (0-9) \d\d\d matches 123, 456

Department of science & Humanities, KGCE, Karjat Page 65


Python Programming (VSEC202) (Lab Manual)

Symbol Description Example

\D Matches any non-digit character \D\D matches ab, XY

Matches any word character (a-z, A-Z,


\w \w\w\w matches abc, A1B
0-9, _)

\W Matches any non-word character \W\W matches @!, #$

Matches any whitespace (space, tab,


\s a\s\sb matches a b
newline)

Matches any non-whitespace


\S \S\S matches ab, 1@
character

Quantifiers (Repetition)

Symbol Description Example

* Matches 0 or more occurrences ab*c matches ac, abc, abbc

+ Matches 1 or more occurrences ab+c matches abc, abbc, but not ac

? Matches 0 or 1 occurrence (optional) colou?r matches color and colour

{n} Matches exactly n occurrences \d{3} matches 123, 456

{n,} Matches at least n occurrences \d{2,} matches 12, 45678

{n,m} Matches between n and m occurrences \d{2,4} matches 12, 123, 1234

Character Sets and Groups-

Department of science & Humanities, KGCE, Karjat Page 66


Python Programming (VSEC202) (Lab Manual)

Symbol Description Example

[abc] Matches any one of a, b, or c [aeiou] matches any vowel

[^abc] Matches any character except a, b, or c [^0-9] matches non-digit characters

[a-z] Matches any lowercase letter from a to z [a-zA-Z] matches any letter

(abc) Groups characters together (ab)+ matches ab, abab

Anchors and Assertions-


Symbol Description Example

\bhello\b matches hello but not


\b Matches a word boundary
helloworld

\Bworld matches "helloworld" but not


\B Matches non-word boundary
"world"

Positive lookahead (ensures


(?=...) a(?=b) matches a if followed by b
presence)

Negative lookahead (ensures


(?!...) a(?!b) matches a if not followed by b
absence)

Common Regex Patterns-

Pattern Description Example Matches

Matches a 10-digit phone


^\d{10}$ 9876543210
number

Department of science & Humanities, KGCE, Karjat Page 67


Python Programming (VSEC202) (Lab Manual)

Pattern Description Example Matches

^[\w\.-]+@[\w\.-
Matches an email address user@example.com
]+\.\w{2,}$

Matches an HTTP/HTTPS http://google.com,


https?://[\w\.-]+
URL https://example.org

Matches a date in
\b\d{1,2}/\d{1,2}/\d{4}\b 12/05/2023
DD/MM/YYYY format

Matches "password" case-


(?i)password Password, pAsSwOrD
insensitively

The re.match() Function

This function attempts to match RE pattern at the start of string with optional flags.
Following is the syntax for this function −

re.match(pattern, string, flags=0)

Here is the description of the parameters –

Sr.No. Parameter & Description

pattern
1
This is the regular expression to be matched.

String
2 This is the string, which would be searched to match the pattern at the
beginning of string.

Flags
3 You can specify different flags using bitwise OR (|). These are modifiers,
which are listed in the table below.

Department of science & Humanities, KGCE, Karjat Page 68


Python Programming (VSEC202) (Lab Manual)

The re.match() function returns a match object on success, None on failure. A


match object instance contains information about the match: where it starts and ends,
the substring it matched, etc.

The match object's start() method returns the starting position of pattern in the
string, and end() returns the endpoint.

If the pattern is not found, the match object is None.

We use group(num) or groups() function of match object to get matched


expression.

Sr.No. Match Object Methods & Description

group(num=0)This method returns entire match (or specific subgroup


1
num)

groups()This method returns all matching subgroups in a tuple (empty if


2
there weren't any)

The search() Function

The search() function searches the string for a match, and returns a Match
object if there is a match.

If there is more than one match, only the first occurrence of the match will be
returned:

import re

txt = "The rain in Spain"


x = re.search("\s", txt)

print("The first white-space character is located in position:", x.start())

Output-

The first white-space character is located in position: 3

Department of science & Humanities, KGCE, Karjat Page 69


Python Programming (VSEC202) (Lab Manual)

The split() Function-

The split() function returns a list where the string has been split at each match:

import re

txt = "The rain in Spain"


x = re.split("\s", txt)
print(x)

Output-

['The', 'rain', 'in', 'Spain']

The sub() Function

The sub() function replaces the matches with the text of your choice:

1. Phone Number Validation:

Regular Expression Used:

r"^\d{10}$"

• ^ → Matches the start of the string.


• \d{10} → Matches exactly 10 digits (\d represents a digit, and {10} specifies that it
should be exactly 10 digits).
• $ → Matches the end of the string.
• Valid examples: 9876543210, 1234567890
• Invalid examples: 98765 (too short), 98765432101 (too long), abcd123456 (contains
non-numeric characters)

Department of science & Humanities, KGCE, Karjat Page 70


Python Programming (VSEC202) (Lab Manual)

2. Email Address Validation:


r"^[\w\.-]+@[\w\.-]+\.\w+$"
• ^ → Matches the start of the string.
• [\w\.-]+ → Matches one or more alphanumeric characters (\w), dots (.), or hyphens
(-) before the @ symbol.
• @ → Matches the @ symbol.
• [\w\.-]+ → Matches the domain name (e.g., gmail, yahoo).
• \. → Matches the dot (.) before the domain extension (e.g., .com, .org).
• \w+ → Matches the domain extension (e.g., com, edu, net).
• $ → Matches the end of the string.
• Valid examples: example@gmail.com, user.name-123@domain.org
• Invalid examples: user@com (missing domain), user@domain. (missing extension),
user#email.com (invalid character #)
PROGRAM-
# Write a Python script that prompts the user to enter their phone number and email ID.
It then employs Regular Expressions to verify if these inputs adhere to standard phone
number and email address formats.
import re

phone = input("Enter your phone number: ")


email = input("Enter your email ID: ")

# Validate phone number (10 digits)


if re.match(r"^\d{10}$", phone):
print("Valid phone number.")
else:
print("Invalid phone number.")

Department of science & Humanities, KGCE, Karjat Page 71


Python Programming (VSEC202) (Lab Manual)

# Validate email address


if re.match(r"^[\w\.-]+@[\w\.-]+\.\w+$", email):
print("Valid email address.")
else:
print("Invalid email address.")

Output:
Enter your phone number: 9452124768
Enter your email ID: abc@gmail.com
Valid phone number.
Valid email address.

Enter your phone number: 23456


Enter your email ID: abcgmail.com
Invalid phone number.
Invalid email address.

Enter your phone number: 9452124768


Enter your email ID: abcgmail.com
Valid phone number.
Invalid email address.

Enter your phone number: 12345


Enter your email ID: abc@gmail.com
Invalid phone number.
Valid email address.

CONCLUSON- In this way we can validate mobile number and email id of member in python.

Department of science & Humanities, KGCE, Karjat Page 72


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 20

CREATING A MANUPULATING ARRAY

AIM- Write a Python program to create a 1D, 2D, and 3D NumPy array. Perform basic
operations like reshaping, slicing, and indexing.

OBJECTIVES- To understand the basic concept of Numpy for creation of array.

THEORY-
NumPy array in Python:
Python lists are a substitute for arrays, but they fail to deliver the performance
required while computing large sets of numerical data. To address this issue we use a
python library called NumPy. The word NumPy stands for Numerical Python.
• Unlike lists, NumPy arrays are of fixed size, and changing the size of an array will
lead to the creation of a new array while the original array will be deleted.
• All the elements in an array are of the same type.
• Numpy arrays are faster, more efficient, and require less syntax than standard
python sequences.

Numpy array from a list


You can use the np alias to create nd array of a list using the array() method.
li = [1,2,3,4]
numpyArr = np.array(li)
or
numpyArr = np.array([1,2,3,4])

The list is passed to the array() method which then returns a NumPy array with the
same elements.

Department of science & Humanities, KGCE, Karjat Page 73


Python Programming (VSEC202) (Lab Manual)

Creation of arrays using Numpy:


Creation of 1-D array:
import numpy as np

arr = np.array([1, 2, 3, 4, 5])


print(arr)
Creation of 2-D array:
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])


print(arr)
Creation of 3-D array:
import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])


print(arr)
Array Indexing: Knowing the basics of array indexing is important for analysing and
manipulating the array object. NumPy offers many ways to do array indexing.
Slicing: Just like lists in python, NumPy arrays can be sliced. As arrays can be
multidimensional, you need to specify a slice for each dimension of the array.

PROGRAM-
# Write a python Program to create 1D,2D and 3D Numpy Array. Perform basic operation like
reshaping, slicing and indexing

import numpy as np
# Creating 1D, 2D, and 3D NumPy arrays
array_1d = np.array([1, 2, 3, 4, 5])
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
array_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print("1D Array:")
print(array_1d)

Department of science & Humanities, KGCE, Karjat Page 74


Python Programming (VSEC202) (Lab Manual)

print("\n2D Array:")
print(array_2d)
print("\n3D Array:")
print(array_3d)

Output-
1D Array:
[1 2 3 4 5]

2D Array:
[[1 2 3]
[4 5 6]
[7 8 9]]

3D Array:
[[[ 1 2 3]
[ 4 5 6]]

[[ 7 8 9]
[10 11 12]]]

# Reshaping Arrays
reshaped_1d = array_1d.reshape((5, 1))
print("\nReshaped 1D to 5x1:")
print(reshaped_1d)
reshaped_2d = array_2d.reshape((1, 9))
print("\nReshaped 2D to 1x9:")
print(reshaped_2d)

Output-
Reshaped 1D to 5x1:
[[1]

Department of science & Humanities, KGCE, Karjat Page 75


Python Programming (VSEC202) (Lab Manual)

[2]
[3]
[4]
[5]]

Reshaped 2D to 1x9:
[[1 2 3 4 5 6 7 8 9]]
# Slicing Arrays
slice_1d = array_1d[1:4] # Elements from index 1 to 3
print("\nSliced 1D Array (index 1 to 3):")
print(slice_1d)
slice_2d = array_2d[:, 1] # Second column from 2D array
print("\nSliced 2D Array (Second column):")
print(slice_2d)
slice_3d = array_3d[:, 0, :] # First row of each 2D matrix in 3D array
print("\nSliced 3D Array (First row from each 2D matrix):")
print(slice_3d)

Output-
Sliced 1D Array (index 1 to 3):
[2 3 4]

Sliced 2D Array (Second column):


[2 5 8]

Sliced 3D Array (First row from each 2D matrix):


[[1 2 3]
[7 8 9]]
# Indexing-
index_1d = array_1d[2]
print("\nIndexing 1D Array (Element at index 2):")
print(index_1d)

Department of science & Humanities, KGCE, Karjat Page 76


Python Programming (VSEC202) (Lab Manual)

index_2d = array_2d[1, 1]
print("\nIndexing 2D Array (Element at row 1, column 1):")
print(index_2d)
index_3d = array_3d[1, 0, 2]
print("\nIndexing 3D Array (Element at [1,0,2]):")
print(index_3d)

Output:
Indexing 1D Array (Element at index 2):
3
Indexing 2D Array (Element at row 1, column 1):
5
Indexing 3D Array (Element at [1,0,2]):
9

PROGRAM 2:
# Develop A python program to create 2D arrays of same shape perform all Arithmatic
operation and calculate the dot product of two vectors.

import numpy as np
# Creating 2D arrays of the same shape
array_2d_1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
array_2d_2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

# Performing Arithmetic Operations


print( array_2d_1 + array_2d_2)
print( array_2d_1 - array_2d_2)
print(array_2d_1 * array_2d_2)
print(array_2d_1 / (array_2d_2 + 1e-9)) # Avoiding division by zero

# Dot Product of Two Vectors


vector_1 = np.array([1, 2, 3])
Department of science & Humanities, KGCE, Karjat Page 77
Python Programming (VSEC202) (Lab Manual)

vector_2 = np.array([4, 5, 6])


dot_product = np.dot(vector_1, vector_2)
print(dot_product)

Output-

[[10 10 10]
[10 10 10]
[10 10 10]]
[[-8 -6 -4]
[-2 0 2]
[ 4 6 8]]
[[ 9 16 21]
[24 25 24]
[21 16 9]]
[[0.11111111 0.25 0.42857143]
[0.66666667 1. 1.5 ]
[2.33333333 4. 8.99999999]]
32

CONCLUSON- In this way we can perform different operations on 1D, 2D and 3D array using
Numpy in python.

Department of science & Humanities, KGCE, Karjat Page 78


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 21

PANDAS IN PYTHON

AIM- Write a Python program to implement Pandas library of given dataset.

OBJECTIVES- To understand the basic concept of Pandas for creation of CSV files using data.

THEORY-
Pandas is a Python package providing fast, flexible, and expressive data structures
designed to make working with “relational” or “labeled” data both easy and intuitive. It aims
to be the fundamental high-level building block for doing practical, real-world data analysis
in Python.
• Pandas is an open-source library that is made mainly for working with relational
or labeled data both easily and intuitively.
• It provides various data structures and operations for manipulating numerical
data and time series.
• Pandas builds on packages like Numpy & matplotlib to give us a single and
convenient place for data analysis and visualization.
• Pandas is fast and it has high performance & productivity for users.
FEATURES OF PANDAS:
• Fast and efficient for manipulating and analyzing data.
• Data from different file objects can be loaded.
• Easy handling of missing data (represented as NaN) in floating point as well as
non- floating point data
• Size mutability: columns can be inserted and deleted from DataFrame and higher
dimensional objects
• Data set merging and joining.
• Flexible reshaping and pivoting of data sets
• Data alignment & integrated handling of missing data
• Label-based slicing & indexing.
• Provides time-series functionality.

Department of science & Humanities, KGCE, Karjat Page 79


Python Programming (VSEC202) (Lab Manual)

• Powerful group by functionality for performing split-apply-combine operations on


data sets.
Pandas generally provide two data structures for manipulating data, They are:
• Series
• DataFrame
• Series:
Pandas Series is a one-dimensional labeled array capable of holding data of any type
(integer, string, float, python objects, etc.)i.e. Homogenous data.
• The axis labels are collectively called indexes.
Pandas Series is nothing but a column in an excel sheet. Labels need not be
unique but must be a hashable type.
• The object supports both integer and label-based indexing and provides a host of
methods for performing operations involving the index.
• Pandas series Size is immutable and data is immutable

Syntax:
pandas.Series(data,index,datatype,copy)

• Series can be created using:


1. Array
2. Dictionary
3. Scalar Value or Constant.

DataFrame:
Pandas DataFrame is a two-dimensional size-mutable, potentially Heterogeneous
tabular data structure with labelled axes (rows and columns).
• A Data frame is a n-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.

Department of science & Humanities, KGCE, Karjat Page 80


Python Programming (VSEC202) (Lab Manual)

• Basic Features:
1.Heterogeneous Data.
2.Size Mutable.
3.Data Mutable.

Syntax:
pandas.DataFrame(data,index,colums,datatype,copy)

• DataFrame can be created with:


1. List , 2. Dictionary, 3.Series, 4.Numpy ndarrays, 5.Another DataFrame

PROGRAM-
# Load a CSV file containing information on global COVID-19 cases into a
DataFrame.Display the few rows, check the data type, and summarize basic statistics.
global_covid19_cases.csv
Date Country Confirmed Deaths Recovered
01-01-20 Russia 53251 4107 7393
02-01-20 UK 23662 4747 47833
03-01-20 Brazil 9392 864 3936
04-01-20 UK 31535 3484 74790
05-01-20 UK 79603 1717 76713
06-01-20 India 53256 2787 6395
07-01-20 Brazil 90135 1743 20238
08-01-20 Brazil 36222 4941 31246
09-01-20 Brazil 78373 3520 49877
10-01-20 UK 80575 212 48904
11-01-20 Russia 97354 3265 54545
12-01-20 Brazil 85651 4228 40290
13-01-20 UK 64335 4506 6100
14-01-20 India 11965 776 41264

Department of science & Humanities, KGCE, Karjat Page 81


Python Programming (VSEC202) (Lab Manual)

15-01-20 Russia 25538 4399 75043


16-01-20 India 71592 2337 46214
17-01-20 Russia 99018 2941 57335
18-01-20 UK 9110 207 74244
19-01-20 USA 80309 1940 56991
20-01-20 Russia 28266 3592 19089
21-01-20 India 53992 618 43984
22-01-20 UK 83948 3282 36712
23-01-20 Russia 99806 1157 44025
24-01-20 USA 7910 4292 47702
25-01-20 USA 91982 3407 33135
26-01-20 Brazil 1206 2521 63708
27-01-20 Brazil 88054 1804 34328
28-01-20 India 88897 669 19211
29-01-20 Russia 24419 2821 3920
30-01-20 Russia 51636 1379 801
31-01-20 Brazil 51015 1996 45736
01-02-20 Russia 55268 156 66735
02-02-20 Russia 88939 3229 54740
03-02-20 USA 19141 2921 66226
04-02-20 Brazil 81356 1744 10992
05-02-20 UK 72910 1853 6602
06-02-20 Brazil 57044 498 50836
07-02-20 UK 68214 2986 27141
08-02-20 USA 34827 1969 35084
09-02-20 India 56820 2395 33245
10-02-20 Russia 63623 2929 23593
11-02-20 USA 82734 4746 66605
12-02-20 Russia 76450 1812 52385
13-02-20 India 94426 4071 37131
14-02-20 India 23299 3379 73491

Department of science & Humanities, KGCE, Karjat Page 82


Python Programming (VSEC202) (Lab Manual)

15-02-20 USA 44585 272 4514


16-02-20 India 65044 633 11593
17-02-20 UK 43557 1026 18570
18-02-20 India 50080 3653 36277
19-02-20 Russia 3693 4986 57458
20-02-20 Russia 96003 2059 11229
21-02-20 Russia 96259 3733 45517
22-02-20 Russia 70163 4558 66820
23-02-20 UK 26939 3118 28251
24-02-20 Brazil 49925 4100 78569
25-02-20 USA 43941 2066 55248
26-02-20 Russia 22834 3180 6301
27-02-20 India 19047 1692 19690
28-02-20 Russia 27105 2265 50189
29-02-20 India 76766 1164 51493
01-03-20 India 16707 4509 30092
02-03-20 Russia 22976 3201 11147
03-03-20 UK 45262 1706 9216
04-03-20 India 24776 4001 70816
05-03-20 India 31080 4733 2868
06-03-20 Russia 67842 4692 78075
07-03-20 India 62373 1658 7155
08-03-20 India 7776 1455 70531
09-03-20 Russia 93787 4209 76929
10-03-20 Russia 56016 3933 56266
11-03-20 USA 10474 263 13903
12-03-20 UK 59053 3193 32597
13-03-20 UK 22959 2567 79157
14-03-20 India 6530 108 11466
15-03-20 UK 95856 2210 53421
16-03-20 India 4748 2971 50226

Department of science & Humanities, KGCE, Karjat Page 83


Python Programming (VSEC202) (Lab Manual)

17-03-20 USA 98504 4983 50800


18-03-20 Russia 99098 4443 23177
19-03-20 Russia 14545 3787 56109
20-03-20 Russia 67199 2879 57161
21-03-20 UK 35766 3244 31524
22-03-20 USA 74530 3801 70813
23-03-20 UK 94557 966 53506
24-03-20 UK 62087 4077 15838
25-03-20 USA 96839 170 68527
26-03-20 USA 69840 4503 20008
27-03-20 USA 55384 1310 3551
28-03-20 USA 52005 4921 49247
29-03-20 Russia 47576 3997 54521
30-03-20 Brazil 40353 1537 66912
31-03-20 Brazil 63003 1228 58835
01-04-20 USA 84211 4506 56679
02-04-20 Brazil 53733 4745 32593
03-04-20 Brazil 66318 3114 70178
04-04-20 USA 90474 2745 40234
05-04-20 Brazil 24664 4565 73115
06-04-20 UK 68172 964 74023
07-04-20 India 86616 4575 17519
08-04-20 India 94264 3456 74347
09-04-20 USA 27736 1055 28751

#Loading CSV file containing COVID-19 cases


import pandas as pd
data = pd.read_csv(r"E:\Python\global_covid19_cases.csv")
# Display first few rows
print("\nFirst few rows of the dataset:")
print(data.head())

Department of science & Humanities, KGCE, Karjat Page 84


Python Programming (VSEC202) (Lab Manual)

# Checking data types


print("\nData Types:")
print(data.dtypes)
# Summarizing some attributes
print("\nSummary Statistics:")
print(data.describe())
Output:

Department of science & Humanities, KGCE, Karjat Page 85


Python Programming (VSEC202) (Lab Manual)

# Write a python program to study and understand merging, joining, and


concatenation in pandas DataFrame.
import pandas as pd
data1=pd.DataFrame({'id':[1,2,3,4],'name':['Manoj','Kranti','Gauri','Vishal']},index=['one'
,'two', 'three','four'])
data2=pd.DataFrame({'s_id':[1,2,3,6,7],'marks':[98,90,78,86,78]},index=['one','two','thre
e', 'four','seven'])

#Method of joining DataFrames based on indexes.


print("Joined DataFrame is as follow:")
print(data1.join(data2))
#To merge DataFrames with Matching Indexes
print("Merged DataFrame is as follow:")
print(pd.merge(data1,data2,left_index=True,right_index=True))
#To concate the DataFrames
print("Concatenation:")
print(pd.concat([data1,data2],axis=1))
Output:

Department of science & Humanities, KGCE, Karjat Page 86


Python Programming (VSEC202) (Lab Manual)

CONCLUSON- In this way we can perform different operations on CSV files using Pandas in
python.

Department of science & Humanities, KGCE, Karjat Page 87


Python Programming (VSEC202) (Lab Manual)

EXPERIMENT NO. 22

MATPLOTLIB IN PYTHON

AIM- Write a Python program to implement Matplotlib library of given dataset.

OBJECTIVES- To understand the basic concept of Matplotlib for data science.

THEORY-
Matplotlib is a popular data visualization library in Python. It's often used for
creating static, interactive, and animated visualizations in Python. Matplotlib allows you
to generate plots, histograms, bar charts, scatter plots, etc., with just a few lines of
code.
Example of a Plot in Matplotlib:
import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.plot(x, y)
plt.show()

Department of science & Humanities, KGCE, Karjat Page 88


Python Programming (VSEC202) (Lab Manual)

Different Types of Plots in Matplotlib-


Matplotlib offers a wide range of plot types to suit various data visualization needs.
1. Line Graph
2. Bar Chart
3. Histogram
4. Scatter Plot
5. Pie Chart
6. 3D Plot

1. Line Plot
Line charts are used to represent the relation between two data X and Y on a different axis.
import matplotlib.pyplot as plt
import numpy as np

# define data values


x = np.array([1, 2, 3, 4]) # X-axis points
y = x*2 # Y-axis points
plt.plot(x, y) # Plot the chart
plt.show() # display

2. Bar Chart-
A bar plot uses rectangular bars to represent data categories, with bar length or
height proportional to their values. It compares discrete categories, with one axis for
categories and the other for values.

Department of science & Humanities, KGCE, Karjat Page 89


Python Programming (VSEC202) (Lab Manual)

import matplotlib.pyplot as plt


import numpy as np

fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']


sales = [400, 350, 300, 450]

plt.bar(fruits, sales)
plt.title('Fruit Sales')
plt.xlabel('Fruits')
plt.ylabel('Sales')
plt.show()

3. Histogram-
Histograms are a fundamental tool in data visualization, providing a graphical
representation of the distribution of data. They are particularly useful for exploring
continuous data, such as numerical measurements or sensor readings.

import matplotlib.pyplot as plt


import numpy as np

# Generate random data for the histogram


data = np.random.randn(1000)

Department of science & Humanities, KGCE, Karjat Page 90


Python Programming (VSEC202) (Lab Manual)

# Plotting a basic histogram


plt.hist(data, bins=30, color='skyblue', edgecolor='black')

# Adding labels and title


plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Basic Histogram')

# Display the plot


plt.show()

4. Scatter Plot-
matplotlib.pyplot.scatter() is used to create scatter plots, which are essential for visualizing
relationships between numerical variables. Scatter plots help illustrate how changes in one
variable can influence another, making them invaluable for data analysis.
import matplotlib.pyplot as plt
import numpy as np

x = np.array([12, 45, 7, 32, 89, 54, 23, 67, 14, 91])

Department of science & Humanities, KGCE, Karjat Page 91


Python Programming (VSEC202) (Lab Manual)

y = np.array([99, 31, 72, 56, 19, 88, 43, 61, 35, 77])

plt.scatter(x, y)
plt.show()

5. Pie chart-
A Pie Chart is a circular statistical plot that can display only one series of data. The
area of the chart is the total percentage of the given data. Pie charts in Python are widely
used in business presentations, reports, and dashboards due to their simplicity and
effectiveness in displaying data distributions.
# Import libraries
from matplotlib import pyplot as plt
import numpy as np

# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]

Department of science & Humanities, KGCE, Karjat Page 92


Python Programming (VSEC202) (Lab Manual)

# Creating plot
fig = plt.figure(figsize=(10, 7))
plt.pie(data, labels=cars)

# show plot
plt.show()

6. 3 D plot-
3D plots are very important tools for visualizing data that have three dimensions
such as data that have two dependent and one independent variable. By plotting data in 3d
plots we can get a deeper understanding of data that have three variables.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')

Department of science & Humanities, KGCE, Karjat Page 93


Python Programming (VSEC202) (Lab Manual)

Program Code-
Using the Cars Data (https://www.kaggle.com/datasets/nameeerafatima/toyotacsv) perform
the following tasks:
✓ Create a scatter plot between the Age and Price of the cars to illustrate how the price
decreases as the age of the car increases.
✓ Generate a histogram to show the frequency distribution of kilometres driven by the
cars.
✓ Produce a bar plot to display the distribution of cars by fuel type.
✓ Create a pie chart to represent the percentage distribution of cars based on fuel types.
✓ Draw a box plot to visualize the distribution of car prices across different fuel types.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Load dataset
df = pd.read_csv("E:/Vinita/Python/Toyota.csv").dropna(subset=["Age", "Price", "KM",
"FuelType"])

# Scatter Plot: Age vs Price


sns.scatterplot(x=df["Age"], y=df["Price"], alpha=0.6)
plt.title("Age vs Price")
plt.xlabel("Age of the Car")
plt.ylabel("Price of the Car")
plt.show()

# Histogram: Kilometers Driven


sns.histplot(df["KM"], bins=30, kde=True, color="blue")
plt.title("Kilometers Driven Distribution")
plt.xlabel("Kilometers Driven")
plt.ylabel("Frequency")
plt.show()
Department of science & Humanities, KGCE, Karjat Page 94
Python Programming (VSEC202) (Lab Manual)

# Bar Plot: Fuel Type Distribution


sns.countplot(x=df["FuelType"], palette="viridis")
plt.title("Cars by Fuel Type")
plt.xlabel("Fuel Type")
plt.ylabel("Count")
plt.show()

# Pie Chart: Fuel Type Percentage


df["FuelType"].value_counts().plot.pie(autopct="%1.1f%%",
colors=sns.color_palette("pastel"))
plt.title("Fuel Type Distribution")
plt.ylabel("")
plt.show()

# Box Plot: Price vs Fuel Type


sns.boxplot(x=df["FuelType"], y=df["Price"], palette="coolwarm")
plt.title("Car Prices by Fuel Type")
plt.xlabel("Fuel Type")
plt.ylabel("Price")
plt.show()

Output:-

Department of science & Humanities, KGCE, Karjat Page 95


Python Programming (VSEC202) (Lab Manual)

CONCLUSON- In this way we can perform different operations on data files using Matplotlib in
python.

Department of science & Humanities, KGCE, Karjat Page 96

You might also like