0% found this document useful (0 votes)
12 views37 pages

PYTHON LAB Manual - Merged

The document is a lab file for a Programming in Python course at Guru Gobind Singh Indraprastha University, detailing various programming experiments. Each experiment focuses on different programming concepts such as data types, conditional statements, loops, and file I/O, with corresponding code examples and explanations. The file includes a structured index and aims to enhance students' understanding of Python programming through practical exercises.

Uploaded by

coderxyz3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views37 pages

PYTHON LAB Manual - Merged

The document is a lab file for a Programming in Python course at Guru Gobind Singh Indraprastha University, detailing various programming experiments. Each experiment focuses on different programming concepts such as data types, conditional statements, loops, and file I/O, with corresponding code examples and explanations. The file includes a structured index and aims to enhance students' understanding of Python programming through practical exercises.

Uploaded by

coderxyz3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

AFFILATED TO

GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY, NEW DELHI

DEPARTMENT
OF
ELECTRONICS & COMMUNICATION ENGINEERING

LAB FILE
PROGRAMMING IN PYTHON
(IOT-330P)

NAME : Prerna
SUBMIT TO :
ROLL NO: 01396202822
DR. JUHI
SECTION : T13
INDEX

S.NO. AIM OF EXPERIMENT DATE REMARKS SIGNATURE

Basic data types and operators: Create a program that


prompts the user for their name and age and prints a
1.
personalized message.

Conditional statements : Create a program that


prompts the user for their age and tells them if they
2.
can vote in the next election.

Loops: Create a program that calculates the factorial of


3. a number entered by the user using a loop.

Lists and arrays : Create a program that prompts the


4. user for a list of numbers and then sorts them in
ascending order.

Strings and string manipulation: Create a program that


5. prompts the user for a string and then prints out the
string reversed.

Functions: Create a program that defines a function


6.
to calculate the area of a circle based on the radius
entered by the user.

Classes and objects: Create a program that defines a


7
class to represent a car and then creates an object of
that class with specific attributes.

File input/output: Create a program that reads data fr


8
om a file and writes it to another file in a different f
ormat.

Regular expressions :Create a program that uses


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

GUI programming: Create a program that uses a


graphical user interface (GUI) to allow the user to
11.
perform simple calculations.

Web scraping : Create a program that uses a web


scraping library to extract data from a website and then
12.
stores it in a database.

Data visualization: Create a program that reads data


from a file and then creates a visualization of that data
13.
using a data visualization library.

Machine learning: Create a program that uses a machi


14.
ne learning library to classify images based on their c
ontent.

Networking: Create a program that uses a networki


15 ng library to communicate with a server and retriev
e data from it
EXPERIMENT-1

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

THEORY -# Data Types : It refers to the built-in types of data that a programming
language inherently understands.These typically include :
● Integer:Represents whole numbers,e.g.,-1,0,1,2.
● Float:Represents real numbers,can include a fractional part, e.g.,
1.23, 3.14.
● Boolean:Represents True or False.
● String:Represents a sequence of characters,e.g.,a,A.
These are fundamental to performing operations in the language and
building more complex data structures.

#Operators:They are symbols that represent specificactions to be


performed on operands. These typically include :
● Arithmetic Operators : Perform mathematical operations like
addition(+),subtraction(-),multiplication(*),anddivision(/).
● Comparison Operators : Compare two values and return True or
False. Examples include equalto(==),notequalto(!=),lessthan (<),
and greater than (>).
● Logical Operators:Used to combine conditional statements.
Includes and, or, and not.

