Nehru Institute of Technology
(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
U23CS211 - PYTHON PROGRAMMING LABORATORY
II SEMESTER
NAME
REG. NO.
CLASS
SUBJECT
Nehru Institute of Technology
(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited
Institution Vision
To be leading Institution in Academic excellence, Multidisciplinary Research,
Innovation, Entrepreneurship and Industry relations in order to mould true citizens
of the country.
Institution Mission
• To create innovative and vibrant young leaders in the field of Engineering and
Technology to grow India as knowledge power by strengthening the teaching-learning
process.
• To enhance employability, entrepreneurship and to improve the research competence to
address Societal needs.
• To generate engineering graduates who use knowledge as a powerful tool to drive
societal transformation and inculcate ethical and moral values.
Department Vision
To become a School of Computing excellence in research and innovation by
imparting industry driven Teaching Learning Process.
Department Mission
• To inculcate an innovator by adopting student-centric, activity and outcome-based
teaching learning process in diversified areas of Computer Science and Engineering.
• To achieve global standards with technical transformations in education and value
based living through a social and scientific approach.
• To groom graduates with all-round leadership qualities, team spirit to meet the
requirements of industry, business and society
U23CS211 - PYTHON PROGRAMMING LABORATORY
Certified that this is the bonafide record of work done by …..…………..……………………..
in the………………………………………………………………………………laboratory of
this institution, as prescribed by the Autonomous Regulation …………………..for
the………………… Semester B.E/[Link]., during the academic year …………………..
Faculty in-charge: HOD:
Date: Date:
Register No
Submitted for the (……………………………………………………..) B.E/[Link].,
Examination Practical conducted on………………………………………………..
Internal Examiner External Examiner
INDEX
Pg
[Link]. DATE EXPERIMENT NAME MARK SIGN
No.
Average
Exp No:1a
EXCHANGE THE VALUES OF TWO VARIABLES
Date:
AIM:
To write a python program for exchanging the values of two variables.
ALGORITHM:
STEP1: Start
STEP2: Initialize two variables, a and b, with some values. STEP3: Print the values of a and b
before swapping.
STEP4: Exchange the values of a and b using a temporary variable. STEP5: Print the values of a
and b after swapping.
STEP6: Stop
PROGRAM:
# Exchange the values of two variables
a = int(input("Enter the value of a:"))
b = int(input("Enter the value of b:"))
print("Before swapping:")
print("a =", a)
print("b =", b)
# Using a temporary variable
temp = a
a=b
b = temp
print("\nAfter swapping:")
print("a =", a)
print("b =", b)
OUTPUT:
Enter the value of a:5
Enter the value of b:10
Before swapping:
a=5
b = 10
After swapping:
a = 10
b=5
RESULT:
The python program for exchanging the values of two variables was executed successfully and
output is verified.
Exp No:1b
CIRCULATE THE VALUES OF N VARIABLES
Date:
AIM:
To write a python program for circulating the values of n variables.
ALGORITHM:
STEP1: Start
STEP2: Initialize n variables with some values.
STEP3: Print the values of all variables before circulating.
STEP4: Circulate the values of the variables.
STEP5: Print the values of all variables after circulating.
STEP6: Stop
PROGRAM:
# Circulate the values of n variables
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))
d = int(input("Enter the value of d: "))
print("Before circulating:", a, b, c, d)
# Circulating values
temp = a
a=b
b=c
c=d
d = temp
print("\nAfter circulating:", a, b, c, d)
OUTPUT:
Enter the value of a: 5
Enter the value of b: 6
Enter the value of c: 7
Enter the value of d: 1
Before circulating: 5 6 7 1
After circulating: 6 7 1 5
RESULT:
The python program for circulating the values of n variables was executed successfully and output
is verified.
Exp No:2
CALCULATE DISTANCE BETWEEN TWO POINTS
Date:
AIM:
To write a python program for calculating the distance between two points.
ALGORITHM:
STEP1: Start
STEP2: Define the coordinates of two points.
STEP3: Calculate the distance using the distance formula.
STEP4: Print the calculated distance.
STEP5: Stop
PROGRAM:
import math
# Define the coordinates of two points
x1, y1 = 1, 2
x2, y2 = 4, 6
# Calculate the distance using the distance formula
distance = [Link]((x2 - x1)**2 + (y2 - y1)**2)
print("The distance between the two points is:", distance)
OUTPUT:
The distance between the two points is: 5.0
RESULT:
Thus, the python program for calculating the distance between two points was executed
successfully and output is verified.
Exp No:3
SIMPLE PROGRAM FOR HANDLING ERROR MESSAGES
Date:
AIM:
To write a python program for read user input, perform a simple operation (addition), and handle
basic errors without using functions.
ALGORITHM:
STEP1: Prompt the user to enter two numbers.
STEP2: Read the input from the user and convert it to integers. STEP3: Perform the addition
operation on the two numbers.
STEP4: Handle potential errors, such as invalid input or keyboard interrupts, using try-except
blocks.
STEP5: Print the result of the addition operation or an error message if an exception occurs.
PROGRAM:
try:
# Prompt the user to enter two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Perform the operation
result = num1 + num2
# Print the result
print("Result of the operation:", result)
except ValueError:
print("Error: Please enter valid numbers.")
except KeyboardInterrupt:
print("\nOperation interrupted by the user.")
except Exception as e:
print("Error:", e)
OUTPUT 1:
Enter the first number: 5
Enter the second number: s
Error: Please enter valid numbers.
OUTPUT 2:
Enter the first number: 5
Enter the second number: s
Error: Please enter valid numbers.
RESULT:
Thus, the python program for read user input, perform a simple operation (addition), and handle
basic errors without using functions was executed successfully and output is verified.
Exp No:4a
NUMBER SERIES
Date:
AIM:
To write a python program for generating different number series using iterative loops and
conditionals.
ALGORITHM:
STEP1: Start
STEP2: Prompt the user to input the type of number series to generate (e.g., Fibonacci, prime,
square).
STEP3: Depending on the user's choice, generate the corresponding number series using iterative
loops and conditionals.
STEP4: Print the generated number series.
STEP5: Stop
PROGRAM:
# Generate different types of number series
series_type = input("Enter the type of number series to generate (Fibonacci, Prime, Square):
").lower()
if series_type == "fibonacci":
n = int(input("Enter the number of terms: "))
a, b = 0, 1
count = 0
while count < n:
print(a, end=" ")
nth = a + b
a=b
b = nth
count += 1
elif series_type == "prime":
n = int(input("Enter the number of prime numbers to generate: "))
num = 2
prime_count = 0
while prime_count < n:
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
prime_count += 1
num += 1
elif series_type == "square":
n = int(input("Enter the limit for generating square numbers: "))
for i in range(1, n + 1):
print(i * i, end=" ")
else:
print("Invalid series type. Please choose from Fibonacci, Prime, or Square.")
OUTPUT 1:
Enter the type of number series to generate (Fibonacci, Prime, Square): fibonacci
Enter the number of terms: 10
0 1 1 2 3 5 8 13 21 34
OUTPUT 2:
Enter the type of number series to generate (Fibonacci, Prime, Square): prime
Enter the number of prime numbers to generate: 10
2 3 5 7 11 13 17 19 23 29
OUTPUT 3:
Enter the type of number series to generate (Fibonacci, Prime, Square): square
Enter the limit for generating square numbers: 7
1 4 9 16 25 36 49
RESULT:
Thus, the python program for generating different number series using iterative loops and
conditionals was executed successfully and output is verified.
Exp No:4b
NUMBER PATTERNS
Date:
AIM:
To write a python program for printing a number pattern using iterative loops and conditionals
ALGORITHM:
STEP 1: Start
STEP 2: Prompt the user to input the type of number pattern to print (e.g., triangle, diamond,
Pascal's triangle).
STEP 3: Depending on the user's choice, generate and print the corresponding number pattern
using iterative loops and conditionals.
STEP 4: Stop
PROGRAM:
# Print different types of number patterns
pattern_type = input("Enter the type of number pattern to print (Triangle, Diamond, Pascal):
").lower()
if pattern_type == "triangle":
rows = int(input("Enter the number of rows for the triangle pattern: "))
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end=" ")
print()
elif pattern_type == "diamond":
rows = int(input("Enter the number of rows for the diamond pattern: "))
for i in range(1, rows + 1):
print(" " * (rows - i) + " ".join(map(str, list(range(1, i + 1)))) + " " + " ".join(map(str,
list(range(i - 1, 0, -1)))))
for i in range(rows - 1, 0, -1):
print(" " * (rows - i) + " ".join(map(str, list(range(1, i + 1)))) + " " + " ".join(map(str,
list(range(i - 1, 0, -1)))))
elif pattern_type == "pascal":
rows = int(input("Enter the number of rows for Pascal's triangle: "))
for i in range(rows):
print(" " * (rows - i), end="")
coef = 1
for j in range(1, i + 2):
print(coef, end=" ")
coef = int(coef * (i - j + 1) / j)
print()
else:
print("Invalid pattern type. Please choose from Triangle, Diamond, or Pascal.")
OUTPUT 1:
Enter the type of number pattern to print (Triangle, Diamond, Pascal): triangle
Enter the number of rows for the triangle pattern: 5
1
12
123
1234
12345
OUTPUT 2:
Enter the type of number pattern to print (Triangle, Diamond, Pascal): diamond
Enter the number of rows for the diamond pattern: 5
1
121
12321
1234321
123454321
1234321
12321
121
1
OUTPUT 3:
Enter the type of number pattern to print (Triangle, Diamond, Pascal): pascal
Enter the number of rows for Pascal's triangle: 5
1
11
121
1331
14641
RESULT:
Thus, the python program for printing a number pattern using iterative loops and conditionals was
executed successfully and output is verified.
Exp No:4c
PYRAMID PATTERN
Date:
AIM:
To write a python program for printing a pyramid pattern using iterative loops and conditionals.
ALGORITHM:
STEP1: Start
STEP2: Prompt the user to input the number of rows for the pyramid pattern.
STEP3: Generate and print the pyramid pattern using iterative loops and conditionals.
STEP4: Stop
PROGRAM:
# Print a pyramid pattern of asterisks
rows = int(input("Enter the number of rows for the pyramid pattern: "))
for i in range(1, rows + 1):
print(" " * (rows - i) + "* " * i)
OUTPUT:
Enter the number of rows for the pyramid pattern: 6
*
**
***
****
*****
******
RESULT:
Thus, the python program for printing a pyramid pattern using iterative loops and conditionals was
executed successfully and output is verified.
Exp No:5a
FACTORIAL OF A NUMBER USING FUNCTION
Date:
AIM:
To write a python program for calculating the factorial of a given number using a function.
ALGORITHM:
STEP1: Start
STEP2: Define a function factorial(n) that takes an integer n as input.
STEP3: Initialize a variable result to 1.
STEP4: Use a for loop to iterate from 1 to n (inclusive).
STEP5: Multiply result by the current value of i.
STEP6: Return the value of result.
STEP7: Stop
PROGRAM:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
num = int(input("Enter a number to calculate its factorial: "))
print("Factorial of", num, "is:", factorial(num))
OUTPUT:
Enter a number to calculate its factorial: 6
Factorial of 6 is: 720
RESULT:
Thus, the python program for calculating the factorial of a given number using a function was
executed successfully and output is verified.
Exp No:5b
LARGEST NUMBER IN A LIST USING FUNCTION
Date:
AIM:
To write a python program for finding the largest number in a given list using a function.
ALGORITHM:
STEP1: Start
STEP2: Define a function find_largest(lst) that takes a list lst as input.
STEP3: Initialize a variable max_num to the first element of the list.
STEP4: Use a for loop to iterate through each element of the list.
STEP5: If the current element is greater than max_num, update max_num to the current element.
STEP6: Return the value of max_num.
STEP7: Stop
PROGRAM:
def find_largest(lst):
max_num = lst[0]
for num in lst:
if num > max_num:
max_num = num
return max_num
numbers = [int(x) for x in input("Enter a list of numbers separated by space: ").split()]
print("The largest number in the list is:", find_largest(numbers))
OUTPUT:
Enter a list of numbers separated by space: 22 56 12 17 9 1 33
The largest number in the list is: 56
RESULT:
Thus, the python program for finding the largest number in a given list using a function was
executed successfully and output is verified.
Exp No:6a
VALIDATING EMAIL ADDRESS USING REGULAR
Date: EXPRESSIONS
AIM:
To write a python program for validating email addresses using regular expressions.
ALGORITHM:
STEP1: Start
STEP2: Import the re module for regular expressions.
STEP3: Define a function validate_email(email) that takes an email address as input. STEP4: Use
a regular expression pattern to validate the email address format.
STEP5: Return True if the email address is valid, otherwise return False.
STEP6: Stop
PROGRAM:
import re
def validate_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
if [Link](pattern, email):
return True
else:
return False
email = input("Enter an email address to validate: ")
if validate_email(email):
print("Valid email address.")
else:
print("Invalid email address.")
OUTPUT 1:
Enter an email address to validate: [Link]
Invalid email address.
OUTPUT 2:
Enter an email address to validate: contactus@[Link]
Valid email address.
RESULT:
Thus, the python program for validating email addresses using regular expressions was executed
successfully and output is verified.
Exp No:6b
EXTRACTING PHONE NUMBERS FROM TEXT USING
Date: REGULAR EXPRESSION
AIM:
To write a python program for extracting phone numbers from a given text using regular
expressions.
ALGORITHM:
STEP1: Start
STEP2: Import the re module for regular expressions.
STEP3: Define a function extract_phone_numbers(text) that takes a text as input. STEP4: Use a
regular expression pattern to find phone numbers in the text.
STEP5: Return a list of all phone numbers found in the text.
STEP6: Stop
PROGRAM:
import re
def extract_phone_numbers(text):
pattern = r'\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b'
return [Link](pattern, text)
text = "Contact us at 123-456-7890 or 987.654.3210 for assistance."
phone_numbers = extract_phone_numbers(text)
print("Phone numbers found in the text:", phone_numbers)
INPUT:
text = "Contact us at 123-456-7890 or 987.654.3210 for assistance."
OUTPUT:
Phone numbers found in the text: ['123-456-7890', '987.654.3210']
RESULT:
Thus, the python program for extracting phone numbers from a given text using regular
expressions was executed successfully and output is verified.
Exp No:7a
REVERSING A STRING
Date:
AIM:
To write a python program for reversing a given string.
ALGORITHM:
STEP1: Start
STEP2: Define a function reverse_string(s) that takes a string s as input.
STEP3: Use for to reverse the string.
STEP4: Return the reversed string.
STEP5: Stop
PROGRAM:
def reverse_string(s):
reversed_str = ""
for i in range(len(s) - 1, -1, -1):
reversed_str += s[i]
return reversed_str
# Test the function
string = input("Enter a string to reverse: ")
reversed_string = reverse_string(string)
print("Reversed string:", reversed_string)
OUTPUT:
Enter a string to reverse: program
Reversed string: margorp
RESULT:
Thus, the python program for reversing a given string was executed successfully and output is
verified.
Exp No:7b
PALINDROME OR NOT
Date:
AIM:
To write a python program for checking if the given string is a palindrome or not.
ALGORITHM:
STEP1: Take the input string from the user.
STEP2: Remove any non-alphanumeric characters from the input string and convert it to
lowercase.
STEP3: Compare the cleaned string with its reverse.
STEP4: If the cleaned string is equal to its reverse, print "The string is a palindrome." STEP5:
Otherwise, print "The string is not a palindrome."
PROGRAM:
def is_palindrome(s):
# Convert string to lowercase and remove non-alphanumeric characters
cleaned_string = ''.join([Link]()
for char in s
if [Link]())
# Compare the cleaned string with its reverse
return cleaned_string == cleaned_string[::-1]
# Test the function
string = input("Enter a string to check for palindrome: ")
if is_palindrome(string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
OUTPUT 1:
Enter a string to check for palindrome: student
The string is not a palindrome.
OUTPUT 2:
Enter a string to check for palindrome: malayalam
The string is a palindrome.
RESULT:
Thus, the python program for checking if the given string is a palindrome or not was executed
successfully and output is verified.
Exp No:8
IMPLEMENTING REAL TIME APPLICATION USING LIST,
Date: TUPLES
AIM:
To write a python program for managing the items present in a library and perform various
operations on lists and tuples, such as adding items, removing items, and displaying the available
items.
ALGORITHM:
STEP1: Start
STEP2: Define a list library to store the items present in the library. Each item in the library will
be represented as a tuple containing the item's name, author/artist, and availability status.
STEP3: Implement functions to perform the following operations:
● Add an item to the library.
● Remove an item from the library.
● Display all items in the library along with their availability status. STEP4: Initialize the
library with some initial items.
STEP5: Display a menu to the user with options to add, remove, or display items, and an option to
exit the program.
STEP6: Depending on the user's choice, perform the corresponding operation and display the
updated library.
STEP7: Repeat steps 5-6 until the user chooses to exit the program.
STEP8: Stop
PROGRAM:
def add_item(library, item):
[Link](item)
def remove_item(library, item_name):
removed = False
library[:] = [item for item in library if item[0] != item_name]
if removed:
print("Item removed successfully.")
else:
print("Item not found in the library.")
def display_library(library):
print("Items in the library:")
for item in library:
print("- Name:", item[0])
print(" Author/Artist:", item[1])
print(" Availability:", "Available" if item[2] else "Not Available")
print()
def main():
library = [
("Book1", "Author1", True),
("Book2", "Author2", False),
("CD1", "Artist1", True),
("CD2", "Artist2", True)
]
while True:
print("\nLibrary Management System")
print("1. Add Item")
print("2. Remove Item")
print("3. Display Library")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
try:
name = input("Enter item name: ")
author_artist = input("Enter author/artist name: ")
availability = input("Is the item available? (True/False): ").strip().lower() == 'true'
add_item(library, (name, author_artist, availability))
print("Item added successfully.")
except Exception as e:
print("Error:", e)
elif choice == '2':
try:
name = input("Enter item name to remove: ")
remove_item(library, name)
except Exception as e:
print("Error:", e)
elif choice == '3':
display_library(library)
elif choice == '4':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please enter a valid option.")
if __name__ == "__main__":
main()
OUTPUT:
Library Management System
1. Add Item
2. Remove Item
3. Display Library
4. Exit
Enter your choice: 1
Enter item name: Book1
Enter author/artist name: lavan
Is the item available? (True/False): true
Item added successfully.
Library Management System
1. Add Item
2. Remove Item
3. Display Library
4. Exit
Enter your choice: 3
Items in the library:
- Name: Book1
Author/Artist: Author1
Availability: Available
- Name: Book2
Author/Artist: Author2
Availability: Not Available
- Name: CD1
Author/Artist: Artist1
Availability: Available
- Name: CD2
Author/Artist: Artist2
Availability: Available
- Name: Book1
Author/Artist: lavan
Availability: Available
Library Management System
1. Add Item
2. Remove Item
3. Display Library
4. Exit
Enter your choice: 4
Exiting program. Goodbye!
RESULT:
Thus, the python program for managing the items present in a library and perform various
operations on lists and tuples, such as adding items, removing items, and displaying the available
items was executed successfully and output is verified.
Exp No:9a
COPYING FROM ONE FILE TO ANOTHER
Date:
AIM:
To write a python program for copying the contents of one file to another.
ALGORITHM:
STEP1: Open the source file in read mode and the destination file in write mode.
STEP2: Read the content from the source file.
STEP3: Write the read content to the destination file.
STEP4: Close both files after copying is completed.
PROGRAM:
def copy_file(soc, dest):
with open(soc, 'r') as source:
with open(dest, 'w') as destination:
[Link]([Link]())
print("Content copied successfully from", soc, "to", dest)
# Test the function
copy_file("[Link]", "[Link]")
INPUT:
Source file:
Destination file
OUTPUT:
Source file:
Destination file
RESULT:
Thus, the python program for copying the contents of one file to another was executed
successfully and output is verified.
Exp No:9b
COUNTING THE WORDS IN A FILE
Date:
AIM:
To write a python program for counting the number of words in a file.
ALGORITHM:
STEP1: Open the file in read mode.
STEP2: Read the content of the file.
STEP3: Split the content into words using the split() method.
STEP4: Count the number of words in the list of words.
STEP5: Close the file after counting is completed.
STEP6: Stop
PROGRAM:
def word_count(soc):
with open(soc, 'r') as file:
content = [Link]()
words = [Link]()
return len(words)
# Test the function
word_count_result = word_count("[Link]")
print("Word count:", word_count_result)
INPUT:
OUTPUT:
RESULT:
Thus, the python program for counting the number of words in a file was executed successfully and
output is verified.
Exp No:9c
FINDING THE LONGEST WORD IN A FILE
Date:
AIM:
To write a python program for finding the longest word in a file.
ALGORITHM:
STEP1: Open the file in read mode.
STEP2: Read the content of the file.
STEP3: Split the content into words using the split() method.
STEP4: Iterate over each word in the list of words and find the length of each word. STEP5: Keep
track of the longest word encountered.
STEP6: Close the file after finding the longest word.
PROGRAM:
def longest_word(soc):
with open(soc, 'r') as file:
content = [Link]()
words = [Link]()
longest = max(words, key=len)
return longest
# Test the function
longest = longest_word("[Link]")
print("Longest word:", longest)
INPUT:
OUTPUT:
RESULT:
Thus, the python program for finding the longest word in a file was executed successfully and
output is verified.
Exp No:10
PYTHON PROGRAM USING OOP
Date:
AIM:
To write a python program for implementing Object-Oriented Programming (OOP) concepts by
creating a simple class to represent a bank account and demonstrating its functionalities.
ALGORITHM:
STEP1: Define a class named BankAccount to represent a bank account.
STEP2: Inside the class, define an init method to initialize the attributes of the bank account,
such as account number, account holder name, and balance.
STEP3: Implement methods within the class to perform operations like depositing money,
withdrawing money, and displaying the account details.
STEP4: Create instances of the BankAccount class and demonstrate the usage of attributes and
methods to manage bank accounts effectively.
PROGRAM:
class BankAccount:
def __init__(self, acc_number, acc_holder, balance=0):
self.acc_number = acc_number
self.acc_holder = acc_holder
[Link] = balance
def deposit(self, amount):
[Link] += amount
print(f"Amount {amount} deposited successfully.")
def withdraw(self, amount):
if amount <= [Link]:
[Link] -= amount
print(f"Amount {amount} withdrawn successfully.")
else:
print("Insufficient balance!")
def display_account_details(self):
print("Account Number:", self.acc_number)
print("Account Holder:", self.acc_holder)
print("Balance:", [Link])
# Create instances of the BankAccount class
account1 = BankAccount("123456", "Alice")
account2 = BankAccount("789012", "Bob", 1000)
# Perform operations on bank accounts
print("Account 1 Details:")
account1.display_account_details()
[Link](500)
[Link](200)
print("Updated Account 1 Details:")
account1.display_account_details()
print("\nAccount 2 Details:")
account2.display_account_details()
[Link](1500)
account2.display_account_details()
OUTPUT:
Account 1 Details:
Account Number: 123456
Account Holder: Alice
Balance: 0
Amount 500 deposited successfully.
Amount 200 withdrawn successfully.
Updated Account 1 Details:
Account Number: 123456
Account Holder: Alice
Balance: 300
Account 2 Details:
Account Number: 789012
Account Holder: Bob
Balance: 1000
Insufficient balance!
Account Number: 789012
Account Holder: Bob
Balance: 1000
RESULT:
Thus, the python program for implementing Object-Oriented Programming (OOP) concepts was
executed successfully and output is verified.
Exp No:11
PYTHON PROGRAM USING IMAGE PROCESSING
Date:
AIM:
To write a python program for performing basic image processing operations using Python.
ALGORITHM:
STEP1: Read an image file using a suitable library (e.g., OpenCV).
STEP2: Perform image processing operations, such as resizing, blurring, or edge detection.
STEP3: Display the original and processed images.
STEP4: Save the processed image to a file, if needed.
PROGRAM:
import cv2
# Read an image file
image = [Link]('input_image.jpg')
# Display the original image
[Link]('Original Image', image) [Link](0)
# Perform image processing operations (e.g., resizing, blurring, edge detection)
# For example, let's resize the image to half its original size
resized_image = [Link](image, None, fx=0.5, fy=0.5)
# Display the resized image
[Link]('Resized Image', resized_image)
[Link](0)
# Save the processed image to a file
[Link]('output_image.jpg', resized_image)
# Close all OpenCV windows
[Link]()
OUTPUT:
Input Image: size 10kb
Output Image:7kb
RESULT:
Thus, the python program for performing basic image processing operations was executed
successfully and output is verified.
Exp No:12
PYTHON PROGRAM USING NETWORKING
Date:
AIM:
To write a python program for performing simple TCP client server connection using Python.
ALGORITHM:
STEP1: Implement a server program that listens for incoming connections on a specific port.
STEP2: Implement a client program that connects to the server's IP address and port.
STEP3: Define a protocol for communication between the client and server (e.g., sending and
receiving messages).
STEP4: Handle incoming client connections on the server side and respond to client requests.
STEP5: Close the connection when the communication is complete.
PROGRAM:
Program 1 for server
import socket
# Define server settings
HOST = '[Link]' # Localhost
PORT = 12345 # Port to listen on
# Create a socket object
server_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the host and port
server_socket.bind((HOST, PORT))
# Listen for incoming connections
server_socket.listen()
print("Server is listening for incoming connections...")
# Accept incoming connections
client_socket, client_address = server_socket.accept()
print("Connected to client:", client_address)
# Receive data from the client
data = client_socket.recv(1024) print("Received:", [Link]())
# Send a response back to the client
message = "Hello from the server!"
client_socket.sendall([Link]())
# Close the connection
client_socket.close() server_socket.close()
Program 2 for client
import socket
# Define server settings
HOST = '[Link]' # Localhost
PORT = 12345 # Port to connect to
# Create a socket object
client_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
client_socket.connect((HOST, PORT))
# Send data to the server
message = "Hello from the client!"
client_socket.sendall([Link]())
# Receive response from the server
response = client_socket.recv(1024)
print("Received response from server:", [Link]())
# Close the connection
client_socket.close()
OUTPUT:
Server Window:
Server is listening for incoming connections…
Connected to Client: (‘[Link]’, 60643)
Received: Hello from the client!
Client Window:
Received response from server: Hello from the server!
RESULT:
Thus, the python program for performing simple TCP client server connection using Python was
executed successfully and output is verified.