Python_Programming_LabManuals
Python_Programming_LabManuals
LAB MANUALS
Department- First Year Engineering
Semester- II (NEP-2020)
Course- F.E. (All Branches)
Subject Name- Python Programming (VSEC 202)
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.
9. Develop a Python program that takes a numerical input and identifies whether it
is even or odd, utilizing conditional statements and loops.
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.
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.
• Students should make an entry in the log book whenever they enter
the labs during practical or for their own personal work.
LAB OBJECTIVES-
➢ To write, test, and debug simple Python programs.
LAB OUTCOMES-
Upon completion of the course, students will be able to-
EXPERIMENT NO.
OBJECTIVES- To study the installation of python and set the path for environment.
➢ 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.
➢ 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.
✓ 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.
✓ To exit from the command line of Python, press Ctrl+z followed by Enter or Enter
exit() or quit() and Enter.
➢ Once the installer launches, accept the license agreement and then click Next-
➢ Accept the default location for installation and then click Next-
➢ 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-
➢ Click Finish to exit the installation and (by default) lauch the Visual Studio Code.
CONCLUSON- In this way we can install the python and VS code integrated development
environment.
EXPERIMENT NO. 01 to 03
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”.
In this program we will use the input and output instruction, the syntax for input and
output instructions are-
Input syntax-
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-
Output-
# 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.
Output-
CONCLUSON- In this way we can generate the personalized greeting with the help of input and
output statements.
EXPERIMENT NO. 04
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-
✓Arithmetic Operators
✓Comparison Operators
✓Logical Operators
✓Bitwise Operators
✓Assignment Operators
✓Identity Operators and Membership Operators
Program-
a = int(input(“Enter the first number- “)
b = int(input(“Enter the second number- “)
# 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-
CONCLUSON- In this way we can study and write simple programs for arithmetic operations in
python.
EXPERIMENT NO. 05
AIM- Develop a Python program to manage a task list using lists and tuples, including
adding, removing, updating, and sorting tasks.
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
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
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
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.
EXPERIMENT NO. 06
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
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.
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)
# 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)
# 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.
EXPERIMENT NO. 07
AIM- Write a Python program to create, update, and manipulate a dictionary of student
records, including their grades and attendance.
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-
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)
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.
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-
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 – 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.
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.
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
LOOP-
Iterative statements-
✓ 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.
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.
PROGRAM-
# Program to find Even or Odd number using conditional statement and loop
Output-
Output-
Program-
*
* *
* * *
* * * *
* * * * *
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.
FUNCTIONS
AIM- Write a program to demonstrate functions for finding prime number and
calculator in Python.
THEORY-
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..
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-
• 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-
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-
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
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.
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
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.
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.
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.
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.
else:
print("File does not exists", fname)
sys.exit(0)
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.
Output-
Number of lines- 6
Number of words- 10
Number of characters- 71
✓ 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.
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.
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
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.
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
• code-in tools, where you set breakpoints by adding temporary code to your
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.
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.
EXPERIMENT NO. 17
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.
class Car:
def __init__(self, brand, model): # Constructor
self.brand = brand # Attribute
self.model = model # Attribute
class Car:
def __init__(self, brand, model): # Constructor
self.brand = brand # Attribute
self.model = model # Attribute
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.
car1.display_info()
car2.display_info()
Output-
CONCLUSON- In this way we can execute the class using constructor in python.
EXPERIMENT NO. 18
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 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:
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.
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)
Program-
from tkinter import *
master = Tk()
var1 = IntVar()
Frame: It acts as a container to hold the widgets. It is used for grouping and organizing
the widgets.
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')
CONCLUSON- In this way we can study and write simple programs for different types of built
in functions for graphical user interface in python.
EXPERIMENT NO. 19
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 .
Quantifiers (Repetition)
{n,m} Matches between n and m occurrences \d{2,4} matches 12, 123, 1234
[a-z] Matches any lowercase letter from a to z [a-zA-Z] matches any letter
^[\w\.-]+@[\w\.-
Matches an email address user@example.com
]+\.\w{2,}$
Matches a date in
\b\d{1,2}/\d{1,2}/\d{4}\b 12/05/2023
DD/MM/YYYY format
This function attempts to match RE pattern at the start of string with optional flags.
Following is the syntax for this function −
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.
The match object's start() method returns the starting position of pattern in the
string, and end() returns the endpoint.
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
Output-
The split() function returns a list where the string has been split at each match:
import re
Output-
The sub() function replaces the matches with the text of your choice:
r"^\d{10}$"
Output:
Enter your phone number: 9452124768
Enter your email ID: abc@gmail.com
Valid phone number.
Valid email address.
CONCLUSON- In this way we can validate mobile number and email id of member in python.
EXPERIMENT NO. 20
AIM- Write a Python program to create a 1D, 2D, and 3D NumPy array. Perform basic
operations like reshaping, slicing, and indexing.
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.
The list is passed to the array() method which then returns a NumPy array with the
same elements.
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)
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]
[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]
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]])
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.
EXPERIMENT NO. 21
PANDAS IN PYTHON
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.
Syntax:
pandas.Series(data,index,datatype,copy)
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.
• Basic Features:
1.Heterogeneous Data.
2.Size Mutable.
3.Data Mutable.
Syntax:
pandas.DataFrame(data,index,colums,datatype,copy)
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
CONCLUSON- In this way we can perform different operations on CSV files using Pandas in
python.
EXPERIMENT NO. 22
MATPLOTLIB IN PYTHON
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()
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
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.
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.
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
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']
# 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')
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"])
Output:-
CONCLUSON- In this way we can perform different operations on data files using Matplotlib in
python.