CODE :
# Taking user input
name = input("Please enter your name please : ")
age = int(input("\ nPlease enter your age please : "))
# Displaying the message
print("\n Message for you!\n")
print(f"Hello, {name}! You are {age} years old.\n")
# Providing a motivational message for the 20s
if 20 <= age < 30:
print("Your 20s are your 'selfish' years. It's a decade to immerse
yourself in every single thing possible. "
"Be adventurous with your time, all aspects of you and never
stop learning.")
OUTPUT:
EXPERIMENT-2

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

THEORY-#Conditional Statements: This is a feature used to perform different computations or actions


depending on whether a
Specified Boolean condition evaluates to true or false.Common types of conditional statements
include if, if-else, and switch statements.

CODE : age = int(input("Please enteí youí age please : ")) if age >= 18:
píint("\nYou aíe eligible to votein the next election.\n")
else:
píint("\nYou aíe not eligible to vote in thenext election.\n")
OutPut:
EXPERIMENT-3

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

THEORY-#Loops: They are control flow structures that enable the


Repeated execution of a set of instructions or codeblock as long as a specified condition is met.
They are fundamental to the concept of iteration in programming, enhancing code efficiency,
readability, and promoting the reuse of code logic.

#Factorial: It’s a function that multiplies a given number,`n`,by every number less than `n` down
to 1. This operation is
Symbolized by an exclamation point(`!`).For example,the factorial of 4 (denoted as 4!) is
`4*3*2*1` which equals 24.
Factorials are particularly useful in scenarios involving
Permutations and combinations,as they can help determine the total number of possible
outcomes.

CODE:⭲
# Function to calculate factorial
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
# Taking user input
num = int(input("Please enter a number : "))

# Calculating factorial
fact = factorial(num)

# Displaying the result


print(f"\nThe factorial of {num} is {fact}.")
OUTPUT:
EXPERIMENT-4

AIM-
Lists and arrays: Create a program that prompts the user for a list of numbers and then sorts t
hem in ascending

THEORY

Lists:
It’s a data structure that represents a finite number of ordered values, where the same value may occur more than
once. It can store multiple data together in a single variable. The elements in a list can be of different data types.

Array:
It’s a data structure consisting of a collection of elements (values or variables), each identified by at least one array
index or key. It is a collection of items of the same data type stored at contiguous memory locations. The size of an
array is set when created.

CODE:

# Taking user input as a list of numbers

numbers = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))

# Sorting the list in ascending order

numbers.sort()

# Displaying the sorted list

print("\nSorted numbers in ascending order:", numbers)


OUTPUT:
EXPERIMENT-5

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

THEORY

String:
A string in programming is a sequence of characters, such as letters, numbers, and symbols. They are widely
used for storing and manipulating textual data in various programming languages. Strings can be thought of as
an array of characters.

String Manipulation:

String manipulation in programming refers to the process of modifying a string or creating a new string by
making changes to existing strings. This can involve a variety of operations such as slicing, concatenation,
repeating, interpolation, and formatting. These operations can be performed using built-in string functions in
many programming languages.

CODE: # Taking user input

user_string = input("Enter a string: ")

# Reversing the string using slicing

reversed_string = user_string[::-1]

# Displaying the reversed string

print("\nReversed string:", reversed_string)


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 :

A function in Python is a block of reusable code that performs a specific task. Functions help in modularizing code,
making it more readable, reusable, and easier to maintain.

Defining a Function

A function is defined using the def keyword, followed by the function name and parentheses. It can take input values
(parameters) and return an output using the return statement.

Code:

import math # Importing math module to use the value of π

# Function to calculate the area of a circle

def calculate_area(radius):

return math.pi * radius ** 2 # Using the formula π × r²

# Taking user input

radius = float(input("Enter the radius of the circle: ")) # Calling the function and displaying the
result area = calculate_area(radius)

print(f"\nThe area of the circle with radius {radius} is: {area:.2f}")


EXPERIMENT-7

Aim
:Classes and objects: Create a program that defines a class to represent a car and then creates an obj
ect of that class with specific attributes.

Theory: classes and objects are fundamental concepts of object-oriented programming (OOP).

 A class is a blueprint or template for creating objects. It defines the attributes (variables) and behaviors
(methods) that the objects of the class will have.
 An object is an instance of a class with actual values assigned to its attributes.

Defining a Class

A class in Python is created using the class keyword. Inside the class, we define attributes (properties) and methods
(functions).

Creating an Object

To create an object, we call the class name with specific attribute values.

Code:

# Define a class to represent a Car

class Car:

def __init__(self, brand, model, year, color):

self.brand = brand

self.model = model

self.year = year

self.color = color

def display_info(self):

return f"Car Details: {self.year} {self.color} {self.brand} {self.model}"

# Create an object of the Car class

my_car = Car("Toyota", "Corolla", 2022, "Red")

# Print car details

print(my_car.display_info())

OutPut:

Car Details: 2022 Red Toyota Corolla


EXPERIMENT-8

AIM –

File input/output: Create a program that reads data from a file and writes it to another file in a different for
mat.
Theory –
File Input/Output in Python

