PYTHON LAB Manual - Merged
PYTHON LAB Manual - Merged
DEPARTMENT
OF
ELECTRONICS & COMMUNICATION ENGINEERING
LAB FILE
PROGRAMMING IN PYTHON
(IOT-330P)
NAME : Prerna
SUBMIT TO :
ROLL NO: 01396202822
DR. JUHI
SECTION : T13
INDEX
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.
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.
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.
#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)
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:
numbers.sort()
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.
reversed_string = user_string[::-1]
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:
def calculate_area(radius):
radius = float(input("Enter the radius of the circle: ")) # Calling the function and displaying the
result area = calculate_area(radius)
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:
class Car:
self.brand = brand
self.model = model
self.year = year
self.color = color
def display_info(self):
print(my_car.display_info())
OutPut:
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().
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
lines = infile.readlines()
# Process data
formatted_data = []
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.
return matches
pattern = input("\nEnter the regular expression pattern you want to search for: ")
text = file.read()
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.
Code :
try:
# Perform division
except ZeroDivisionError:
except Exception as e:
output:
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.
# 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)
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
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.
data = pd.read_csv('data.csv')
plt.figure(figsize=(10, 6))
plt.bar(data['Category'], data['Amount'])
plt.xlabel('Category')
plt.ylabel('Amount')
plt.show()
plt.figure(figsize=(10, 6))
plt.show()
plt.figure(figsize=(10, 6))
plt.scatter(data['Category'], data['Amount'])
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.
Python provides several libraries for machine learning and image processing, including:
Code :
import tensorflow as tf
import numpy as np
model = MobileNetV2(weights='imagenet')
def classify_image(img_path):
img_array = preprocess_input(img_array)
# Make prediction
preds = model.predict(img_array)
plt.imshow(img)
plt.axis('off')
plt.show()
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.
def get_data_from_server():
try:
response = requests.get(url)
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:-