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

Experiment Python 12018

The document outlines various programming experiments focused on file I/O, regular expressions, exception handling, GUI programming, web scraping, data visualization, and machine learning. Each experiment includes an aim, theoretical background, code examples, and expected outputs. The experiments utilize Python and cover essential programming concepts and libraries.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Experiment Python 12018

The document outlines various programming experiments focused on file I/O, regular expressions, exception handling, GUI programming, web scraping, data visualization, and machine learning. Each experiment includes an aim, theoretical background, code examples, and expected outputs. The experiments utilize Python and cover essential programming concepts and libraries.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

EXPERIMENT – 12

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

File Input/Output File input and output (I/O) is an essential part of


programming, allowing data to be stored and retrieved from files. File I/O
operations include reading, writing, appending, and modifying files. There are
two primary types of files: text files and binary files. Text files store data as
readable text, while binary files store data in machine-readable format.

Common file handling operations include:

 Opening a file using different modes (read, write, append).


 Reading from a file using functions like read(), readline(), and
readlines().
 Writing to a file using write() and writelines().
 Closing a file to ensure proper resource management.
 Exception handling to prevent errors like file not found.

CODE:
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Welcome to file handling in Python.")

# Reading from a file


with open("example.txt", "r") as file:
content = file.read()
print("File Contents:\n", content)

OUTPUT:
EXPERIMENT – 13
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 patterns used to match character
combinations in strings. They provide a flexible and efficient way to search,
replace, and extract text patterns. Regex is widely used in data validation, text
processing, and web scraping.
Common Regex Functions in Python

 re.match(pattern, string): Matches a pattern at the beginning of a string.


 re.search(pattern, string): Searches for the first occurrence of a pattern
anywhere in a string.
 re.findall(pattern, string): Finds all occurrences of a pattern.
 re.sub(pattern, replacement, string): Replaces occurrences of a pattern
with a specified string.

CODE:

import re

text = "My phone number is 123-456-7890."

pattern = r"\d{3}-\d{3}-\d{4}"

match = re.search(pattern, text)

# Print the result

if match:

print("Phone number found:", match.group())

else:

print("No phone number found.")

OUTPUT:
EXPERIMENT – 14
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 is a crucial feature in programming that allows developers
to handle unexpected errors gracefully, preventing program crashes and
ensuring a smooth user experience. In Python, exceptions occur during
execution when an operation fails, such as dividing by zero or trying to access a
missing file.

Why Use Exception Handling?

1. Prevents Program Crashes – Avoids abrupt termination of the program.


2. Improves Debugging – Helps identify and resolve issues effectively.
3. Ensures Reliability – Allows handling of known and unknown errors.
4. Enhances User Experience – Provides meaningful error messages.

Key Exception Handling Constructs in Python

 try: Defines the block of code where an exception may occur.


 except: Catches and handles specific exceptions.
 finally: Runs code regardless of whether an exception occurred or not.
 raise: Manually triggers an exception.

CODE:

try:

num = int(input("Enter a number: "))

result = 10 / num

print("Result:", result)

except ZeroDivisionError:

print("Error: Cannot divide by zero!")


except ValueError:

print("Error: Invalid input! Please enter a number.")

finally:

print("Execution completed.")

OUTPUT:
EXPERIMENT-15
AIM:
GUI programming: Create a program that uses a graphical user interface (GUI) to
allow the user to perform simple calculations.
THEORY:
Graphical User Interface (GUI) programming allows users to interact with
applications using visual elements like buttons, labels, text fields, and menus.
Unlike command-line interfaces, GUIs provide a more intuitive and user-
friendly experience.

Python provides several libraries for GUI development, including:

 Tkinter – The standard GUI library in Python (lightweight and easy to


use).
 PyQt/PySide – More advanced GUI development using Qt framework.
 Kivy – Used for developing multi-touch applications.

Why Use GUI Programming?

1. User-Friendly Interface – Makes applications easier to use.