File input and output (I/O) operations allow a program to read data from files and write processed data into new
files. In Python, file handling is performed using built-in functions like open(), read(), and write().

Concept of File I/O

File I/O in Python follows these basic steps:

1. Opening a File:
o A file must be opened before reading or writing.
o The open() function is used with different modes such as 'r' (read), 'w' (write), and 'a' (append).
2. Reading from a File:
o Data can be read using methods like .read(), .readline(), or .readlines().
3. Processing the Data:
o The retrieved data may be modified, reformatted, or converted into a different structure.
4. Writing to Another File:
o The processed data is then written to a new file using .write() or .writelines().
5. Closing the File:
o It is essential to close the file using .close() or use the with statement to manage files efficiently.

Code :

# Read from input file and write to output file in a different format

# Read data from input file

with open("input.txt", "r") as infile:

lines = infile.readlines()

# Process data

formatted_data = []

for line in lines:

name, age = line.strip().split(",") # Assuming "Name,Age" format

formatted_data.append(f'{{"name": "{name.strip()}", "age": {age.strip()}}}')


# Write processed data to output file

with open("output.txt", "w") as outfile:

outfile.write("[\n" + ",\n".join(formatted_data) + "\n]")

print("Data has been successfully written to output.txt in a different format.")

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 sequences of characters that form a search pattern. They are primarily used for
pattern matching in strings, such as "find" or "find and replace" operations.

Regular expressions are supported in almost every programming language, including C++, Java, and Python. They
provide a generalized way to match patterns within sequences of characters. However, the exact syntax and
behavior of regular expressions may vary between different programming languages.

CODE: import re # Import the regular expressions module

def find_pattern_in_text(text, pattern):

matches = re.findall(pattern, text) # Find all matches using regex

return matches

# Get user input for filename and pattern

file_name = input("\nEnter your filename please: ")

pattern = input("\nEnter the regular expression pattern you want to search for: ")

# Open the file and read its contents

with open(file_name, 'r') as file:

text = file.read()

# Find matches in the text

matches = find_pattern_in_text(text, pattern)


# Print matched patterns

for match in matches:

print(match)
OUTPUT:
EXPERIMENT-10

Aim :
Exception handling: Create a program that prompts the user for two numbers and then divide
s them, handling any exceptions that may arise.

Theory :
Exception Handling in Python

Exception handling is a mechanism that allows a program to handle errors gracefully instead of crashing. When a
program encounters an error (exception), Python provides a way to handle it using try-except blocks.

Concept of Exception Handling

1. Try Block: Contains the code that may raise an exception.


2. Except Block: Catches and handles the exception if one occurs.
3. Finally Block (Optional): Contains code that executes regardless of whether an exception occurs or not.

Code :

try:

# Take user input for two numbers

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# Perform division

result = num1 / num2

# Print the result

print(f"Result: {num1} / {num2} = {result}")

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")


except ValueError:

print("Error: Please enter valid numeric values.")

except Exception as e:

print(f"An unexpected error occurred: {e}")

output:

Enter the first number: 10

Enter the second number: 2

Result: 10.0 / 2.0 = 5.0

Enter the first number: 10

Enter the second number: 0

Error: Division by zero is not allowed.

Enter the first number: ten

Enter the second number: 2

Error: Please enter valid numeric values.


EXPERIMENT-11

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

THEORYGUI Programming refers to the development of programs that use a Graphical User Interface (GUI). A
GUI allows users to interact with electronic devices through graphical icons, buttons, and visual indicators, rather
than text-based commands.

It involves designing the visual layout and interactive behavior of the interface to improve usability and
efficiency. The goal of GUI programming is to create intuitive and user-friendly applications that enhance the
interaction between users and the underlying logic of a program.

CODE : import tkinter as tk


from tkinter.font import Font

# Function to handle button clicks


def click(number):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, current + str(number))

# Function to clear the input field


def clear():
entry.delete(0, tk.END)

# Function to evaluate and calculate the result


def calculate(event=None):
try:
result = eval(entry.get()) # Evaluate the
expression safely
entry.delete(0, tk.END)
entry.insert(0, result)
except Exception:
entry.delete(0, tk.END)
entry.insert(0, "Invalid input")
root.after(300, clear) # Clear after 300ms

