Python Programming Lab Manual
Python Programming Lab Manual
COLLEGE OF ENGINEERING
(AUTONOMOUS)
[Link], NELLORE (DIST)
PYTHON
PROGRAMMING LAB
MANUAL
(R- 23 REGULATION)
II BTECH CSE –I SEM
DEPARTMENT
OF
ARTIFICIAL INTELLIGENCE AND MACHINE
LEARNING
NAME OF THE STUDENT
ROLL NO
YEAR
BRANCH
SREE VENKATESWARA COLLEGE OF ENGINEERING
NAAC ‘A’ Grade Accredited
Institution An ISO 9001: 2015
Certified Institution
(Approved by AICTE, New Delhi and Affiliated to JNTU, Anantapur)
Northrajupalem (Vi), Kodavaluru (M) , S.P.S.R Nellore (Dt)-524316
PEO-3: To train the graduates to have basic interpersonal skills and a sense
of social responsibility that covers them a way to become good team members
and leaders.
SREE VENKATESWARA COLLEGE OF ENGINEERING
NAAC ‘A’ Grade Accredited
Institution An ISO 9001:: 2015
Certified Institution
(Approved by AICTE, New Delhi and Affiliated to JNTU, Anantapur)
Northrajupalem (Vi), Kodavaluru (M) , S.P.S.R Nellore (Dt)-524316
UNIT-1
Program-1:
Aim: Write a program to find the largest element among three Numbers
Program:
# Function to find the largest of three numbers
def find_largest(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
return largest
# Input three numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
# Find and print the largest number
largest = find_largest(num1, num2, num3)
print(f"The largest number among {num1}, {num2}, and {num3} is {largest}")
Output:
Program-2:
Program:
# Function to check if a number is prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
# Function to find all prime numbers in a given interval
def find_primes(start, end):
primes = []
for num in range(start, end + 1):
if is_prime(num):
[Link](num)
return primes
# Input the interval
start = int(input("Enter the starting number of the interval: "))
end = int(input("Enter the ending number of the interval: "))
# Find and print all prime numbers in the interval
primes = find_primes(start, end)
print(f"Prime numbers between {start} and {end} are: {primes}")
Output:
Program-3:
Aim: Write a program to swap two numbers without using a temporary variable
Program:
# Function to swap two numbers
def swap_numbers(a, b):
print(f"Before swapping: a = {a}, b = {b}")
a, b = b, a # Swapping using tuple unpacking
print(f"After swapping: a = {a}, b = {b}")
return a, b
# Input two numbers
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
# Swap and display the numbers
swap_numbers(a, b)
Output:
Program-4:
Program:
def demonstrate_operators():
a = 10
b=3
c = None
print(f"Arithmetic Operators:")
print(f"Addition: {a} + {b} = {a + b}")
print(f"Subtraction: {a} - {b} = {a - b}")
print(f"Multiplication: {a} * {b} = {a * b}")
print(f"Division: {a} / {b} = {a / b}")
print(f"Modulus: {a} % {b} = {a % b}")
print(f"Exponentiation: {a} ** {b} = {a ** b}")
print(f"Floor Division: {a} // {b} = {a // b}")
print(f"Relational Operators:")
print(f"{a} > {b}: {a > b}")
print(f"{a} < {b}: {a < b}")
print(f"{a} == {b}: {a == b}")
print(f"{a} != {b}: {a != b}")
print(f"{a} >= {b}: {a >= b}")
print(f"{a} <= {b}: {a <= b}")
print(f"Assignment Operators:")
c=a+b
print(f"c = a + b: c = {c}")
c += a
print(f"c += a: c = {c}")
c -= a
print(f"c -= a: c = {c}")
c *= a
print(f"c *= a: c = {c}")
c /= a
print(f"c /= a: c = {c}")
c %= a
print(f"c %= a: c = {c}")
c **= b
print(f"c **= b: c = {c}")
c //= b
print(f"c //= b: c = {c}")
print(f"Logical Operators:")
print(f"a > 5 and b < 5: {a > 5 and b < 5}")
print(f"a > 5 or b > 5: {a > 5 or b > 5}")
print(f"not(a > 5): {not(a > 5)}")
print(f"Bitwise Operators:")
print(f"a = {a} ({bin(a)})")
print(f"b = {b} ({bin(b)})")
print(f"a & b: {a & b} ({bin(a & b)})")
print(f"a | b: {a | b} ({bin(a | b)})")
print(f"a ^ b: {a ^ b} ({bin(a ^ b)})")
print(f"~a: {~a} ({bin(~a)})")
print(f"a << 2: {a << 2} ({bin(a << 2)})")
print(f"a >> 2: {a >> 2} ({bin(a >> 2)})")
print(f"Ternary Operator:")
max_value = a if a > b else b
print(f"Max value between a and b: {max_value}")
print(f"Membership Operators:")
my_list = [1, 2, 3, 4, 5]
print(f"a in my_list: {a in my_list}")
print(f"b in my_list: {b in my_list}")
print(f"6 not in my_list: {6 not in my_list}")
print(f"Identity Operators:")
x=5
y=5
print(f"x is y: {x is y}")
print(f"x is not y: {x is not y}")
z = [1, 2, 3]
w = [1, 2, 3]
print(f"z is w: {z is w}")
print(f"z is not w: {z is not w}")
demonstrate_operators()
Output:
Program-5:
Aim: Write a program to add and multiply complex numbers
Program:
# Function to add two complex numbers
def add_complex_numbers(c1, c2):
return c1 + c2
# Function to multiply two complex numbers
def multiply_complex_numbers(c1, c2):
return c1 * c2
# Input two complex numbers
c1 = complex(input("Enter the first complex number (in the form a+bj): "))
c2 = complex(input("Enter the second complex number (in the form a+bj): "))
# Add and multiply the complex numbers
sum_result = add_complex_numbers(c1, c2)
product_result = multiply_complex_numbers(c1, c2)
# Display the results
print(f"The sum of {c1} and {c2} is {sum_result}")
print(f"The product of {c1} and {c2} is {product_result}")
Output:
Program-6:
Program:
# Function to print the multiplication table of a given number
def print_multiplication_table(number, up_to=10):
print(f"Multiplication Table for {number}:")
for i in range(1, up_to + 1):
print(f"{number} x {i} = {number * i}")
# Input the number for which the multiplication table is to be printed
number = int(input("Enter the number to print the multiplication table: "))
up_to = int(input("Enter the range up to which the multiplication table should be printed
(default is 10): ") or 10)
# Print the multiplication table
print_multiplication_table(number, up_to)
Output:
UNIT-2
Program-7:
Output:
Program-8:
Output:
Program-9:
Aim: Write a program to find the length of the string without using any library functions.
Program:
def find_string_length(string):
"""Calculates the length of a string without using any library functions."""
count = 0
for char in string:
count += 1
return count
user_input = input("Enter a string: ")
length = find_string_length(user_input)
print("Length of the string:", length)
Output:
Program-10:
Aim: Write a program to check if the substring is present in a given string or not.
Program:
def is_substring_present(main_string, sub_string):
main_len = len(main_string)
sub_len = len(sub_string)
for i in range(main_len - sub_len + 1):
if main_string[i:i + sub_len] == sub_string:
return True
return False
# Get user input
main_string = input("Enter the main string: ")
sub_string = input("Enter the substring to check: ")
# Check if the substring is present
result = is_substring_present(main_string, sub_string)
# Print the result
if result:
print(f"The substring '{sub_string}' is present in the string '{main_string}'.")
else:
print(f"The substring '{sub_string}' is not present in the string '{main_string}'.")
Output:
Program-11:
Aim: Write a program to perform any 5 built-in functions by taking any list.
Program:
# Function to get a list of numbers from user input
def get_user_list():
user_input = input("Enter a list of numbers separated by spaces: ")
# Convert input string to a list of integers
number_list = list(map(int, user_input.split()))
return number_list
# Function to display the results of various built-in functions on the list
def display_list_functions(number_list):
print("List:", number_list)
print("Length of the list:", len(number_list))
print("Maximum value in the list:", max(number_list))
print("Minimum value in the list:", min(number_list))
print("Sum of the list elements:", sum(number_list))
print("Sorted list:", sorted(number_list))
# Main program execution
if name == " main ":
numbers = get_user_list()
display_list_functions(numbers)
Output:
UNIT-3
Program-13:
Aim: Write a program to create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated tuples.
Program:
def get_member_details():
# Get details for a member from user input
name = input("Enter name: ")
age = int(input("Enter age: "))
address = input("Enter address: ")
college = input("Enter college: ")
return (name, age, address, college)
# Get details for two members
print("Enter details for the first member:")
member1 = get_member_details()
print("Enter details for the second member:")
member2 = get_member_details()
# Concatenate the tuples
concatenated_tuples = member1 + member2
# Print the concatenated tuples
print("\nConcatenated Tuples:")
print(concatenated_tuples)
Output:
PS D:\python\2-1 lab> py [Link]
Enter details for the first member:
Enter name: John
Enter age: 21
Enter address: Nellore
Enter college: SVCN
Enter details for the second member:
Enter name: Jack
Enter age: 20
Enter address: Rajupalem
Enter college: SVEN
Concatenated Tuples:
('John', 21, 'Nellore', 'SVCN', 'Jack', 20, 'Rajupalem', 'SVEN')
PS D:\python\2-1 lab>
Program-14:
Aim: Write a program to count the number of vowels in a string (No control flow
allowed).
Program:
def count_vowels(s):
# Define vowels
vowels = "aeiouAEIOU"
# Use a list comprehension to filter out vowels and then get the length of the list
vowel_count = sum(char in vowels for char in s)
return vowel_count
# Example usage
input_string = input("Enter a string: ")
print("Number of vowels:", count_vowels(input_string))
Output:
Program-15:
Output:
Program-16:
Output:
Program-17:
Output:
UNIT-4
Program-18:
Aim: Write a program to sort words in a file and put them in another file. The output file
should have only lower-case words, so any upper-case words from source must be
lowered.
Program:
def sort_and_lower_words(input_file, output_file):
try:
# Read words from the input file
with open(input_file, 'r') as file:
words = [Link]().split()
# Convert words to lower case and sort them
sorted_words = sorted([Link]() for word in words)
# Write sorted words to the output file
with open(output_file, 'w') as file:
for word in sorted_words:
[Link](word + '\n')
print(f"Sorted words have been written to {output_file}")
except FileNotFoundError:
print(f"The file {input_file} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
input_file = '[Link]' # Replace with your input file name
output_file = '[Link]' # Replace with your output file name
sort_and_lower_words(input_file, output_file)
Input File: // Create a file named [Link] in the same directory as your Python script and
add the following words:
Apple
banana
Cherry
date
Elderberry
FIG
Grape
ORANGE
Output File:
Program-19:
Aim: Write a Python program to print each line of a file in reverse order.
Program:
def reverse_lines_in_file(filename):
try:
with open(filename, 'r') as file:
lines = [Link]()
for line in lines:
print([Link]()[::-1])
except FileNotFoundError:
print(f"The file {filename} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Replace '[Link]' with the path to your file
reverse_lines_in_file('[Link]')
Input file: // Create a file named [Link] in the same directory as your Python script
and add the following lines:
Hello, world!
Python programming is fun.
Reverse these lines.
Output:
Program-20:
Aim: Python program to compute the number of characters, words and lines in a file.
Program:
def compute_file_statistics(filename):
try:
with open(filename, 'r') as file:
lines = [Link]()
num_lines = len(lines)
num_words = sum(len([Link]()) for line in lines)
num_chars = sum(len(line) for line in lines)
print(f"Number of lines: {num_lines}")
print(f"Number of words: {num_words}")
print(f"Number of characters: {num_chars}")
except FileNotFoundError:
print(f"The file {filename} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Replace '[Link]' with the path to your file
compute_file_statistics('[Link]')
Input file: // Create a file named [Link] in the same directory as your Python script
and add the following lines:
Hello, world!
Python programming is fun.
Count these lines, words, and characters.
Output:
Program-21:
Aim: Write a program to create, display, append, insert and reverse the order of the items
in the array.
Program:
def display_array(arr):
print("Current array:", arr)
def main():
array = []
while True:
print("\nOptions:")
print("1. Create an array")
print("2. Display the array")
print("3. Append an item")
print("4. Insert an item")
print("5. Reverse the array")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == '1':
array = input("Enter elements separated by spaces: ").split()
print("Array created.")
elif choice == '2':
display_array(array)
elif choice == '3':
item = input("Enter item to append: ")
[Link](item)
print(f"Item '{item}' appended.")
elif choice == '4':
item = input("Enter item to insert: ")
index = int(input("Enter position to insert at (0-based index): "))
if 0 <= index <= len(array):
[Link](index, item)
print(f"Item '{item}' inserted at position {index}.")
else:
print("Invalid index.")
elif choice == '5':
[Link]()
print("Array reversed.")
elif choice == '6':
print("Exiting.")
break
else:
print("Invalid choice. Please try again.")
if name == " main ":
main()
Output:
Program-22:
Output:
Program-23:
Aim: Write a Python program to create a class that represents a shape. Include methods to
calculate its area and perimeter. Implement subclasses for different shapes like circle,
triangle, and square.
Program:
import math
class Shape:
def area(self):
raise NotImplementedError
def perimeter(self):
raise NotImplementedError
class Circle(Shape):
def init (self):
[Link] = float(input("Enter the radius of the circle: "))
def area(self):
return [Link] * [Link]**2
def perimeter(self):
return 2 * [Link] * [Link]
class Triangle(Shape):
def init (self):
self.side1 = float(input("Enter the first side of the triangle: "))
self.side2 = float(input("Enter the second side of the triangle: "))
self.side3 = float(input("Enter the third side of the triangle: "))
def area(self):
s = (self.side1 + self.side2 + self.side3) / 2
return [Link](s * (s - self.side1) * (s - self.side2) * (s - self.side3))
def perimeter(self):
return self.side1 + self.side2 + self.side3
class Square(Shape):
def init (self):
[Link] = float(input("Enter the side of the square: "))
def area(self):
return [Link]**2
def perimeter(self):
return 4 * [Link]
def main():
shape_type = input("Enter the shape type (circle, triangle, square): ")
if shape_type == "circle":
shape = Circle()
elif shape_type == "triangle":
shape = Triangle()
elif shape_type == "square":
shape = Square()
else:
print("Invalid shape type")
return
print("Area:", [Link]())
print("Perimeter:", [Link]())
if name == " main ":
main()
Output:
UNIT-5
Program-24:
Aim: Python program to check whether a JSON string contains complex object or not.
Program:
import json
def is_complex_object(data):
"""Check if the given data contains a complex object (nested dictionaries or lists)."""
if isinstance(data, dict):
for key, value in [Link]():
if isinstance(value, (dict, list)):
return True
if is_complex_object(value):
return True
elif isinstance(data, list):
for item in data:
if isinstance(item, (dict, list)):
return True
if is_complex_object(item):
return True
return False
def check_json_complexity(json_string):
"""Check if the JSON string contains a complex object."""
try:
data = [Link](json_string)
except [Link]:
print("Invalid JSON string.")
return False
return is_complex_object(data)
def main():
# Take JSON string input from the user
json_string = input("Enter a JSON string to check: ")
# Check if the JSON string contains a complex object
if check_json_complexity(json_string):
print("The JSON string contains a complex object.")
else:
print("The JSON string does not contain a complex object.")
if name == " main ":
main()
Output:
Program-25:
Aim: Python Program to demonstrate NumPy arrays creation using array () function.
Program:
import numpy as np
def create_array_from_input():
# Prompt the user to enter values for the array
input_values = input("Enter values separated by spaces: "
# Split the input string into a list of strings
input_list = input_values.split()
# Convert the list of strings to a list of floats
input_list = [float(value) for value in input_list]
# Create a NumPy array from the list
numpy_array = [Link](input_list)
return numpy_array
# Call the function and display the result
array = create_array_from_input()
print("NumPy Array created:")
print(array)
Output:
Program-26:
Output:
Program-27:
Aim: Python program to demonstrate basic slicing, integer and Boolean indexing.
Program:
# Import the numpy library for array operations
import numpy as np
# Function to demonstrate slicing
def slicing_example(arr):
print("\nSlicing Example:")
start = int(input("Enter the start index: "))
stop = int(input("Enter the stop index: "))
print(f"Slice from index {start} to {stop}:")
print(arr[start:stop])
# Function to demonstrate integer indexing
def integer_indexing_example(arr):
print("\nInteger Indexing Example:")
index = int(input("Enter the index of the element to access: "))
print(f"Element at index {index}:")
print(arr[index])
indices = input("Enter multiple indices (space-separated): ")
indices = [int(x) for x in [Link]()]
print(f"Elements at indices {indices}:")
print(arr[indices])
# Function to demonstrate Boolean indexing
def boolean_indexing_example(arr):
print("\nBoolean Indexing Example:")
threshold = int(input("Enter the threshold value: "))
mask = arr > threshold
print(f"Elements greater than {threshold}:")
print(arr[mask])
# Main function
def main():
# Create a sample array
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("Sample Array:")
print(arr)
# Call the example functions
slicing_example(arr)
integer_indexing_example(arr)
boolean_indexing_example(arr)
if name == " main ":
main()
Output:
Program-28:
Aim: Python program to find min, max, sum, cumulative sum of array
Program:
import numpy as np
def main():
# Take user input for the array
user_input = input("Enter the elements of the array separated by spaces: ")
arr = [Link]([int(x) for x in user_input.split()])
# Find the minimum value in the array
min_value = [Link](arr)
print(f"\nMinimum value: {min_value}")
# Find the maximum value in the array
max_value = [Link](arr)
print(f"Maximum value: {max_value}")
# Calculate the sum of all elements in the array
sum_value = [Link](arr)
print(f"Sum of all elements: {sum_value}")
# Calculate the cumulative sum of the array
cumulative_sum = [Link](arr)
print(f"Cumulative sum of the array: {cumulative_sum}")
if name == " main ":
main()
Output:
Program-29:
Aim: Create a dictionary with at least five keys and each key represent value as a list where
this list contains at least ten values and convert this dictionary as a pandas data frame and
explore the data through the data frame as follows:
A) Apply head () function to the pandas data frame
B) Perform various data selection operations on Data Frame
Program:
import pandas as pd
# Create a dictionary with five keys, each representing a list of ten values from user input
data_dict = {}
for i in range(5):
key = input(f"Enter key {i+1}: ")
values = []
for j in range(10):
value = input(f"Enter value {j+1} for key {key}: ")
[Link](value)
data_dict[key] = values
# Convert the dictionary to a pandas DataFrame
df = [Link](data_dict)
# Print the first few rows of the DataFrame using head()
print("First few rows of the DataFrame:")
print([Link]())
# Perform various data selection operations
print("\nSelecting specific columns:")
user_input_columns = input("Enter column names (separated by commas): ")
columns = [[Link]() for col in user_input_columns.split(',')]
print(df[columns])
print("\nSelecting specific rows:")
user_input_rows = input("Enter row indices (separated by commas): ")
rows = [int([Link]()) for row in user_input_rows.split(',')]
print([Link][rows])
print("\nSelecting specific rows and columns:")
user_input_rows = input("Enter row indices (separated by commas): ")
user_input_columns = input("Enter column names (separated by commas): ")
rows = [int([Link]()) for row in user_input_rows.split(',')]
columns = [[Link]() for col in user_input_columns.split(',')]
print([Link][rows, columns])
print("\nFiltering data based on conditions:")
user_input_condition = input("Enter a condition (e.g., A > 5): ")
print([Link](user_input_condition))
Output:
Program-30:
Aim: Select any two columns from the above data frame, and observe the change in
one attribute with respect to other attribute with scatter and plot operations in matplotlib
Program:
import pandas as pd
import [Link] as plt
# the DataFrame ffrom the above program
data = {
'A': [1, 2, 3, 4, 5],
'B': ['a', 'b', 'c', 'd', 'e'],
'C': [10.1, 20.2, 30.3, 40.4, 50.5],
'D': [True, False, True, False, True],
'E': ['apple', 'banana', 'cherry', 'date', 'elderberry']
}
df = [Link](data)
# Get the column names
column_names = list([Link])
# Ask the user to select two columns
print("Select two columns:")
for i, column in enumerate(column_names):
print("{}. {}".format(i+1, column))
column1_index = int(input("Enter the number of the first column: ")) - 1
column2_index = int(input("Enter the number of the second column: ")) - 1
column1 = column_names[column1_index]
column2 = column_names[column2_index]
# Create a scatter plot
[Link](figsize=(10, 6))
[Link](df[column1], df[column2])
[Link](column1)
[Link](column2)
[Link]('Scatter Plot of {} vs {}'.format(column1, column2))
[Link]()
# Create a line plot
[Link](figsize=(10, 6))
[Link](df[column1], df[column2], marker='o')
[Link](column1)
[Link](column2)
[Link]('Line Plot of {} vs {}'.format(column1, column2))
[Link]()
Output: