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

py

The document outlines a programming lab course in Python for students at Maharaja Agrasen Institute of Technology, detailing various practical experiments to be conducted. Each experiment focuses on different programming concepts such as data types, conditional statements, loops, and GUI programming, along with their theoretical backgrounds and expected outcomes. The document serves as a record for students to track their progress and marks in the lab exercises.

Uploaded by

Ansh Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

py

The document outlines a programming lab course in Python for students at Maharaja Agrasen Institute of Technology, detailing various practical experiments to be conducted. Each experiment focuses on different programming concepts such as data types, conditional statements, loops, and GUI programming, along with their theoretical backgrounds and expected outcomes. The document serves as a record for students to track their progress and marks in the lab exercises.

Uploaded by

Ansh Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

PROGRAMMING IN PYTHON LAB

(PAPER CODE: CIE-332P)

Faculty Name: Dr. Nidhi Sengar Student Name: Ansh Gupta


Designation: Assistant professor Roll No.: 00314807723
Semester: 6th FSD-III-A(IT)
Batch: 2022-26

Department of Information Technology


Maharaja Agrasen Institute of Technology, PSP area,
Sector-22, Rohini, New Delhi -110085
PROGRAMMING IN PYTHON LAB PRACTICAL

RECORD

PAPER CODE : CIE-332P

Name of the student : Ansh Gupta

University Roll No. 00314807723

Branch : IT

Section/ Group : FSD-III-A

PRACTICAL DETAILS

Experi Date Experiment Name Marks (0-3) Total Signature


ment Marks
No. (15)

R1 R2 R3 R4 R5

1. Basic data types and operators: Create


a program that prompts the user for
their name and age and prints a
personalized message.
2. Conditional statements: Create a
program that prompts the user for their
age and tells them if they can vote in
the next election.
3. Loops: Create a program that
calculates the factorial of a number
entered by the user using a loop.

4. Lists and arrays: Create a program that


prompts the user for a list of numbers
and then sorts them in ascending
order.
5. Strings and string manipulation:
Create a program that prompts the user
for a string and then prints out the
string reversed.
6. Functions: Create a program that
defines a function to calculate the
area of a circle based on the radius
entered by the user.
7. Classes and objects: Create a program
that defines a class to represent a car
and then creates an object of that class
with specific attributes.
8. File input/output: Create a program that
reads data from a file and writes it to
another file in a different format.

9. Regular expressions: Create a program


that uses regular expressions to find all
instances of a specific pattern in a text
file.
10. Exception handling: Create a program
that prompts the user for two numbers
and then divides them, handling any
exceptions that may arise.

a) Experiments beyond the list provided by GGSIPU

Experiment Date Experiment Name Marks (0-3) Total Signature


No. Marks (15)

R1 R2 R3 R4 R5

1. GUI programming: Create a


program that uses a graphical
user interface (GUI) to allow the
user to perform simple
calculations.
2. Web scraping: Create a program
that uses a web scraping library
to extract data from a website
and then stores it in a database.
3. Data visualization: Create a
program that reads data from a
file and then creates a
visualization of that data using a
data visualization library.
4. Machine learning: Create a
program that uses a machine
learning library to classify
images based on their content.
5. Networking: Create a program
that uses a networking library
to communicate with a server
and retrieve data from it.
EXPERIMENT - 1

AIM – Basic data types and operators: Create a program that prompts the user for their
name and age and prints a personalized message.

THEORY - Basic Data Types and Operators in Python:


Python provides several built-in data types to handle different kinds of data:

1. String (str): A sequence of characters used to represent text (e.g., names, messages).
2. Integer (int): Whole numbers without a fractional part (e.g., age, count).
3. Float (float): Numbers with a fractional part (e.g., 3.14, 2.5).
4. Boolean (bool): Represents truth values (True or False).
Operators are symbols used to perform operations on data. Some common types are:
1. Arithmetic Operators: Perform mathematical calculations (+, -, *, /, %, etc.).
2. Relational Operators: Compare values (==, !=, <, >, etc.).
3. Assignment Operators: Assign values to variables (=, +=, -=, etc.).
4. String Concatenation: The + operator can combine strings.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 2

AIM – Conditional statements: Create a program that prompts the user for their age and tells them if
they can vote in the next election.

THEORY - Conditional Statements in Python


Conditional statements are used to execute code based on specific conditions. These
conditions are evaluated as True or False, and the program decides which block of code to
run accordingly.
Key Components of Conditional Statements:
1. if Statement: Executes a block of code if a condition is true.
2. elif (Else If): Checks additional conditions if the previous ones are false.
3. else Statement: Executes a block of code if all conditions are false.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 3

AIM – Loops: Create a program that calculates the factorial of a number entered by the user using a
loop.

THEORY -- Loops and Factorials in Python

Loops are control structures used to repeatedly execute a block of code as long as a
the condition is true. Python provides two main types of loops:
1. for Loop: Iterates over a sequence (e.g., list, range, string) a fixed number of times.
2. while Loop: Repeats a block of code while a specified condition is true.
Factorial:
The factorial of a number n (denoted as n!) is the product of all positive integers from 1 to
n. Factorial of 0 is defined as 1 : 0!=1! =1

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 4

AIM – Lists and arrays: Create a program that prompts the user for a list of numbers and then sorts
them in ascending order.

THEORY - Lists and Arrays in Python

Lists and arrays are fundamental data structures in Python that allow us to store collections
of elements. While both serve similar purposes, there are some differences between them:
1. Lists:
• A list is a built-in Python data type that can store a collection of elements of any data
type (e.g., integers, strings, floats, etc.).
• Lists are mutable, meaning their elements can be changed after creation.
• Lists are versatile and widely used in Python.
2. Arrays:
• Arrays are provided by external libraries, such as array or numpy.
• Arrays store elements of the same data type and are more memory-efficient
compared to lists when working with numerical data.
• They are ideal for large-scale numerical computations.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 5

AIM – Strings and string manipulation: Create a program that prompts the user for a string and then
prints out the string reversed.

THEORY - Strings and String Manipulation in Python