# Function to adjust font size based on window


width
def adjust_font_and_entry_width(event):
size = max(min(root.winfo_width() // 20, 20),
10) # Dynamic font size
entry_font.configure(size=size)

# Function to handle keyboard input


def key_press(event):
if event.char.isdigit() or event.char in ['+', '-',
'*', '/']:
click(event.char)
elif event.keysym == 'BackSpace':
entry.delete(len(entry.get()) - 1, tk.END)
elif event.keysym == 'Return':
calculate()

# Create the main application window


root = tk.Tk()
root.title("Simple Calculator")
root.geometry("600x500")

# Create font object


entry_font = Font(family="Helvetica", size=24)

# Create an input field


entry = tk.Entry(root, font=entry_font,
width=20, borderwidth=5,
justify="right")
entry.grid(row=0, column=0, columnspan=4,
pady=10, padx=10, sticky='we')

# Bind Enter key to calculate function


entry.bind("<Return>", calculate)

# Create calculator buttons


buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3),
]

# Add buttons to the window


for (text, row, col) in buttons:
if text == "=":
btn = tk.Button(root, text=text,
font=entry_font, height=2, width=5,
command=calculate)
else:
btn = tk.Button(root, text=text,
font=entry_font, height=2, width=5,
command=lambda t=text: click(t))

btn.grid(row=row, column=col, padx=5,


pady=5, sticky="nsew")

# Clear button
clear_btn = tk.Button(root, text="C",
font=entry_font, height=2, width=5,
command=clear)
clear_btn.grid(row=5, column=0,
columnspan=4, sticky="we", padx=5,
pady=5)

# Bind window resizing event to adjust font size


dynamically
root.bind("<Configure>",
adjust_font_and_entry_width)

# Bind keyboard inputs


root.bind("<Key>", key_press)

# Run the application


root.mainloop()
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#WebScraping: It is an automated method used to extract large amounts of data from websites
quickly. The data collected is usually unstructured in an HTML format, which is then
converted into a structured format such as a spreadsheet or a database, making it useful for
various applications.
CODE:impoítíequests
fíombs4impoítBeautifulSoup impoít sqlite3
í=íequests.get('http://quotes.toscíape.com/tag/tíuth/') í_html = í.text
soup = BeautifulSoup(í_html, 'html.paíseí') quotes =
soup.find_all('div', class_='quote') conn =
sqlite3.connect('quotes.db')
c = conn.cuísoí() c.execute('''
CREATE TABLE quotes( quote
TEXT,
authoíTEXT
)
''')
foíquoteinquotes:
quote_text=quote.find('span',class_='text').text
authoí=quote.find('small',class_='authoí').text
c.execute("INSERTINTOquotesVALUES(?,?)",(quote_text,authoí))
conn.commit() conn.close()
import requests
from bs4 import BeautifulSoup
import sqlite3

# Fetch the webpage


response = requests.get('http://quotes.toscrape.com/tag/truth/')
html_content = response.text

# Parse the HTML


soup = BeautifulSoup(html_content, 'html.parser')
quotes = soup.find_all('div', class_='quote')
# Connect to SQLite database
conn = sqlite3.connect('quotes.db')
c = conn.cursor()

# Create table if it doesn't exist


c.execute('''
CREATE TABLE IF NOT EXISTS quotes (
quote TEXT,
author TEXT
)
''')

# Extract and insert quotes into the database


for quote in quotes:
quote_text = quote.find('span', class_='text').text
author = quote.find('small', class_='author').text
c.execute("INSERT INTO quotes (quote, author) VALUES (?, ?)", (quote_text, author))

# Commit changes and close the connection


conn.commit()
conn.close()

print("Quotes successfully scraped and saved to the database!")


EXPERIMENT-13

AIM -
Data visualization: Create a program that reads data from a file and then creates a visualization o
f that data using a data visualization library.

THEORY

#DataVisualization: It is the process of graphically representing information and data. By using visual elements
like charts, graphs, and maps, data visualization tools provide an accessible way to see and understand trends,
patterns, and outliers in data.

CODE: import pandas as pd

import matplotlib.pyplot as plt

# Read data from CSV file

data = pd.read_csv('data.csv')

# Create a bar chart

plt.figure(figsize=(10, 6))

plt.bar(data['Category'], data['Amount'])