2. Improves Visual Appeal – Enhances user experience with buttons,
menus, and graphics.
3. Event-Driven Programming – Responds to user actions like clicks and
keypresses.
4. Cross-Platform Compatibility – Can run on Windows, macOS, and Linux.

Key Components of a GUI

 Window (Tk()): The main application window.


 Labels (Label): Display text or images.
 Buttons (Button): Trigger actions when clicked.
 Text Entry (Entry): Accept user input.
 Event Loop (mainloop()): Keeps the GUI running and responsive.

CODE:
import tkinter as tk
# Create main window
root = tk.Tk()
root.title("Simple GUI")
# Create a label
label = tk.Label(root, text="Hello, GUI!")
label.pack()
# Run the application
root.mainloop()

OUTPUT:
EXPERIMENT-16
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 in Python

Web scraping is the process of extracting data from websites using automated
scripts. It is commonly used for data analysis, price comparison, news
aggregation, and research purposes. Python provides powerful libraries such as
BeautifulSoup, requests, and Scrapy for web scraping.

How Web Scraping Works?

1. Send an HTTP request to the target webpage using requests.


2. Retrieve the HTML content of the webpage.
3. Parse the HTML using BeautifulSoup to extract relevant data.
4. Store or display the extracted data.

CODE:

import requests

from bs4 import BeautifulSoup

url = "https://www.example.com"

response = requests.get(url)

soup = BeautifulSoup(response.text, "html.parser")

print("Page Title:", soup.title.text)

OUTPUT:
EXPERIMENT-17
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 data to help identify
patterns, trends, and insights. It is widely used in data analysis, business
intelligence, and scientific research. Python provides several libraries for
visualization, with Matplotlib and Seaborn being the most popular.
Why Use Data Visualization?

1. Simplifies Data Interpretation – Makes complex data easier to


understand.
2. Identifies Trends & Patterns – Helps detect correlations and anomalies.
3. Enhances Decision-Making – Supports data-driven decision-making.
4. Effective Communication – Presents findings visually for better
storytelling.

Popular Data Visualization Libraries

 Matplotlib – A flexible library for creating static, animated, and


interactive plots.
 Seaborn – Built on Matplotlib, used for statistical data visualization.
 Plotly – Provides interactive charts for dashboards and reports.

CODE:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [10, 20, 25, 30, 40]

plt.plot(x, y, marker="o", linestyle="-", color="b", label="Data Line")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.title("Sample Line Plot")


plt.legend() # Add a legend

plt.grid(True) # Add grid lines

plt.show()

OUTPUT:
EXPERIMENT-18
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 (AI) that enables


computers to learn from data and make predictions without being explicitly
programmed. It is widely used in applications like recommendation systems,
fraud detection, speech recognition, and self-driving cars.

Types of Machine Learning

1. Supervised Learning – The model learns from labeled data (e.g.,


predicting house prices).
2. Unsupervised Learning – The model finds patterns in unlabeled data
(e.g., customer segmentation).
3. Reinforcement Learning – The model learns through rewards and
penalties (e.g., game-playing AI).

Key Libraries for Machine Learning in Python

 Scikit-learn – Provides tools for data preprocessing, regression,


classification, and clustering.
 TensorFlow & Keras – Used for deep learning applications like image
recognition.
 Pandas & NumPy – Helps in handling and manipulating large datasets.
 Matplotlib & Seaborn – Used for data visualization and model
interpretation.

CODE:

from sklearn.linear_model import LinearRegression

import numpy as np

import matplotlib.pyplot as plt

# Sample dataset
X = np.array([[1], [2], [3], [4], [5]]) # Independent variable

y = np.array([10, 20, 30, 40, 50]) # Dependent variable

# Create and train the model

model = LinearRegression()

model.fit(X, y)

# Make a prediction

predicted_value = model.predict([[6]])

print("Prediction for X=6:", predicted_value[0])

# Visualization

plt.scatter(X, y, color='blue', label="Actual Data")

plt.plot(X, model.predict(X), color='red', label="Regression Line")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.title("Simple Linear Regression")

plt.legend()

plt.show()

OUTPUT:

You might also like