A string is a sequence of characters enclosed in single quotes (') or double quotes ("). Strings
in Python are immutable, meaning their contents cannot be changed directly after creation.

However, Python provides many powerful methods and techniques to manipulate strings.
String Manipulation Operations:

1. Accessing Characters: Strings can be accessed using indexing (string[index]).


2. Slicing: Substrings can be extracted using slicing (string[start:end:step]).
3. Concatenation: Joining strings using the + operator.
4. Reversing: Strings can be reversed using slicing with a negative step ([::-1]).
5. String Methods: Python offers built-in methods like .upper(), .lower(), .strip(),
.replace(), etc., for manipulation.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 6

AIM – Functions: Create a program that defines a function to calculate the area of a circle based on the
radius entered by the user.

THEORY - Functions in Python

A function is a block of reusable code that performs a specific task. Functions make
programs are modular, efficient, and easier to maintain. Python functions are defined using the
def keyword and can take parameters as input, process them, and return an output using
the return statement.

Key Components of a Function:


• Function Definition: Declared using the def keyword followed by the function name
and parentheses.
• Parameters: Variables passed into the function to provide input data.
• Return Value: The result or output of the function, returned using the return
keyword.
• Function Call: Executing a function by its name and providing necessary arguments

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 7

AIM – Classes and objects: Create a program that defines a class to represent a car and then creates
an object of that class with specific attributes.

THEORY -
In object-oriented programming, classes and objects are fundamental concepts that help structure
code in a more organized and reusable way.
A class is like a blueprint for creating objects—it defines the attributes (variables) and behaviors
(methods) that the objects created from it will have.
An object is an instance of a class, representing a real-world entity with specific values assigned to its
attributes.
For example, a Car class can have attributes like brand, model, and year, and you can create multiple
Car objects with different values.
This approach promotes code modularity, reusability, and abstraction, making programs easier to
maintain and expand.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 8

AIM – File input/output: Create a program that reads data from a file and writes it to another file in a
different format.

THEORY -
File Input/Output (I/O) in Python allows programs to interact with data stored in files, enabling reading
from and writing to external text or data files.
This is essential for tasks like data processing, logging, and configuration management. Python provides
built-in functions such as open(), read(), write(), and context managers (with statement) to make
file operations easy and safe.
In a typical file I/O operation, data is read from an input file, processed as needed, and then written to an
output file—often in a different format for clarity or compatibility.
This approach enhances data storage, manipulation, and transfer in real-world applications.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 9

AIM – Regular expressions: Create a program that uses regular expressions to find all instances of a
specific pattern in a text file.

THEORY -
Regular expressions (regex) are powerful tools used in programming to search, match, and manipulate
strings based on specific patterns.
They allow for flexible and efficient text processing by defining search patterns using special characters
and sequences.
In Python, the re module provides functions like findall(), search(), and match() to work with
regular expressions.
This is especially useful in tasks such as validating input formats (like emails or phone numbers),
extracting data, or finding patterns within large text files.
Regular expressions help automate complex string operations with minimal and concise code.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 10

AIM – Exception handling: Create a program that prompts the user for two numbers and then divides
them, handling any exceptions that may arise.

THEORY -
Exception handling in Python is used to gracefully manage errors that occur during program execution.
Instead of crashing the program when an error arises (like dividing by zero or entering invalid input),
exception handling lets you define how the program should respond using try, except, else, and
finally blocks.
This makes programs more robust, user-friendly, and less prone to unexpected termination.
Common exceptions like ZeroDivisionError, ValueError, and TypeError can be caught and
handled, ensuring smooth execution even when errors occur.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 11

AIM – GUI programming: Create a program that uses a graphical user interface (GUI) to allow the user
to perform simple calculations.

THEORY -
GUI (Graphical User Interface) programming in Python allows developers to create interactive,
user-friendly applications using graphical elements like buttons, text fields, and labels.
Unlike command-line programs, GUI applications offer a visual interface for user interaction.
Python provides several libraries for GUI development, with Tkinter being one of the most popular and
built-in options.
Using Tkinter, developers can design windows, handle user events (like clicks), and display results
dynamically, making programs more intuitive and accessible for everyday users.

ALGORITHM –
SOURCE CODE –
import tkinter as tk
def calculate():
try:
num1 = float(entry1.get())
num2 = float(entry2.get())
operation = operation_var.get()
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
result = num1 / num2
else:
result = "Invalid operation"
result_label.config(text=f"Result: {result}")
except ValueError:
result_label.config(text="Please enter valid numbers.")
except ZeroDivisionError:
result_label.config(text="Cannot divide by zero.")
root = tk.Tk()
root.title("Simple Calculator")
root.geometry("300x250")
tk.Label(root, text="First Number").pack()
entry1 = tk.Entry(root)
entry1.pack()
tk.Label(root, text="Second Number").pack()
entry2 = tk.Entry(root)
entry2.pack()
operation_var = tk.StringVar(root)
operation_var.set('+')
tk.Label(root, text="Operation").pack()
tk.OptionMenu(root, operation_var, '+', '-', '*', '/').pack()
tk.Button(root, text="Calculate", command=calculate).pack(pady=10)
result_label = tk.Label(root, text="Result:")
result_label.pack()
root.mainloop()
OUTPUT -
EXPERIMENT - 12

AIM – Web scraping: Create a program that uses a web scraping library to extract data from a website
and then stores it in a database.

THEORY -
Web scraping is the process of automatically extracting data from websites using programs or scripts.
In Python, libraries like BeautifulSoup, requests, and Selenium are commonly used for scraping
HTML content from webpages.
Scraped data can include anything visible on the site—such as text, links, tables, or images.
Once the data is extracted, it can be stored in databases like SQLite, MySQL, or PostgreSQL for
further analysis, storage, or display.
Web scraping is widely used in applications like price comparison, news aggregation, data mining, and
research, but it's important to respect a site's robots.txt file and terms of service.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT - 13

AIM – Data visualization: Create a program that reads data from a file and then creates a visualization of
that data using a data visualization library.

THEORY -

Data visualization is the graphical representation of information and data using visual elements like
charts, graphs, and plots.
It helps in understanding patterns, trends, and insights that are often hard to grasp from raw data. In
Python, libraries like Matplotlib, Seaborn, and Plotly are commonly used for data visualization.
These tools allow developers to create a wide range of visualizations such as bar charts, line graphs, pie
charts, and scatter plots.
Visualization plays a crucial role in data analysis, reporting, and storytelling, making complex data more
accessible and easier to interpret.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT – 14

AIM – Machine learning: Create a program that uses a machine learning library to classify images based
on their content.

THEORY -
Machine Learning (ML) is a branch of artificial intelligence that enables systems to learn from data and
improve their performance without being explicitly programmed.
In the context of image classification, ML models are trained to recognize patterns and features within
images—such as shapes, colors, and textures—to categorize them into predefined classes.
Python provides powerful ML libraries like scikit-learn, TensorFlow, and Keras, which allow
developers to build, train, and test image classifiers.
These models are widely used in applications such as facial recognition, medical imaging, and
automated tagging in photo libraries.

ALGORITHM –
SOURCE CODE –

OUTPUT -
EXPERIMENT – 15

AIM – Networking: Create a program that uses a networking library to communicate with a server and
retrieve data from it.

THEORY -
Networking in Python involves the exchange of data between devices (clients and servers) over a
network using protocols like HTTP, TCP, or UDP.
Python provides built-in and third-party libraries such as socket, http.client, and requests that
make it easy to create networked applications.
These libraries allow a program to connect to servers, send requests, and receive responses.
A common use case is retrieving data from a web server via HTTP, such as downloading JSON data
from an API.
Networking is fundamental in applications like web scraping, online games, messaging apps, and
real-time data services.

ALGORITHM –
SOURCE CODE –

OUTPUT -

You might also like