plt.title('Bar Chart: Amount by Category')

plt.xlabel('Category')

plt.ylabel('Amount')

plt.xticks(rotation=45) # Rotate x-axis labels for better visibility

plt.show()

# Create a pie chart

plt.figure(figsize=(10, 6))

plt.pie(data['Amount'], labels=data['Category'], autopct='%1.1f%%')


plt.title('Pie Chart: Amount by Category')

plt.show()

# Create a scatter plot

plt.figure(figsize=(10, 6))

plt.scatter(data['Category'], data['Amount'])

plt.title('Scatter Plot: Amount by Category')

plt.xlabel('Category')

plt.ylabel('Amount')

plt.xticks(rotation=45)
OUTPUT:-

BarChart:
Piechart:

ScatterPlot:
EXPERIMENT-14

Aim :
Machine learning: Create a program that uses a machine learning library to classify images based on their co
ntent.

Theory : Machine learning is a branch of artificial intelligence (AI) that enables computers to learn from data and
make predictions or decisions without being explicitly programmed. It involves using algorithms that analyze and
identify patterns in data, allowing the system to improve its performance over time.

To classify images based on their content, machine learning models use techniques such as deep learning, which
employs neural networks to process visual information. Libraries like TensorFlow, Keras, and Scikit-Learn provide
powerful tools for building and training such models.

Steps to Create an Image Classification Program:

1. Data Collection: Gather a dataset of labeled images for training.


2. Preprocessing: Resize, normalize, and augment images to improve model performance.
3. Model Selection: Choose a machine learning model (e.g., Convolutional Neural Network - CNN).
4. Training: Train the model using the dataset and adjust parameters to improve accuracy.
5. Evaluation: Test the model on new images to assess its performance.
6. Prediction: Use the trained model to classify new images based on learned patterns.

Python provides several libraries for machine learning and image processing, including:

 TensorFlow/Keras: For building deep learning models.


 OpenCV: For image processing and feature extraction.
 Pandas & NumPy: For handling and manipulating data.
 Matplotlib & Seaborn: For visualizing results.

Code :

import tensorflow as tf

import numpy as np

from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions

from tensorflow.keras.preprocessing import image

import matplotlib.pyplot as plt

# Load pre-trained MobileNetV2 model

model = MobileNetV2(weights='imagenet')

def classify_image(img_path):

# Load and preprocess the image

img = image.load_img(img_path, target_size=(224, 224))


img_array = image.img_to_array(img)

img_array = np.expand_dims(img_array, axis=0)

img_array = preprocess_input(img_array)

# Make prediction

preds = model.predict(img_array)

decoded_preds = decode_predictions(preds, top=3)[0]

# Display image and prediction results

plt.imshow(img)

plt.axis('off')

plt.title(f"Predicted: {decoded_preds[0][1]} ({decoded_preds[0][2] * 100:.2f}%)")

plt.show()

# Print top-3 predictions

for i, (imagenet_id, label, score) in enumerate(decoded_preds):

print(f"{i+1}: {label} ({score * 100:.2f}%)")

# Test with an image (provide a valid image path)

image_path = "dog.jpg" # Replace with an actual image path

classify_image(image_path)
EXPERIMENT-15

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

THEORY

Networking: Often referred to as Network Programming, it is the practice of writing programs or processes
that can communicate with other programs or processes across a network. It enables data exchange between
devices using protocols such as HTTP, TCP/IP, and WebSockets, facilitating applications like web browsing,
online gaming, and cloud computing.

CODE: import requests

def get_data_from_server():

url = input("Please enter the URL of the server: ")

print("\nSending request to the server...")

try:

response = requests.get(url)

response.raise_for_status() # Raise an HTTPError for bad responses (4xx and 5xx)

except requests.exceptions.HTTPError as errh:

print("\nHTTP Error:", errh)

except requests.exceptions.ConnectionError as errc:

print("\nError Connecting:", errc)

except requests.exceptions.Timeout as errt:

print("\nTimeout Error:", errt)

except requests.exceptions.RequestException as err:

print("\nSomething went wrong:", err)


else:

print("\nData retrieved successfully!")

return response.text

data = get_data_from_server()

if data:

print("\033[92m" + "\nHere is the data from the server:\n" + "\033[93m" + data + "\033[0m")
OUTPUT:-

You might also like